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.

json_backend.py 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. # -*- coding: utf-8 -*-
  2. ## @package EditorialModel.backend.json_backend
  3. # @brief Handle json files
  4. #
  5. # Allows an editorial model to be loaded/saved in
  6. # json format
  7. import json
  8. import datetime
  9. from Lodel.utils.mlstring import MlString
  10. import EditorialModel
  11. def date_cast(date):
  12. if len(date):
  13. return datetime.datetime.strptime(date, '%c')
  14. else:
  15. return None
  16. ## @brief dirty obsolote cast function
  17. def int_or_none(i):
  18. if isinstance(i, int):
  19. return i
  20. elif i is None:
  21. return None
  22. elif len(i):
  23. return int(i)
  24. else:
  25. return None
  26. ## Manages a Json file based backend structure
  27. class EmBackendJson(object):
  28. cast_methods = {
  29. 'uid': int,
  30. 'rank': int,
  31. 'class_id': int,
  32. 'fieldgroup_id': int,
  33. 'rel_to_type_id': int_or_none,
  34. 'rel_field_id': int_or_none,
  35. 'optional': bool,
  36. 'internal': bool,
  37. 'string': MlString.load,
  38. 'help_text': MlString.load,
  39. 'date_create': date_cast,
  40. 'date_update': date_cast,
  41. }
  42. ## Constructor
  43. #
  44. # @param json_file str: path to the json_file used as data source
  45. def __init__(self, json_file):
  46. self.json_file = json_file
  47. pass
  48. @staticmethod
  49. ## @brief Used by json.dumps to serialize date and datetime
  50. def date_handler(obj):
  51. return obj.strftime('%c') if isinstance(obj, datetime.datetime) or isinstance(obj, datetime.date) else None
  52. ## Loads the data in the data source json file
  53. #
  54. # @return list
  55. def load(self):
  56. data = {}
  57. with open(self.json_file) as json_data:
  58. rdata = json.loads(json_data.read())
  59. for index, component in rdata.items():
  60. attributes = {}
  61. for attr_name, attr_value in component.items():
  62. if attr_name in EmBackendJson.cast_methods:
  63. attributes[attr_name] = EmBackendJson.cast_methods[attr_name](attr_value)
  64. else:
  65. attributes[attr_name] = attr_value
  66. data[int(index)] = attributes
  67. return data
  68. ## Saves the data in the data source json file
  69. # @param filename str : The filename to save the EM in (if None use self.json_file provided at init )
  70. def save(self, em, filename = None):
  71. with open(self.json_file if filename is None else filename, 'w') as fp:
  72. fp.write(json.dumps({ component.uid : component.attr_flat() for component in em.components() }, default=self.date_handler))