aboutsummaryrefslogtreecommitdiff
path: root/mapping.py
diff options
context:
space:
mode:
authorDeclan Hoare <[email protected]>2020-04-16 22:58:21 +1000
committerDeclan Hoare <[email protected]>2020-04-16 23:10:44 +1000
commit7000fce72fbec34c6f4957a59d4146cc7148ee59 (patch)
tree5affe93d68a7fbcc6cf85a4d9a3eedecc730d1f7 /mapping.py
downloadshiftgears-7000fce72fbec34c6f4957a59d4146cc7148ee59.tar.gz
shiftgears-7000fce72fbec34c6f4957a59d4146cc7148ee59.tar.bz2
shiftgears-7000fce72fbec34c6f4957a59d4146cc7148ee59.zip
Initial Release
Diffstat (limited to 'mapping.py')
-rw-r--r--mapping.py52
1 files changed, 52 insertions, 0 deletions
diff --git a/mapping.py b/mapping.py
new file mode 100644
index 0000000..a01652f
--- /dev/null
+++ b/mapping.py
@@ -0,0 +1,52 @@
+import enum
+import os
+
+# A mapping defines how to convert part of a row to a dictionary for
+# an API response, and how to insert data from a received dictionary
+# back into the row. In other words it allows you to quickly select
+# and rename a lot of fields. This module deals with parsing them.
+# They are used in database and the path is chosen in myconfig.
+
+class Direction(enum.Flag):
+ TO = enum.auto()
+ FROM = enum.auto()
+
+Direction.BOTH = Direction.TO|Direction.FROM
+
+_direction_symbols = [("<", Direction.TO), (">", Direction.FROM)]
+
+def load_mappings(path):
+ mappings = {}
+ for fn in os.listdir(path):
+ with open(os.path.join(path, fn)) as f:
+ mapping = []
+ for l in f:
+ l = l.strip()
+ if l == "" or l.startswith("#"):
+ continue
+ cols = l.split()
+ dictname = cols.pop(0)
+ if cols:
+ direction = Direction(0)
+ dirstring = cols.pop(0)
+ for sym, val in _direction_symbols:
+ if sym in dirstring:
+ direction |= val
+ else:
+ direction = Direction.BOTH
+ if cols:
+ tablename = cols.pop(0)
+ else:
+ tablename = dictname
+ mapping.append((dictname, direction, tablename))
+ mappings[fn] = mapping
+ return mappings
+
+def map_to(row, mapping):
+ return {dictname: getattr(row, tablename) for dictname, direction, tablename in mapping if direction & direction.TO}
+
+def map_from(row, mapping, data):
+ for dictname, direction, tablename in mapping:
+ if direction & direction.FROM:
+ setattr(row, tablename, data[dictname])
+