暫無描述
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

lefactory.py 4.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. #-*- coding: utf-8 -*-
  2. import functools
  3. from lodel.editorial_model.components import *
  4. from lodel.leapi.leobject import LeObject
  5. from lodel.leapi.datahandlers.base_classes import DataHandler
  6. ##@brief Generate python module code from a given model
  7. # @param model lodel.editorial_model.model.EditorialModel
  8. def dyncode_from_em(model):
  9. # Generation of LeObject child classes code
  10. cls_code, modules, bootstrap_instr = generate_classes(model)
  11. # Header
  12. imports = """from lodel.leapi.leobject import LeObject
  13. from lodel.leapi.datahandlers.base_classes import DataField
  14. """
  15. for module in modules:
  16. imports += "import %s\n" % module
  17. # formating all components of output
  18. res_code = """#-*- coding: utf-8 -*-
  19. {imports}
  20. {classes}
  21. {bootstrap_instr}
  22. """.format(
  23. imports = imports,
  24. classes = cls_code,
  25. bootstrap_instr = bootstrap_instr,
  26. )
  27. return res_code
  28. ##@brief return A list of EmClass sorted by dependencies
  29. #
  30. # The first elts in the list depends on nothing, etc.
  31. # @return a list of EmClass instances
  32. def emclass_sorted_by_deps(emclass_list):
  33. def emclass_deps_cmp(cls_a, cls_b):
  34. return len(cls_a.parents_recc) - len(cls_b.parents_recc)
  35. ret = sorted(emclass_list, key = functools.cmp_to_key(emclass_deps_cmp))
  36. return ret
  37. ##@brief Returns a list of EmClass that will be represented as LeObject child classes
  38. def get_classes(model):
  39. return [ cls for cls in emclass_sorted_by_deps(model.classes()) if not cls.pure_abstract ]
  40. ##@brief Given an EmField returns the data_handler constructor suitable for dynamic code
  41. def data_handler_constructor(emfield):
  42. #dh_module_name = DataHandler.module_name(emfield.data_handler_name)+'.DataHandler'
  43. get_handler_class_instr = 'DataField.from_name(%s)' % repr(emfield.data_handler_name)
  44. options = []
  45. for name, val in emfield.data_handler_options.items():
  46. if name == 'back_reference' and isinstance(val, tuple):
  47. options.append('{optname}: ({leo_name}, {fieldname})'.format(
  48. optname = repr(name),
  49. leo_name = LeObject.name2objname(val[0]),
  50. fieldname = repr(val[1]),))
  51. else:
  52. options.append(repr(name)+': '+forge_optval(val))
  53. return '{handler_instr}(**{{ {options} }})'.format(
  54. handler_instr = get_handler_class_instr,
  55. options = ', '.join(options))
  56. ##@brief Return a python repr of option values
  57. def forge_optval(optval):
  58. if isinstance(optval, dict):
  59. return '{' + (', '.join( [ '%s: %s' % (repr(name), forge_optval(val)) for name, val in optval.items()])) + '}'
  60. if isinstance(optval, (set, list, tuple)):
  61. return '[' + (', '.join([forge_optval(val) for val in optval])) + ']'
  62. if isinstance(optval, EmField):
  63. return "{leobject}.data_handler({fieldname})".format(
  64. leobject = LeObject.name2objname(optval._emclass.uid),
  65. fieldname = repr(optval.uid)
  66. )
  67. elif isinstance(optval, EmClass):
  68. return LeObject.name2objname(optval.uid)
  69. else:
  70. return repr(optval)
  71. ##@brief Generate dyncode from an EmClass
  72. # @param model EditorialModel :
  73. # @param emclass EmClass : EmClass instance
  74. # @return a tuple with emclass python code, a set containing modules name to import, and a list of python instruction to bootstrap dynamic code, in this order
  75. def generate_classes(model):
  76. res = ""
  77. imports = list()
  78. bootstrap = ""
  79. # Generating field list for LeObjects generated from EmClass
  80. for em_class in get_classes(model):
  81. uid = list() # List of fieldnames that are part of the EmClass primary key
  82. parents = list() # List of parents EmClass
  83. # Determine pk
  84. for field in em_class.fields():
  85. if field.data_handler_instance.is_primary_key():
  86. uid.append(field.uid)
  87. # Determine parent for inheritance
  88. if len(em_class.parents) > 0:
  89. for parent in em_class.parents:
  90. parents.append(LeObject.name2objname(parent.uid))
  91. else:
  92. parents.append('LeObject')
  93. # Dynamic code generation for LeObject childs classes
  94. em_cls_code = """
  95. class {clsname}({parents}):
  96. _abstract = {abstract}
  97. _fields = None
  98. _uid = {uid_list}
  99. """.format(
  100. clsname = LeObject.name2objname(em_class.uid),
  101. parents = ', '.join(parents),
  102. abstract = 'True' if em_class.abstract else 'False',
  103. uid_list = repr(uid),
  104. )
  105. res += em_cls_code
  106. # Dyncode bootstrap instructions
  107. bootstrap += """{classname}._set__fields({fields})
  108. """.format(
  109. classname = LeObject.name2objname(em_class.uid),
  110. fields = '{' + (', '.join(['\n\t%s: %s' % (repr(emfield.uid),data_handler_constructor(emfield)) for emfield in em_class.fields()])) + '}',
  111. )
  112. return res, set(imports), bootstrap