Procházet zdrojové kódy

Transform algorithm in python 3

wackazong před 6 roky
rodič
revize
f76a7100de
No account linked to committer's email address
1 změnil soubory, kde provedl 35 přidání a 0 odebrání
  1. 35
    0
      lib/php_crud_api_transform.py

+ 35
- 0
lib/php_crud_api_transform.py Zobrazit soubor

@@ -0,0 +1,35 @@
1
+def php_crud_api_transform(tables):
2
+
3
+    def get_objects(tables, table_name, where_index=None, match_value=None):
4
+        objects = []
5
+        for record in tables[table_name]['records']:
6
+            if where_index == None or (record[where_index] == match_value):
7
+                object = {}
8
+                columns = tables[table_name]['columns']
9
+                for column in columns:
10
+                    index = columns.index(column)
11
+                    object[column] = record[index]
12
+                    for relation, reltable in tables.items():
13
+                        for key, target in reltable.get('relations', {}).items():
14
+                            if target == table_name + '.' + column:
15
+                                relcols = reltable['columns']
16
+                                column_indices = {value: relcols.index(value) for value in relcols}
17
+                                object[relation] = get_objects(
18
+                                    tables, relation, column_indices[key], record[index])
19
+                objects.append(object)
20
+        return objects
21
+
22
+    tree = {}
23
+    for name, table in tables.items():
24
+        if not 'relations' in table:
25
+            tree[name] = get_objects(tables, name)
26
+            if 'results' in table:
27
+                tree['_results'] = table['results']
28
+    return tree
29
+
30
+
31
+if __name__ == "__main__":
32
+    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"]]}}
33
+    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"}]}
34
+
35
+    print(php_crud_api_transform(input)  == output)

Loading…
Zrušit
Uložit