-
Notifications
You must be signed in to change notification settings - Fork 1
/
flaskapp.py
181 lines (145 loc) · 5.33 KB
/
flaskapp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
""" This is the web app server. """
from flask import Flask, request, redirect, render_template, jsonify
import pandas as pd
from datetime import datetime
import networkx as nx
import os
import random
import string
import xml.etree.ElementTree as ET
import re
import pickle
import json
import ea
app = Flask(__name__)
app.debug = True
eadata = ea.dataobj() #persistent data
#=======================================
# UI & RENDER
#=======================================
#test
@app.route('/test')
def test():
return 'done.'
# Main/home
# -------------------------------------------------
@app.route('/')
def index():
return redirect("/static/index.html")
# Search UI (wrapper frame)
# -------------------------------------------------
@app.route('/search/<path:type>/<path:term>', methods=['GET'])
def ui_search(type, term):
return render_template('ea-search-frame.html', type=type, label=term)
# Search Results Frame UI
# -------------------------------------------------
@app.route('/results/<path:type>/<path:term>', methods=['GET'])
def ui_results(type, term):
df = eadata.dfprops
df = df[(df[type].str.contains(term, case=False, regex=False))]
df = df.sort_values(['Type','Name'], ascending=[True,True]).reset_index(drop=True)
respstr = "No matches found."
if not df.empty:
df['Results'] = df.apply(lambda x: "<li><a href='javascript:clickResult(\"" + x.ID + "\")'>" + x.Type + ": " + x.Name + "</a>", axis=1)
respstr = ''.join(df['Results'].tolist())
return render_template('ea-search-results.html', type=type, label=term, results=respstr)
# Node UI - Relations and Views
# -------------------------------------------------
@app.route('/node/<nodeid>', methods=['GET'])
def UI_node(nodeid):
#load graph data
G = eadata.G
if not G.node.get(nodeid):
return '<h2>No relationships for this element.</h2>'
nlist = [G.node[nodeid]] #node list of dicts
views = {} #view dict
elist = [] #edge list of dicts
#filter by layer: sbatpmio
filter = request.args.get('filter')
filterlookup = {"s":"strategy", "b":"business", "a":"application", "t":"technology", "p":"physical", "m":"motivation", "i":"implementation", "o":"other"}
def fedge(x): #format for html
edge = {}
edge['to'] = x[0]
edge['from']= x[1]
edge['arrows']='from'
return edge
def addnode(x):
#check filter
if filter:
for letter in filter:
if x["type"] in ea.layers[filterlookup[letter]]:
return False
#add node
nlist.append(x)
return True
#iterate graph
nids = [] #avoid dupes
for g in G.successors(nodeid):
if G.node[g]['type'] == "view":
views[G.node[g]['id'].replace("id-","")] = G.node[g]['label']
else:
if addnode(G.node[g]):
nids.append(G.node[g]['id']) #watch dupes
for g in G.predecessors(nodeid):
if G.node[g]['id'] not in nids: #no dupes
addnode(G.node[g])
#edge list
buildedges = [n['id'] for n in nlist]
for e in nx.edges(G, buildedges):
elist.append(fedge(e))
#get label
dfe = eadata.dfe.loc[eadata.dfe['ID'] == nodeid]
label = dfe['Name'].values[0]
type = dfe['Type'].values[0]
#TODO - fix me, this WAS sloppy attribute rename for visjs 'Plan' coloring
nlist2 = []
for n in nlist:
#n["group"] = n["plan"]
nlist2.append(n)
return render_template('ea-node.html', nodeid=nodeid, label=label, type=type, nlist=nlist2, elist=elist, views=views, modelid=ea.MODELID)
#=======================================
# DATA PARSE & REFRESH
#=======================================
# Main refresh
# -------------------------------------------------
@app.route('/refreshea', methods=['GET'])
def refreshea():
eadata.refresh()
refresh_html()
return redirect("/static/index.html")
# HTML Refresh
# -------------------------------------------------
#main function
def refresh_html():
htmlpath = os.path.join(ea.path_root, "static")
def gethtmlfiles(directory):
filelist = []
for filename in os.listdir(directory):
if filename.endswith(".html"):
filelist.append(os.path.join(directory, filename))
continue
else:
continue
return filelist
def refresh_url_randomize(filepath):
# Read in the file
with open(filepath, 'r') as file :
filedata = file.read()
# Replace the target string
randstr = ''.join(random.choice(string.ascii_letters) for m in range(5))
filedata = filedata.replace('.html', '.html?' + randstr)
filedata = filedata.replace('.png', '.png?' + randstr)
# Write the file out again
with open(filepath, 'w') as file:
file.write(filedata)
#randomize urls - CHROME IFRAME CACHING
refresh_url_randomize(os.path.join(htmlpath, "index.html"))
for htmlfiles in gethtmlfiles(os.path.join(htmlpath, ea.MODELID, "views")):
refresh_url_randomize(htmlfiles)
for htmlfiles in gethtmlfiles(os.path.join(htmlpath, ea.MODELID, "elements")):
refresh_url_randomize(htmlfiles)
#=======================================
# START
#=======================================
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80, threaded=True)