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 13KB

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