model_manager.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. from pyexpat import model
  2. from sys import modules
  3. from tokenize import String
  4. from sqlalchemy.ext.declarative import DeclarativeMeta
  5. from sqlalchemy import null
  6. from utility.app_logging import *
  7. import json
  8. from werkzeug.security import generate_password_hash
  9. from utility.app_logging import logger_name
  10. import logging
  11. logger = logging.getLogger(logger_name + ".MODEL")
  12. def declare_model():
  13. # insert here all model that need to be declared
  14. # the fact import models files
  15. # OpenISP Core Model
  16. import Model.isp_model
  17. # OpenISP Inventory Model
  18. import Modules.Inventory.inventory_model
  19. def init() :
  20. import Model.isp_model
  21. import persistence
  22. import Modules.Inventory.inventory_model
  23. with persistence.get_Session_Instance() as sess : ##TODO maybe not the best place to perform that
  24. Item = sess.query(Model.isp_model.user_account).filter(Model.isp_model.user_account.nickname == "admin").first()
  25. if not isinstance(Item,Model.isp_model.user_account):
  26. Item = Model.isp_model.user_account(id = 1, nickname = "admin",description = "admin account", is_super_admin = True,password = generate_password_hash("aseqzdwxc"))
  27. obj = Modules.Inventory.inventory_model.inventory_item(name = "mikrotik rb2011 saline 1",brand= "mikrotik",note="router saline2")
  28. sess.add(Item)
  29. sess.add(obj)
  30. sess.commit()
  31. logger.debug("Admin account created")
  32. else :
  33. logger.debug("Admin account already created")
  34. # from https://stackoverflow.com/questions/5022066/how-to-serialize-sqlalchemy-result-to-json
  35. class ComplexEncoder(json.JSONEncoder):
  36. def default(self, obj):
  37. if isinstance(obj.__class__, DeclarativeMeta):
  38. # an SQLAlchemy class
  39. fields = {}
  40. for field in [x for x in dir(obj) if not x.startswith('_') and x != 'metadata']:
  41. data = obj.__getattribute__(field)
  42. try:
  43. # this will fail on non-encodable values, like other classes
  44. json.dumps(data)
  45. fields[field] = data
  46. except TypeError:
  47. fields[field] = None
  48. # a json-encodable dict
  49. return fields
  50. return json.JSONEncoder.default(self, obj)
  51. # from https://howtodoinjava.com/json/custom-deserialization/
  52. class ComplexDecoder(json.JSONDecoder):
  53. def __init__(self):
  54. json.JSONDecoder.__init__(
  55. self,
  56. object_hook=self.dict_to_object,
  57. )
  58. def dict_to_object(self, d):
  59. if '__class__' in d:
  60. class_name = d.pop('__class__')
  61. module_name = d.pop('__module__')
  62. module = __import__(module_name)
  63. class_ = getattr(module, class_name)
  64. args = {
  65. key: value
  66. for key, value in d.items()
  67. }
  68. inst = class_(**args)
  69. else:
  70. inst = d
  71. return inst
  72. def setModelItemAttributesFromJson(Item, JsonString):
  73. attributes_dict = null
  74. try:
  75. attributes_dict = json.loads(
  76. JsonString, cls=ComplexDecoder)
  77. except:
  78. raise "input is not a Json String"
  79. # verification of attribute
  80. """ for key in attributes_dict:
  81. print(key)
  82. print (Item.__dict__)
  83. if not key in Item.__dict__ :
  84. raise "one input attribute is not an attribute of the destination object" """
  85. # TODO later verify json schema ?
  86. for key in attributes_dict:
  87. setattr(Item, key, attributes_dict[key])
  88. def ModelObjectToJsonString(object) -> str:
  89. json_string = json.dumps(object, cls=ComplexEncoder)
  90. json_dict : dict = json.loads(json_string)
  91. json_dict.pop("registry") # removing the registry item that comes from the sql alchemy type.
  92. json_string = json.dumps(json_dict)
  93. assert isinstance(json_string,str)
  94. return json_string