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

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