Skip to content

Commit 3d0753b

Browse files
committed
Ability to process tags stored in a json file
Case sensitive tags are stored in data/tags.json. For now, this is what I have in mine { "WEB_ADDRESS":"localhost", "PAGE_TITLE":"Testing things..." }
1 parent 8ac01ad commit 3d0753b

File tree

1 file changed

+40
-29
lines changed

1 file changed

+40
-29
lines changed

server.py

Lines changed: 40 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
#!/usr/bin/env python
22

3-
import sys, os
43
import SimpleHTTPServer, SocketServer
4+
import sys
5+
import os
6+
import json
7+
import re
58

69
#Replace this with a different path if you need to...
710
base_path = os.path.join(os.getcwd(),"esp8266","data")
@@ -13,44 +16,52 @@ def do_GET(self):
1316
self.send_header("Content-type", "text/html")
1417
self.end_headers()
1518

16-
data = self.process(self.path)
19+
data = self.process_tpl(self.path)
1720
self.wfile.write(data)
1821
self.wfile.close()
1922
return
2023
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
2124

22-
def process(self,fn):
25+
def process_tpl(self,fn):
26+
p = re.compile('\$(.*?)\$')
2327
if fn.startswith("/") or fn.startswith("\\"):
2428
fn = fn[1:]
25-
fn = os.path.join(base_path,os.path.normpath(fn))
26-
fpath,_ = os.path.split(fn)
27-
lines = open(fn).read()
28-
lines = lines.split("\n")
29-
n_lines = len(lines)
29+
30+
fn = os.path.join(base_path,fn)
31+
data = open(fn).read()
32+
33+
fn_json = os.path.join(base_path,"tags.json")
34+
if os.path.exists(fn_json):
35+
json_dic = json.loads(open(fn_json).read())
36+
else:
37+
json_dic = {}
38+
39+
tags = p.findall(data)
3040
i = 0
31-
while i < n_lines:
32-
line = lines[i].strip()
33-
if line.startswith("$INCLUDE["):
34-
p0 = line.find("[")+1
35-
p1 = line.find("]")
36-
if p0 < 0 or p0 == len(line) or p1 < 0:
37-
continue
38-
fn_inc = os.path.join(fpath,line[p0:p1])
39-
if not os.path.exists(fn_inc):
40-
i = i+1
41-
continue
42-
43-
lines_inc = open(fn_inc).read()
44-
lines_inc = lines_inc.split("\n")
45-
if i < n_lines-1:
46-
lines1 = lines[i+1:]
47-
else:
48-
lines1 = []
49-
lines = lines[:i]+lines_inc+lines1
50-
n_lines = len(lines)
41+
n_tags = len(tags)
42+
while i < n_tags:
43+
dd = self.process_tag(data,tags[i],json_dic)
44+
if dd != data:
45+
data = dd
46+
tags = p.findall(data)
47+
n = len(tags)
5148
else:
5249
i = i+1
53-
return "\n".join(lines)
50+
return data
51+
52+
def process_tag(self, data, tag, json_dic={}):
53+
print " processing $%s$" % tag
54+
if tag in json_dic.keys():
55+
data = data.replace("$"+tag+"$",json_dic[tag])
56+
elif tag.startswith("INCLUDE[") and tag.endswith("]"):
57+
fn = tag[8:-1]
58+
fn = os.path.join(base_path,fn)
59+
d = open(fn).read()
60+
p0 = data.find("$"+tag)
61+
p1 = data.find("]",p0)+2
62+
data = data[:p0]+d+data[p1:]
63+
64+
return data
5465

5566
if __name__ == '__main__':
5667
print "="*60

0 commit comments

Comments
 (0)