This repository has been archived by the owner on Aug 23, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame_of_road.py
executable file
·164 lines (141 loc) · 4.7 KB
/
game_of_road.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
from flask import Flask
from flask import abort
from flask import json
from flask import redirect
from flask import request
from flask import url_for
from flask import make_response
import os
import time
import recon
# ########################################################
def _external_add(sessionId, _dict):
# Check if the sessionId is known
pass
def _external_get_answer(question, sessionId):
question = question.replace("+", " ")
try:
return recon.get_answer(question)
except:
return "An unknown error occured"
def _external_get_history(sessionId):
return {}
# ########################################################
def get_answer(question, sessionId):
_external_add(sessionId, dict(
timestamp=time.time(),
who='user',
message=question
))
answer = _external_get_answer(
question=question, sessionId=sessionId)
_external_add(sessionId, dict(
timestamp=time.time(),
who='bot',
message=answer
))
return answer
# ########################################################
# History will be a list of elements, with each elements
# formatted like this:
# {'timestamp':1512685346.413079, 'who':'user',
# 'message':'Hello'}
def get_history(sessionId):
raise NotImplementedError
# ########################################################
# I've created some types of exception in order to handle
# errors
class InvalidSession(RuntimeError):pass
class UnknownUser(InvalidSession):pass
class UndefinedUser(InvalidSession):pass
# ########################################################
app = Flask(__name__)
app.debug = True
# Only used in debug
defaultSessionId = 'ffffffffffffffffffffffffffffffff'
# If we debug, we will route everything here, else,
# we will route only POST and refuse the other
@app.route("/api/answer/", methods=['POST', 'GET'])
@app.route("/api/answer/<question>", methods=['POST', 'GET'])
def api_answer(question=None):
if question is None:
# I havn't found a way to parse it
question = request.get_data()
length = len('question=')
try:
index = request.get_data().lower().index(b'question=')
except ValueError:
return '{"error":"Please give us a \'question\' field in data"}', 401
question = question[index + length:]
if b'&' in question:
question = question[:question.index('&')]
if request.method.upper() == 'GET' and not app.debug:
return '{"error":"Please use POST instead of GET"}', 405
try:
# KeyError will only be caught for this line
try:
sessionId = request.cookies['session']
except KeyError:
raise InvalidSession()
else:
return make_response(
json.dumps(dict(
answer=get_answer(
question=question,
sessionId=sessionId
)
))
)
except InvalidSession:
if app.debug:
response = redirect(url_for(
'api_answer', question=question
))
response.set_cookie('session', defaultSessionId)
return response
else:
return '{"error":"Please give us a valid session id"}'
@app.route("/api/history/", methods=['POST', 'GET'])
def api_history():
try:
# KeyError will only be caught for this line
try:
sessionId = request.cookies['session']
except KeyError:
raise InvalidSession()
else:
return make_response(
json.dumps(dict(
answer=get_history(
sessionId=sessionId
)
))
)
except InvalidSession:
if app.debug:
response = redirect(url_for(
'api_history'
))
response.set_cookie('session', defaultSessionId)
return response
else:
return '{"error":"Please give us a valid session id"}'
return _external_get_history(sessionId=sessionId)
'''if 'session' not in request.cookies:
if not app.debug:
return json.dumps({'error':'Please add cookies'}), 401
response = app.make_response(redirect())
response.set_cookie('session', defaultSessionId)'''
"userSession = request.cookies['session']"
# ####################################
# Default path => Send a 404
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def default(path):
abort(404)
def main():
# Build db
db = recon.build_db()
app.run(host=os.getenv('IP', '0.0.0.0'), port=int(os.getenv('PORT', 80)))
if __name__ == '__main__':
main()