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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. ml_fieldnames = dict()
  101. # Populating fieldtype attr
  102. for field in emclass.fields(relational = False):
  103. if field.name not in EditorialModel.classtypes.common_fields.keys() or not ( hasattr(field, 'immutable') and field.immutable):
  104. self.needed_fieldtypes |= set([field.fieldtype])
  105. cls_fields[field.name] = LeFactory.fieldtype_construct_from_field(field)
  106. fti = field.fieldtype_instance()
  107. if field.string.get() == '':
  108. field.string.set_default(field.name)
  109. ml_fieldnames[field.name] = field.string.__str__()
  110. return """
  111. #Initialisation of {name} class attributes
  112. {name}._fieldtypes = {ftypes}
  113. {name}.ml_fields_strings = {fieldnames}
  114. {name}._linked_types = {ltypes}
  115. {name}._classtype = {classtype}
  116. """.format(
  117. name = _LeCrud.name2classname(emclass.name),
  118. ftypes = "{" + (','.join(['\n %s: %s' % (repr(f), v) for f, v in cls_fields.items()])) + "\n}",
  119. fieldnames = '{' + (','.join(['\n %s: MlString(%s)' % (repr(f), v) for f,v in ml_fieldnames.items()])) + '\n}',
  120. ltypes = "{" + (','.join(['\n %s: %s' % (repr(f), v) for f, v in cls_linked_types.items()])) + "\n}",
  121. classtype = repr(emclass.classtype),
  122. )
  123. ## @brief Given a Model and an EmType instances generate python code for corresponding LeType
  124. # @param model Model : A Model instance
  125. # @param emtype EmType : An EmType instance from model
  126. # @return A string representing the python code for the corresponding LeType child class
  127. def emtype_pycode(self, model, emtype):
  128. type_fields = list()
  129. type_superiors = list()
  130. for field in emtype.fields(relational=False):
  131. if not field.name in EditorialModel.classtypes.common_fields:
  132. type_fields.append(field.name)
  133. for nat, sup_l in emtype.superiors().items():
  134. type_superiors.append('%s: [%s]' % (
  135. repr(nat),
  136. ', '.join([_LeCrud.name2classname(sup.name) for sup in sup_l])
  137. ))
  138. return """
  139. #Initialisation of {name} class attributes
  140. {name}._fields = {fields}
  141. {name}._superiors = {dsups}
  142. {name}._leclass = {leclass}
  143. """.format(
  144. name=_LeCrud.name2classname(emtype.name),
  145. fields=repr(type_fields),
  146. dsups='{' + (', '.join(type_superiors)) + '}',
  147. leclass=_LeCrud.name2classname(emtype.em_class.name)
  148. )
  149. ## @brief Generate python code containing the LeObject API
  150. # @param model EditorialModel.model.Model : An editorial model instance
  151. # @param datasource_cls Datasource : A datasource class
  152. # @param datasource_args dict : A dict representing arguments for datasource_cls instanciation
  153. # @return A string representing python code
  154. def generate_python(self, model, datasource_cls, datasource_args):
  155. self.needed_fieldtypes = set() #Stores the list of fieldtypes that will be used by generated code
  156. model = model
  157. result = ""
  158. #result += "#-*- coding: utf-8 -*-\n"
  159. #Putting import directives in result
  160. heading = """## @author LeFactory
  161. import EditorialModel
  162. from EditorialModel import fieldtypes
  163. from EditorialModel.fieldtypes import {needed_fieldtypes_list}
  164. from Lodel.utils.mlstring import MlString
  165. import leapi
  166. import leapi.lecrud
  167. import leapi.leobject
  168. import leapi.lerelation
  169. from leapi.leclass import _LeClass
  170. from leapi.letype import _LeType
  171. """
  172. result += """
  173. import %s
  174. """ % (datasource_cls.__module__)
  175. #Generating the code for LeObject class
  176. leobj_me_uid = dict()
  177. for comp in model.components('EmType') + model.components('EmClass'):
  178. leobj_me_uid[comp.uid] = _LeCrud.name2classname(comp.name)
  179. #Building the fieldtypes dict of LeObject
  180. common_fieldtypes = dict()
  181. for ftname, ftdef in EditorialModel.classtypes.common_fields.items():
  182. common_fieldtypes[ftname] = ftdef if 'immutable' in ftdef and ftdef['immutable'] else None
  183. (leobj_uid_fieldtype, leobj_fieldtypes) = self.concret_fieldtypes(common_fieldtypes)
  184. #Building the fieldtypes dict for LeRelation
  185. common_fieldtypes = dict()
  186. for ftname, ftdef in EditorialModel.classtypes.relations_common_fields.items():
  187. common_fieldtypes[ftname] = ftdef if 'immutable' in ftdef and ftdef['immutable'] else None
  188. (lerel_uid_fieldtype, lerel_fieldtypes) = self.concret_fieldtypes(common_fieldtypes)
  189. result += """
  190. ## @brief _LeCrud concret class
  191. # @see leapi.lecrud._LeCrud
  192. class LeCrud(leapi.lecrud._LeCrud):
  193. _datasource = {ds_classname}(**{ds_kwargs})
  194. _uid_fieldtype = None
  195. ## @brief _LeObject concret class
  196. # @see leapi.leobject._LeObject
  197. class LeObject(LeCrud, leapi.leobject._LeObject):
  198. _me_uid = {me_uid_l}
  199. _me_uid_field_names = ({class_id}, {type_id})
  200. _uid_fieldtype = {leo_uid_fieldtype}
  201. _leo_fieldtypes = {leo_fieldtypes}
  202. ## @brief _LeRelation concret class
  203. # @see leapi.lerelation._LeRelation
  204. class LeRelation(LeCrud, leapi.lerelation._LeRelation):
  205. _uid_fieldtype = {lerel_uid_fieldtype}
  206. _rel_fieldtypes = {lerel_fieldtypes}
  207. ## WARNING !!!! OBSOLETE ! DON'T USE IT
  208. _superior_field_name = {lesup_name}
  209. ## WARNING !!!! OBSOLETE ! DON'T USE IT
  210. _subordinate_field_name = {lesub_name}
  211. class LeHierarch(LeRelation, leapi.lerelation._LeHierarch):
  212. pass
  213. class LeRel2Type(LeRelation, leapi.lerelation._LeRel2Type):
  214. pass
  215. class LeClass(LeObject, _LeClass):
  216. pass
  217. class LeType(LeClass, _LeType):
  218. pass
  219. """.format(
  220. ds_classname = datasource_cls.__module__ + '.' + datasource_cls.__name__,
  221. ds_kwargs = repr(datasource_args),
  222. me_uid_l = repr(leobj_me_uid),
  223. leo_uid_fieldtype = leobj_uid_fieldtype,
  224. leo_fieldtypes = '{\n\t' + (',\n\t'.join(leobj_fieldtypes))+ '\n\t}',
  225. lerel_fieldtypes = '{\n\t' + (',\n\t'.join(lerel_fieldtypes))+ '\n\t}',
  226. lerel_uid_fieldtype = lerel_uid_fieldtype,
  227. lesup_name = repr(classtypes.relation_superior),
  228. lesub_name = repr(classtypes.relation_subordinate),
  229. class_id = repr(classtypes.object_em_class_id),
  230. type_id = repr(classtypes.object_em_type_id),
  231. )
  232. emclass_l = model.components(EditorialModel.classes.EmClass)
  233. emtype_l = model.components(EditorialModel.types.EmType)
  234. #LeClass child classes definition
  235. for emclass in emclass_l:
  236. if emclass.string.get() == '':
  237. emclass.string.set_default(emclass.name)
  238. result += """
  239. ## @brief EmClass {name} LeClass child class
  240. # @see leapi.leclass.LeClass
  241. class {name}(LeClass, LeObject):
  242. _class_id = {uid}
  243. ml_string = MlString({name_translations})
  244. """.format(
  245. name=_LeCrud.name2classname(emclass.name),
  246. uid=emclass.uid,
  247. name_translations = repr(emclass.string.__str__()),
  248. )
  249. #LeType child classes definition
  250. for emtype in emtype_l:
  251. if emtype.string.get() == '':
  252. emtype.string.set_default(emtype.name)
  253. result += """
  254. ## @brief EmType {name} LeType child class
  255. # @see leobject::letype::LeType
  256. class {name}(LeType, {leclass}):
  257. _type_id = {uid}
  258. ml_string = MlString({name_translations})
  259. """.format(
  260. name=_LeCrud.name2classname(emtype.name),
  261. leclass=_LeCrud.name2classname(emtype.em_class.name),
  262. uid=emtype.uid,
  263. name_translations = repr(emtype.string.__str__()),
  264. )
  265. #Generating concret class of LeRel2Type
  266. result += self.emrel2type_pycode(model)
  267. #Set attributes of created LeClass and LeType child classes
  268. for emclass in emclass_l:
  269. result += self.emclass_pycode(model, emclass)
  270. for emtype in emtype_l:
  271. result += self.emtype_pycode(model, emtype)
  272. #Populating LeObject._me_uid dict for a rapid fetch of LeType and LeClass given an EM uid
  273. me_uid = {comp.uid: _LeCrud.name2classname(comp.name) for comp in emclass_l + emtype_l}
  274. result += """
  275. ## @brief Dict for getting LeClass and LeType child classes given an EM uid
  276. LeObject._me_uid = %s""" % "{" + (', '.join(['%s: %s' % (k, v) for k, v in me_uid.items()])) + "}"
  277. result += "\n"
  278. heading = heading.format(needed_fieldtypes_list = ', '.join(self.needed_fieldtypes))
  279. result = heading + result
  280. del(self.needed_fieldtypes)
  281. return result