-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.py
executable file
·242 lines (206 loc) · 5.66 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
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
#!/usr/bin/python3
from flask import Flask, g, request, jsonify, redirect
from flask_cors import CORS
from flask_swagger import swagger
from flask_swagger_ui import get_swaggerui_blueprint
import json
import sqlite3
DB_INIT = '''
PRAGMA journal_mode = WAL; -- Write-ahead log allows concurrent readers during a write.
PRAGMA synchronous = normal; -- Default is 'full', requiring a full fsync after each commit.
CREATE TABLE IF NOT EXISTS store
(key TEXT PRIMARY KEY, value TEXT, created DATEIME, updated DATETIME);
'''
app = Flask(__name__)
app.config['DATABASE'] = 'store.db'
CORS(app)
# DB Helpers
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect(app.config['DATABASE'])
db.executescript(DB_INIT)
db.row_factory = make_dicts
return db
@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
if db is not None:
db.close()
def make_dicts(cursor, row):
return dict((cursor.description[idx][0], value)
for idx, value in enumerate(row))
# DB Access
def db_store(key, value):
value = json.dumps(value)
conn = get_db()
c = conn.cursor()
try:
c.execute('''INSERT INTO store
VALUES (?, ?, strftime('%Y-%m-%d %H:%M:%S', 'now'), strftime('%Y-%m-%d %H:%M:%S', 'now'))
''', (key, value))
except sqlite3.IntegrityError:
c.execute('''UPDATE store
SET value = ?, updated = strftime('%Y-%m-%d %H:%M:%S', 'now')
WHERE key = ?
''', (value, key))
conn.commit()
def db_fetch(key):
c = get_db().cursor()
c.execute('SELECT * FROM store WHERE key = ? LIMIT 1', (key,))
result = c.fetchone()
if result:
value = result['value']
return json.loads(value)
else:
return None
def db_delete(key: str) -> bool:
conn = get_db()
c = conn.cursor()
c.execute('DELETE FROM store WHERE key = ?', (key,))
did_delete = c.rowcount > 0
conn.commit()
return did_delete
# Docs
SWAGGER_URL = '/docs'
API_URL = '/api/spec'
swaggerui_blueprint = get_swaggerui_blueprint(
SWAGGER_URL,
API_URL,
config={'app_name': 'Storage API'},
)
app.register_blueprint(swaggerui_blueprint, url_prefix=SWAGGER_URL)
@app.route("/api/spec")
def spec():
swag = swagger(app)
swag['info']['version'] = '1.0'
swag['info']['title'] = 'Storage API'
return jsonify(swag)
@app.route("/")
def homepage():
return redirect(SWAGGER_URL)
# Routes
def json_error(status_code, message):
resp = jsonify({"status": status_code, "error": message})
resp.status_code = status_code
return resp
@app.errorhandler(400)
def bad_request(*_, message=None):
return json_error(400, message or "bad request")
@app.errorhandler(403)
def forbidden(*_, message=None):
return json_error(403, message or "forbidden")
@app.errorhandler(404)
def not_found(*_, message=None):
return json_error(404, message or "not found")
@app.errorhandler(500)
def internal_server_error(*_, message=None):
return json_error(500, message or "internal server error")
@app.route('/<path:key>', methods=['POST'])
def store(key):
'''
Store a value
---
tags:
- store
consumes:
- application/json
parameters:
- in: path
name: key
type: string
required: true
default: 'group1/users/georgina'
description: the key you want to store the value at
- in: body
name: value
required: true
description: A JSON object to store
schema:
type: object
example:
name: georgina
food: marzipan
responses:
400:
description: The given value was invalid.
200:
description: The key was successfully stored.
schema:
type: object
properties:
key:
type: string
example: group1/users/georgina
value:
type: string
example: {"name": "georgina", "food": "marzipan"}
'''
try:
value = request.get_json()
except:
value = None
if value is None:
return bad_request(message="You need to supply JSON")
if '/' not in key:
return forbidden(message="You must use keys with a forward slash.")
try:
db_store(key, value)
except:
return internal_server_error(message="Failed to store key")
return jsonify(value)
@app.route('/<path:key>', methods=['DELETE'])
def delete(key):
'''
Delete a key (if it exists)
---
tags:
- delete
parameters:
- in: path
name: key
type: string
required: true
default: 'group1/users/georgina'
description: the key you want to delete
responses:
204:
description: The key was successfully deleted
404:
description: The key did not exist
'''
if db_delete(key):
return jsonify({}), 200 # 200: Gone
else:
return jsonify({}), 404 # 404: Not found
@app.route('/<path:key>', methods=['GET'])
def fetch(key):
'''
Retrieve a value
---
tags:
- fetch
parameters:
- in: path
name: key
type: string
required: true
default: 'group1/users/georgina'
description: the key you want to fetch the value for
responses:
404:
description: There was no JSON object stored at the key.
200:
description: The JSON object stored at the key was returned.
schema:
type: object
example:
name: georgina
food: marzipan
'''
result = db_fetch(key)
if result is None:
return jsonify({}), 404 # 404: Not found
return jsonify(result)
if __name__ == '__main__':
app.run(debug=True, port=3000)