api de gestion de ticket, basé sur php-crud-api. Le but est de décorrélé les outils de gestion des données, afin
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.

php_crud_api_transform.py 2.3KB

1234567891011121314151617181920212223242526272829303132333435
  1. def php_crud_api_transform(tables):
  2. def get_objects(tables, table_name, where_index=None, match_value=None):
  3. objects = []
  4. for record in tables[table_name]['records']:
  5. if where_index == None or (record[where_index] == match_value):
  6. object = {}
  7. columns = tables[table_name]['columns']
  8. for column in columns:
  9. index = columns.index(column)
  10. object[column] = record[index]
  11. for relation, reltable in tables.items():
  12. for key, target in reltable.get('relations', {}).items():
  13. if target == table_name + '.' + column:
  14. relcols = reltable['columns']
  15. column_indices = {value: relcols.index(value) for value in relcols}
  16. object[relation] = get_objects(
  17. tables, relation, column_indices[key], record[index])
  18. objects.append(object)
  19. return objects
  20. tree = {}
  21. for name, table in tables.items():
  22. if not 'relations' in table:
  23. tree[name] = get_objects(tables, name)
  24. if 'results' in table:
  25. tree['_results'] = table['results']
  26. return tree
  27. if __name__ == "__main__":
  28. input = {"posts": {"columns": ["id","user_id","category_id","content"],"records": [[1,1,1,"blogstarted"]]},"post_tags": {"relations": {"post_id": "posts.id"},"columns": ["id","post_id","tag_id"],"records": [[1,1,1],[2,1,2]]},"categories": {"relations": {"id": "posts.category_id"},"columns": ["id","name"],"records": [[1,"anouncement"]]},"tags": {"relations": {"id": "post_tags.tag_id"},"columns": ["id","name"],"records": [[1,"funny"],[2,"important"]]},"comments": {"relations": {"post_id": "posts.id"},"columns": ["id","post_id","message"],"records": [[1,1,"great"],[2,1,"fantastic"]]}}
  29. output = {"posts": [{"id": 1,"post_tags": [{"id": 1,"post_id": 1,"tag_id": 1,"tags": [{"id": 1,"name": "funny"}]},{"id": 2,"post_id": 1,"tag_id": 2,"tags": [{"id": 2,"name": "important"}]}],"comments": [{"id": 1,"post_id": 1,"message": "great"},{"id": 2,"post_id": 1,"message": "fantastic"}],"user_id": 1,"category_id": 1,"categories": [{"id": 1,"name": "anouncement"}],"content": "blogstarted"}]}
  30. print(php_crud_api_transform(input) == output)