-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.py
143 lines (120 loc) · 4.29 KB
/
server.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
import os
import redis
import logging
import datetime
import json
from flask import Flask , send_from_directory, render_template, url_for, request, jsonify
#Redis instance from heroku
r = redis.from_url(os.environ.get("REDIS_URL"), db =None, decode_responses = True)
app = Flask(__name__)
FAIL_MESSAGE = 'la pulenta oe'
INVALID_SEPARATOR = "$$"
data = None
with open('classrooms.json') as json_data:
data = json.load(json_data)
#"Landing page"
@app.route('/')
def webprint():
global data
return render_template('index.html')
#Returning JSON
@app.route('/salones')
def salones():
global data
return json.dumps(data, ensure_ascii=False)
#Returning invalid-posted classrooms
@app.route('/salones/invalidos', methods = ['POST', 'GET'])
def salonesInvalidos():
if request.method == 'GET':
resp = []
#Turning set into list to return JSON
for classroom in r.smembers("invalidos"):
resp.append(classroom)
return jsonify(resp)
elif request.method == 'POST':
info = request.get_json() or request.form #Matching Axios request type
print("Adding invalid classroom: " + info['classroom'])
r.sadd("invalidos", info['classroom'])
return "¡Se registró exitosamente el salón!"
else:
#By default, before entering the function, if the method does not match, an unsupported
#Server method error will be returned
return FAIL_MESSAGE
#Saves the string <strng> in the DB
@app.route('/db/<strng>')
def saveInDB(strng):
r.lpush('db', '%s' % strng)
return 'OK'
#Recalls the stored info in the DB
@app.route('/db/recall/test', methods = ['GET'])
def recallDB():
try:
return str(r.lrange('db', 0, -1))
except Exception as error:
return formatError(error)
#DevMode Handling---------------------------------------------
#Returns devMode.html [GET] #Checks login credentials [POST]
@app.route('/devMode', methods = ['POST', 'GET'])
def devMode():
if request.method == 'GET':
r.incr('devModeGet')
return render_template('devMode.html')
elif request.method == 'POST':
pss = request.get_json() or request.form #Matching Axios request type
if checkPassword(pss['password'], pss['info']):
return os.environ.get('PASSWORD_MESSAGE')
else:
return FAIL_MESSAGE
else: #Message for other methods (DELETE, PUT, CONNECT, ...)
return '¿?'
#Recalls the failed log attemps of devMode
@app.route('/devMode/recall/logAttempts', methods = ['POST'])
def recallLogAttempts():
pss = request.get_json() or request.form
if checkPassword(pss['password'], pss['info']):
try:
return str(r.lrange('devModeGetList', 0, -1))[1:-2]
except Exception as error:
return formatError(error)
else:
return FAIL_MESSAGE
#Recalls the times devMode's URL was accessed
@app.route('/devMode/recall/getTimes', methods = ['POST'])
def recallGetTimes():
pss = request.get_json() or request.form
if checkPassword(pss['password'], pss['info']):
try:
return str(r.get('devModeGet'))
except Exception as error:
return formatError(error)
else:
return FAIL_MESSAGE
#Posts classroom information
@app.route('/devMode/post/classroomInfo', methods = ['POST'])
def postClassroomInfo():
pss = request.get_json() or request.form
if checkPassword(pss['password'], pss['info']):
r.append("classrooms", "<<" + str(pss))
return "yay!"
else:
return "Wrong password"
@app.route('/devMode/get/classroomInfo', methods = ['POST'])
def getClassroomInfo():
pss = request.get_json() or request.form
if checkPassword(pss['password'], pss['info']):
return r.get("classrooms")
else:
return "Wrong password"
#Non-server functions-----------------
#Checks for password and logs failed attempts
def checkPassword(password, info):
date = str(datetime.datetime.utcnow())
attempt = password == os.environ.get('REDIS_URL')
if not attempt:
r.lpush('devModeGetList', "Info: " + info + " --- " + "Timestamp: " + date + " // Attempt: " + password + "\n")
return attempt
#Format function to redis errors
def formatError(error):
msg = 'Type: ' + type(error) + '\n'
msg += 'Exception: ' + error
return msg