model_manager.py 3.7 KB

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