summaryrefslogtreecommitdiff
path: root/yarns.webapp/yarnlib.py
diff options
context:
space:
mode:
authorBen Brown <ben.brown@codethink.co.uk>2015-12-09 17:19:13 +0000
committerPedro Alvarez <pedro.alvarez@codethink.co.uk>2015-12-15 11:34:47 +0000
commit8ffdca7ec095f73f7527e2756fe732ae8bef231a (patch)
treef10aa53d9714c5e24ace9ad10f81c473e3fed702 /yarns.webapp/yarnlib.py
parentee59b5d81283e8ef843e944844bcba596b3ab875 (diff)
downloadlorry-controller-8ffdca7ec095f73f7527e2756fe732ae8bef231a.tar.gz
Add and make use of small python library for yarns
Due to an unwillingness to add another IMPLEMENTS that copypasta'd the same "MATCH_n = os.environ['MATCH_n']", add this small library in an attempt to reduce the amount of repitition. Change-Id: I64dc67ad7bd4c0d7572906168c72b0628a7574db
Diffstat (limited to 'yarns.webapp/yarnlib.py')
-rw-r--r--yarns.webapp/yarnlib.py47
1 files changed, 47 insertions, 0 deletions
diff --git a/yarns.webapp/yarnlib.py b/yarns.webapp/yarnlib.py
new file mode 100644
index 0000000..89f87d9
--- /dev/null
+++ b/yarns.webapp/yarnlib.py
@@ -0,0 +1,47 @@
+# Copyright (C) 2015 Codethink Limited
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; version 2 of the License.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along
+# with this program; if not, write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+# Python library for lorry-controller yarns.
+
+import os
+import json
+
+DATADIR = os.environ['DATADIR']
+
+def matches():
+ '''Returns a generator of MATCH_n environment variables.'''
+ matches = {}
+ prefix = "MATCH_"
+
+ for key, value in os.environ.iteritems():
+ if key.startswith(prefix):
+ stripped_key = key[len(prefix):]
+ if stripped_key.isdigit() and stripped_key != "0":
+ matches[int(stripped_key)] = value
+
+ for key in sorted(matches):
+ if key != 1 and key-1 not in matches:
+ break
+ yield matches[key]
+
+def load_json_from_file(filename):
+ '''Deserialise json file.'''
+ with open(filename, "r") as f:
+ return json.load(f)
+
+def dump_json_to_file(j, filename):
+ '''Write serialised object to file.'''
+ with open(filename, "w") as f:
+ return json.dump(j, f, indent=4)