model_manager.py 3.4 KB

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