-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
172 lines (133 loc) · 4.81 KB
/
app.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
import os
import json
from datetime import datetime
from flask import Flask
from flask import render_template, url_for, request, jsonify
from flask import send_from_directory
from flask.ext.sqlalchemy import SQLAlchemy
from werkzeug.utils import secure_filename
ALLOWED_EXTENSIONS = ['JPEG', 'JPG', 'PNG', 'GIF']
app = Flask(__name__)
# Setup routing for static files
app.jinja_env.globals['static'] = (
lambda filename: url_for('static', filename=filename))
# Setup folder paths for uploads and SQL
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.getcwd() + '/tmp/store.db'
app.config['UPLOAD_FOLDER'] = os.path.join(os.getcwd(), 'tmp/uploads')
# Instantiate db session
db = SQLAlchemy(app)
# Models
class Zone(db.Model):
id = db.Column(db.Integer, primary_key=True)
label = db.Column(db.String(80))
shape = db.Column(db.Text) # store as a json blob
extras = db.Column(db.Text) # store extra stuff as a blob
floor_id = db.Column(db.Integer, db.ForeignKey('floor.id'))
floor = db.relationship('Floor',
backref=db.backref('zones', lazy='dynamic'))
def __init__(self, label, shape, floor, extras=None):
self.shape = shape
self.label = label
self.floor = floor
if extras is None:
self.extras = '{}'
def __repr__(self):
return '<Zone %r>' % self.label
def toObj(self):
d = {}
d['label'] = self.label
d['shape'] = json.loads(self.shape)
return d
class Floor(db.Model):
id = db.Column(db.Integer, primary_key=True)
label = db.Column(db.String(50))
img_name = db.Column(db.String(80))
extras = db.Column(db.Text) # store extra stuff as a blob
def __init__(self, label, img_name, extras=None):
self.label = label
self.img_name = img_name
if extras is None:
self.extras = ''
def __repr__(self):
return '<Floor %r>' % self.label
def toObj(self):
z = []
for zone in self.zones:
z.append(zone.toObj())
return {
'label': self.label,
'imgname': self.img_name,
'zones': z
}
# Misc
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].upper() in ALLOWED_EXTENSIONS
# Routes
@app.route('/')
def list_floors():
floors = Floor.query.all()
return render_template('floor_list.html', floors=floors)
@app.route('/create', methods=['GET', 'POST'])
def create_new_floor():
if request.method == 'GET':
return render_template('create.html')
else:
# Otherwise it's a POST request
try:
data = json.loads(request.data)
# request.data should be a Floor JSON object
# see static/js/models.js
fid = process_floor_json(data)
return jsonify(success=True, floorId=fid)
except:
return jsonify(success=False, msg='Invalid Floor JSON')
def process_floor_json(data):
floor = Floor(data['label'], data['img'])
db.session.add(floor)
for zone in data['zones']:
shape_json = json.dumps(zone['shape'])
z = Zone(zone['label'], shape_json, floor, zone['extras'])
db.session.add(z)
db.session.commit()
return floor.id
@app.route('/view/<floor_id>')
def get_floor_data(floor_id):
try:
floor = Floor.query.filter(Floor.id == int(floor_id)).first()
if floor:
return render_template('view.html', floor=floor)
else:
return render_template('not_found.html')
except:
return render_template('not_found.html')
@app.route('/fetch/floor/<floor_id>')
def fetch_floor_data(floor_id):
try:
floor = Floor.query.filter(Floor.id == int(floor_id)).first()
if floor:
return jsonify(success=True, floor=floor.toObj(), msg='')
else:
return jsonify(success=False, msg='Could not find floor')
except:
return jsonify(success=False, msg='Could not find floor')
@app.route('/up', methods=['POST'])
def upload_file():
if request.method == 'POST':
filename = secure_filename(request.headers.get('X-File-Name'))
if not allowed_file(filename):
return jsonify(success=False, msg='Invalid image format')
filename = datetime.now().strftime('%Y%m%d%H%M%S%f') + '-' + filename
try:
f = open(os.path.join(app.config['UPLOAD_FOLDER'], filename), 'w')
f.write(request.data)
f.close()
return jsonify(success=True, imgname=filename)
except:
return jsonify(success=False, msg='Could not save file')
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename)
if __name__ == '__main__':
app.run(debug=True, port=5000)