-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
154 lines (116 loc) · 3.78 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
# -*- coding=utf-8 -*-
# ======================================
# >>> IMPORTS
# ======================================
# Python
import json
import threading
from bson import json_util
from bson.objectid import ObjectId
from time import time
# Third-party
from flask import Flask, request, render_template
from flask_mail import Mail
from flask_cors import CORS, cross_origin
from pymongo import MongoClient
# Project
import utils
# ======================================
# >>> INITIALIZE
# ======================================
client = MongoClient('localhost', 27017)
db = client.fuusio70
app = Flask(__name__, static_url_path='')
CORS(app)
settings = utils.load_config(app, db, 'config.ini')
mail = Mail(app)
# ======================================
# >>> REST API ENDPOINTS
# ======================================
@app.route('/', methods=['GET'])
@cross_origin(origins='*')
def homepage():
return render_template('index.html')
@app.route('/registration', methods=['GET'])
@cross_origin(origins='*')
def registration():
return render_template('registration.html')
@app.route('/users', methods=['GET'])
@cross_origin(origins='*')
def users_read():
""" Returns all user objects """
users = db.users
return json.dumps(list(users.find()), default=json_util.default)
@app.route('/users/<user_id>', methods=['GET'])
@cross_origin(origins='*')
def user_read(user_id):
""" Returns single user object by id """
user = db.users.find_one({'_id': ObjectId(user_id)})
user = user or {}
return json.dumps(user, default=json_util.default)
@app.route('/usersCount', methods=['GET'])
@cross_origin(origins='*')
def users_count():
""" Returns the count of user objects """
count = db.users.count()
return json.dumps(count)
@app.route('/users', methods=['PUT'])
@cross_origin(origins='*')
def users_update():
""" Update user object """
raw_data = request.data
try:
if not raw_data:
raise ValueError('request.data was empty')
data = json.loads(raw_data)
except ValueError as e:
print('[ERROR] /users PUT ValueError: ' + str(e))
return str(e)
user = data['formData']
user['referenceNumber'] = utils.get_reference_number(db)
user_id = data['userId']
db.users.update({'_id': ObjectId(user_id)}, {'$set': user}, upsert=True)
settings = db.config.find_one()
utils.send_billing_mail(mail, settings, user)
return json.dumps({'userId': str(user_id)})
@app.route('/users', methods=['POST'])
@cross_origin(origins='*')
def users_create():
""" Creates new empty user object """
timestamp = int(time())
users = db.users
dummy_user = {
'additionalInfo': '',
'allergies': '',
'avec': '',
'email': '',
'firstYear': '',
'historyAddress': '',
'historyDeliveryMethod': '',
'historyOrder': '',
'name': '',
'referenceNumber': '',
'sillis': '',
'status': '',
'table': '',
'timestamp': timestamp
}
user_id = users.insert_one(dummy_user).inserted_id
# Timeout, delete if not edited within timeout limit
timeout_duration = int(settings['App']['SessionTimeout'])
threading.Timer(
timeout_duration, session_timeout, (db, str(user_id))
).start()
return json.dumps({'userId': str(user_id), 'timestamp': timestamp})
# ======================================
# >>> HELPER FUNCTIONS
# ======================================
def session_timeout(mongo_db, user_id):
user = mongo_db.users.find_one({'_id': ObjectId(user_id)})
if not user.get('name'):
mongo_db.users.delete_one({'_id': ObjectId(user_id)})
# ======================================
# >>> RUN
# ======================================
if __name__ == '__main__':
app.run(debug=True, use_reloader=True)