Nessuna descrizione
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 6.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. #-*- coding: utf-8 -*-
  2. import os, os.path
  3. import functools
  4. from lodel.context import LodelContext
  5. LodelContext.expose_modules(globals(), {
  6. 'lodel.editorial_model.components': ['EmComponent', 'EmClass', 'EmField',
  7. 'EmGroup'],
  8. 'lodel.leapi.leobject': ['LeObject'],
  9. 'lodel.leapi.datahandlers.base_classes': ['DataHandler'],
  10. 'lodel.logger': 'logger'})
  11. ##@brief Generate python module code from a given model
  12. # @param model lodel.editorial_model.model.EditorialModel
  13. def dyncode_from_em(model):
  14. # Generation of LeObject child classes code
  15. cls_code, modules, bootstrap_instr = generate_classes(model)
  16. # Header
  17. imports = """from lodel.context import LodelContext
  18. LodelContext.expose_modules(globals(), {
  19. 'lodel.leapi.leobject': ['LeObject'],
  20. 'lodel.leapi.datahandlers.base_classes': ['DataField'],
  21. 'lodel.plugin.hooks': ['LodelHook']})
  22. """
  23. for module in modules:
  24. imports += "import %s\n" % module
  25. class_list = [ LeObject.name2objname(cls.uid) for cls in get_classes(model) ]
  26. # formating all components of output
  27. res_code = """#-*- coding: utf-8 -*-
  28. {imports}
  29. {classes}
  30. {bootstrap_instr}
  31. #List of dynamically generated classes
  32. dynclasses = {class_list}
  33. #Dict of dynamically generated classes indexed by name
  34. dynclasses_dict = {class_dict}
  35. {common_code}
  36. """.format(
  37. imports = imports,
  38. classes = cls_code,
  39. bootstrap_instr = bootstrap_instr,
  40. class_list = '[' + (', '.join([cls for cls in class_list]))+']',
  41. class_dict = '{' + (', '.join([ "'%s': %s" % (cls, cls)
  42. for cls in class_list]))+'}',
  43. common_code = common_code(),
  44. )
  45. return res_code
  46. ##@brief Return the content of lodel.leapi.lefactory_common
  47. def common_code():
  48. res = ""
  49. fname = os.path.dirname(__file__)
  50. fname = os.path.join(fname, 'lefactory_common.py')
  51. with open(fname, 'r') as cfp:
  52. for line in cfp:
  53. if not line.startswith('#-'):
  54. res += line
  55. return res
  56. ##@brief return A list of EmClass sorted by dependencies
  57. #
  58. # The first elts in the list depends on nothing, etc.
  59. # @return a list of EmClass instances
  60. def emclass_sorted_by_deps(emclass_list):
  61. def emclass_deps_cmp(cls_a, cls_b):
  62. return len(cls_a.parents_recc) - len(cls_b.parents_recc)
  63. ret = sorted(emclass_list, key = functools.cmp_to_key(emclass_deps_cmp))
  64. return ret
  65. ##@brief Returns a list of EmClass that will be represented as LeObject child classes
  66. def get_classes(model):
  67. return [ cls for cls in emclass_sorted_by_deps(model.classes()) if not cls.pure_abstract ]
  68. ##@brief Given an EmField returns the data_handler constructor suitable for dynamic code
  69. def data_handler_constructor(emfield):
  70. #dh_module_name = DataHandler.module_name(emfield.data_handler_name)+'.DataHandler'
  71. get_handler_class_instr = 'DataField.from_name(%s)' % repr(emfield.data_handler_name)
  72. options = []
  73. for name, val in emfield.data_handler_options.items():
  74. if name == 'back_reference' and isinstance(val, tuple):
  75. options.append('{optname}: ({leo_name}, {fieldname})'.format(
  76. optname = repr(name),
  77. leo_name = LeObject.name2objname(val[0]),
  78. fieldname = repr(val[1]),))
  79. else:
  80. options.append(repr(name)+': '+forge_optval(val))
  81. return '{handler_instr}(**{{ {options} }})'.format(
  82. handler_instr = get_handler_class_instr,
  83. options = ', '.join(options))
  84. ##@brief Return a python repr of option values
  85. def forge_optval(optval):
  86. if isinstance(optval, dict):
  87. return '{' + (', '.join( [ '%s: %s' % (repr(name), forge_optval(val)) for name, val in optval.items()])) + '}'
  88. if isinstance(optval, (set, list, tuple)):
  89. return '[' + (', '.join([forge_optval(val) for val in optval])) + ']'
  90. if isinstance(optval, EmField):
  91. return "{leobject}.data_handler({fieldname})".format(
  92. leobject = LeObject.name2objname(optval._emclass.uid),
  93. fieldname = repr(optval.uid)
  94. )
  95. elif isinstance(optval, EmClass):
  96. return LeObject.name2objname(optval.uid)
  97. else:
  98. return repr(optval)
  99. ##@brief Generate dyncode from an EmClass
  100. # @param model EditorialModel :
  101. # @todo delete imports. It is never use, consequently changed return parameters.
  102. # @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
  103. def generate_classes(model):
  104. res = ""
  105. imports = list()
  106. bootstrap = ""
  107. # Generating field list for LeObjects generated from EmClass
  108. for em_class in get_classes(model):
  109. logger.info("Generating a dynamic class for %s" % em_class.uid)
  110. uid = list() # List of fieldnames that are part of the EmClass primary key
  111. parents = list() # List of parents EmClass
  112. # Determine pk
  113. for field in em_class.fields():
  114. if field.data_handler_instance.is_primary_key():
  115. uid.append(field.uid)
  116. # Determine parent for inheritance
  117. if len(em_class.parents) > 0:
  118. for parent in em_class.parents:
  119. parents.append(LeObject.name2objname(parent.uid))
  120. else:
  121. parents.append('LeObject')
  122. datasource_name = em_class.datasource
  123. # Dynamic code generation for LeObject childs classes
  124. em_cls_code = """
  125. class {clsname}({parents}):
  126. _abstract = {abstract}
  127. _fields = None
  128. _uid = {uid_list}
  129. _ro_datasource = None
  130. _rw_datasource = None
  131. _datasource_name = {datasource_name}
  132. _child_classes = None
  133. """.format(
  134. clsname = LeObject.name2objname(em_class.uid),
  135. parents = ', '.join(parents),
  136. abstract = 'True' if em_class.abstract else 'False',
  137. uid_list = repr(uid),
  138. datasource_name = repr(datasource_name),
  139. )
  140. res += em_cls_code
  141. # Dyncode fields bootstrap instructions
  142. child_classes = model.get_class_childs(em_class.uid)
  143. if len(child_classes) == 0:
  144. child_classes = 'tuple()'
  145. else:
  146. child_classes = '(%s,)' % (', '.join(
  147. [ LeObject.name2objname(emcls.uid) for emcls in child_classes]))
  148. bootstrap += """{classname}._set__fields({fields})
  149. {classname}._child_classes = {child_classes}
  150. """.format(
  151. classname = LeObject.name2objname(em_class.uid),
  152. fields = '{' + (', '.join(['\n\t%s: %s' % (repr(emfield.uid),data_handler_constructor(emfield)) for emfield in em_class.fields()])) + '}',
  153. child_classes = child_classes,
  154. )
  155. bootstrap += "\n"
  156. return res, set(imports), bootstrap