No Description
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 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. #-*- coding: utf-8 -*-
  2. import importlib
  3. import copy
  4. import os.path
  5. import EditorialModel
  6. from EditorialModel.model import Model
  7. from EditorialModel.fieldtypes.generic import GenericFieldType
  8. from leapi.lecrud import _LeCrud
  9. ## @brief This class is designed to generated the leobject API given an EditorialModel.model
  10. # @note Contains only static methods
  11. #
  12. # The name is not good but i've no other ideas for the moment
  13. class LeFactory(object):
  14. output_file = 'dyn.py'
  15. modname = None
  16. def __init__(self, code_filename = 'leapi/dyn.py'):
  17. self._code_filename = code_filename
  18. self._dyn_file = os.path.basename(code_filename)
  19. self._modname = os.path.dirname(code_filename).strip('/').replace('/', '.') #Warning Windaube compatibility
  20. ## @brief Return a call to a FieldType constructor given an EmField
  21. # @param emfield EmField : An EmField
  22. # @return a string representing the python code to instanciate a EmFieldType
  23. @staticmethod
  24. def fieldtype_construct_from_field(emfield):
  25. return '%s.EmFieldType(**%s)' % (
  26. GenericFieldType.module_name(emfield.fieldtype),
  27. repr(emfield._fieldtype_args),
  28. )
  29. ## @brief Write generated code to a file
  30. # @todo better options/params for file creation
  31. def create_pyfile(self, model, datasource_cls, datasource_args):
  32. with open(self._code_filename, "w+") as dynfp:
  33. dynfp.write(self.generate_python(model, datasource_cls, datasource_args))
  34. ## @brief Generate fieldtypes for concret classes
  35. # @param ft_dict dict : key = fieldname value = fieldtype __init__ args
  36. # @return (uid_fieldtypes, fieldtypes) designed to be printed in generated code
  37. def concret_fieldtypes(self, ft_dict):
  38. res_ft_l = list()
  39. res_uid_ft = None
  40. for fname, ftargs in ft_dict.items():
  41. ftargs = copy.copy(ftargs)
  42. fieldtype = ftargs['fieldtype']
  43. self.needed_fieldtypes |= set([fieldtype])
  44. del(ftargs['fieldtype'])
  45. constructor = '{ftname}.EmFieldType(**{ftargs})'.format(
  46. ftname = GenericFieldType.module_name(fieldtype),
  47. ftargs = ftargs,
  48. )
  49. if fieldtype == 'pk':
  50. #
  51. # WARNING multiple PK not supported
  52. #
  53. res_uid_ft = "{ %s: %s }"%(repr(fname),constructor)
  54. else:
  55. res_ft_l.append( '%s: %s'%(repr(fname), constructor) )
  56. return (res_uid_ft, res_ft_l)
  57. ## @brief Given a Model generate concrete instances of LeRel2Type classes to represent relations
  58. # @param model : the EditorialModel
  59. # @return python code
  60. def emrel2type_pycode(self, model):
  61. res_code = ""
  62. for field in [ f for f in model.components('EmField') if f.fieldtype == 'rel2type']:
  63. related = model.component(field.rel_to_type_id)
  64. src = field.em_class
  65. cls_name = _LeCrud.name2rel2type(src.name, related.name)
  66. attr_l = dict()
  67. for attr in [ f for f in model.components('EmField') if f.rel_field_id == field.uid]:
  68. attr_l[attr.name] = LeFactory.fieldtype_construct_from_field(attr)
  69. rel_code = """
  70. class {classname}(LeRel2Type):
  71. _rel_attr_fieldtypes = {attr_dict}
  72. _superior_cls = {supcls}
  73. _subordinate_cls = {subcls}
  74. """.format(
  75. classname = cls_name,
  76. attr_dict = "{" + (','.join(['\n %s: %s' % (repr(f), v) for f,v in attr_l.items()])) + "\n}",
  77. supcls = _LeCrud.name2classname(src.name),
  78. subcls = _LeCrud.name2classname(related.name),
  79. )
  80. res_code += rel_code
  81. return res_code
  82. ## @brief Given a Model and an EmClass instances generate python code for corresponding LeClass
  83. # @param model Model : A Model instance
  84. # @param emclass EmClass : An EmClass instance from model
  85. # @return A string representing the python code for the corresponding LeClass child class
  86. def emclass_pycode(self, model, emclass):
  87. cls_fields = dict()
  88. cls_linked_types = list() #Stores authorized LeObject for rel2type
  89. #Populating linked_type attr
  90. for rfield in [ f for f in emclass.fields() if f.fieldtype == 'rel2type']:
  91. fti = rfield.fieldtype_instance()
  92. cls_linked_types.append(_LeCrud.name2classname(model.component(fti.rel_to_type_id).name))
  93. # Populating fieldtype attr
  94. for field in emclass.fields(relational = False):
  95. self.needed_fieldtypes |= set([field.fieldtype])
  96. cls_fields[field.name] = LeFactory.fieldtype_construct_from_field(field)
  97. fti = field.fieldtype_instance()
  98. return """
  99. #Initialisation of {name} class attributes
  100. {name}._fieldtypes = {ftypes}
  101. {name}._linked_types = {ltypes}
  102. {name}._classtype = {classtype}
  103. """.format(
  104. name = _LeCrud.name2classname(emclass.name),
  105. ftypes = "{" + (','.join(['\n %s: %s' % (repr(f), v) for f, v in cls_fields.items()])) + "\n}",
  106. ltypes = "[" + (','.join(cls_linked_types))+"]",
  107. classtype = repr(emclass.classtype)
  108. )
  109. ## @brief Given a Model and an EmType instances generate python code for corresponding LeType
  110. # @param model Model : A Model instance
  111. # @param emtype EmType : An EmType instance from model
  112. # @return A string representing the python code for the corresponding LeType child class
  113. def emtype_pycode(self, model, emtype):
  114. type_fields = list()
  115. type_superiors = list()
  116. for field in emtype.fields(relational=False):
  117. type_fields.append(field.name)
  118. for nat, sup_l in emtype.superiors().items():
  119. type_superiors.append('%s: [%s]' % (
  120. repr(nat),
  121. ', '.join([_LeCrud.name2classname(sup.name) for sup in sup_l])
  122. ))
  123. return """
  124. #Initialisation of {name} class attributes
  125. {name}._fields = {fields}
  126. {name}._superiors = {dsups}
  127. {name}._leclass = {leclass}
  128. """.format(
  129. name=_LeCrud.name2classname(emtype.name),
  130. fields=repr(type_fields),
  131. dsups='{' + (', '.join(type_superiors)) + '}',
  132. leclass=_LeCrud.name2classname(emtype.em_class.name)
  133. )
  134. ## @brief Generate python code containing the LeObject API
  135. # @param model EditorialModel.model.Model : An editorial model instance
  136. # @param datasource_cls Datasource : A datasource class
  137. # @param datasource_args dict : A dict representing arguments for datasource_cls instanciation
  138. # @return A string representing python code
  139. def generate_python(self, model, datasource_cls, datasource_args):
  140. self.needed_fieldtypes = set() #Stores the list of fieldtypes that will be used by generated code
  141. model = model
  142. result = ""
  143. #result += "#-*- coding: utf-8 -*-\n"
  144. #Putting import directives in result
  145. heading = """## @author LeFactory
  146. import EditorialModel
  147. from EditorialModel import fieldtypes
  148. from EditorialModel.fieldtypes import {needed_fieldtypes_list}
  149. import leapi
  150. import leapi.lecrud
  151. import leapi.leobject
  152. import leapi.lerelation
  153. from leapi.leclass import _LeClass
  154. from leapi.letype import _LeType
  155. """
  156. result += """
  157. import %s
  158. """ % (datasource_cls.__module__)
  159. #Generating the code for LeObject class
  160. leobj_me_uid = dict()
  161. for comp in model.components('EmType') + model.components('EmClass'):
  162. leobj_me_uid[comp.uid] = _LeCrud.name2classname(comp.name)
  163. #Building the fieldtypes dict of LeObject
  164. (leobj_uid_fieldtype, leobj_fieldtypes) = self.concret_fieldtypes(EditorialModel.classtypes.common_fields)
  165. #Building the fieldtypes dict for LeRelation
  166. (lerel_uid_fieldtype, lerel_fieldtypes) = self.concret_fieldtypes(EditorialModel.classtypes.relations_common_fields)
  167. # Fetching superior and subordinate fieldname for LeRelation
  168. lesup = None
  169. lesub = None
  170. for fname, finfo in EditorialModel.classtypes.relations_common_fields.items():
  171. if finfo['fieldtype'] == 'leo':
  172. if finfo['superior']:
  173. lesup = fname
  174. else:
  175. lesub = fname
  176. # Fetch class_id and type_id fieldnames for LeObject
  177. class_id = None
  178. type_id = None
  179. for fname, finfo in EditorialModel.classtypes.common_fields.items():
  180. if finfo['fieldtype'] == 'emuid':
  181. if finfo['is_id_class']:
  182. class_id = fname
  183. else:
  184. type_id = fname
  185. # TEST IF SOME OF THE ARE NONE !!!
  186. result += """
  187. ## @brief _LeCrud concret class
  188. # @see leapi.lecrud._LeCrud
  189. class LeCrud(leapi.lecrud._LeCrud):
  190. _datasource = {ds_classname}(**{ds_kwargs})
  191. _uid_fieldtype = None
  192. ## @brief _LeObject concret class
  193. # @see leapi.leobject._LeObject
  194. class LeObject(LeCrud, leapi.leobject._LeObject):
  195. _me_uid = {me_uid_l}
  196. _me_uid_field_names = ({class_id}, {type_id})
  197. _uid_fieldtype = {leo_uid_fieldtype}
  198. _leo_fieldtypes = {leo_fieldtypes}
  199. ## @brief _LeRelation concret class
  200. # @see leapi.lerelation._LeRelation
  201. class LeRelation(LeCrud, leapi.lerelation._LeRelation):
  202. _uid_fieldtype = {lerel_uid_fieldtype}
  203. _rel_fieldtypes = {lerel_fieldtypes}
  204. _superior_field_name = {lesup_name}
  205. _subordinate_field_name = {lesub_name}
  206. class LeHierarch(LeRelation, leapi.lerelation._LeHierarch):
  207. pass
  208. class LeRel2Type(LeRelation, leapi.lerelation._LeRel2Type):
  209. pass
  210. class LeClass(LeObject, _LeClass):
  211. pass
  212. class LeType(LeClass, _LeType):
  213. pass
  214. """.format(
  215. ds_classname = datasource_cls.__module__ + '.' + datasource_cls.__name__,
  216. ds_kwargs = repr(datasource_args),
  217. me_uid_l = repr(leobj_me_uid),
  218. leo_uid_fieldtype = leobj_uid_fieldtype,
  219. leo_fieldtypes = '{\n\t' + (',\n\t'.join(leobj_fieldtypes))+ '\n\t}',
  220. lerel_fieldtypes = '{\n\t' + (',\n\t'.join(lerel_fieldtypes))+ '\n\t}',
  221. lerel_uid_fieldtype = lerel_uid_fieldtype,
  222. lesup_name = repr(lesup),
  223. lesub_name = repr(lesub),
  224. class_id = repr(class_id),
  225. type_id = repr(type_id),
  226. )
  227. emclass_l = model.components(EditorialModel.classes.EmClass)
  228. emtype_l = model.components(EditorialModel.types.EmType)
  229. #LeClass child classes definition
  230. for emclass in emclass_l:
  231. result += """
  232. ## @brief EmClass {name} LeClass child class
  233. # @see leapi.leclass.LeClass
  234. class {name}(LeClass, LeObject):
  235. _class_id = {uid}
  236. """.format(
  237. name=_LeCrud.name2classname(emclass.name),
  238. uid=emclass.uid
  239. )
  240. #LeType child classes definition
  241. for emtype in emtype_l:
  242. result += """
  243. ## @brief EmType {name} LeType child class
  244. # @see leobject::letype::LeType
  245. class {name}(LeType, {leclass}):
  246. _type_id = {uid}
  247. """.format(
  248. name=_LeCrud.name2classname(emtype.name),
  249. leclass=_LeCrud.name2classname(emtype.em_class.name),
  250. uid=emtype.uid
  251. )
  252. #Generating concret class of LeRel2Type
  253. result += self.emrel2type_pycode(model)
  254. #Set attributes of created LeClass and LeType child classes
  255. for emclass in emclass_l:
  256. result += self.emclass_pycode(model, emclass)
  257. for emtype in emtype_l:
  258. result += self.emtype_pycode(model, emtype)
  259. #Populating LeObject._me_uid dict for a rapid fetch of LeType and LeClass given an EM uid
  260. me_uid = {comp.uid: _LeCrud.name2classname(comp.name) for comp in emclass_l + emtype_l}
  261. result += """
  262. ## @brief Dict for getting LeClass and LeType child classes given an EM uid
  263. LeObject._me_uid = %s""" % "{" + (', '.join(['%s: %s' % (k, v) for k, v in me_uid.items()])) + "}"
  264. result += "\n"
  265. heading = heading.format(needed_fieldtypes_list = ', '.join(self.needed_fieldtypes))
  266. result = heading + result
  267. del(self.needed_fieldtypes)
  268. return result