-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter.py
More file actions
233 lines (203 loc) · 8.57 KB
/
Copy pathrouter.py
File metadata and controls
233 lines (203 loc) · 8.57 KB
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
from flask import Flask, jsonify, abort, request
class InvalidUsage(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
return rv
def make_app(database):
app = Flask(__name__)
@app.route('/')
def index():
return "Hello, World!"
@app.route('/hello')
def hello():
return jsonify({
'greetings': 'Hi! This is TinyNoSQL',
'database_ready': bool(database),
})
@app.route('/show_collections', methods=['GET'])
def show_collections():
return jsonify(database.show_collections())
@app.route('/<string:collection>/_all', methods=['GET'])
def collection_all(collection):
"""
Return all documents in the given collection.
"""
try:
table = database.get_collection(collection)
except KeyError:
return '''
Not found.
The collection \"{}\" is not found. Please check again the name of the collection.
You can use /show_collections to find all collections in the database.
'''.format(collection), 404
return jsonify(table.all())
@app.route('/<string:collection>/<uuid:doc_id>', methods=['GET'])
def collection_find_by_id(collection, doc_id):
"""
Return the document specified by collection name and document id.
"""
try:
table = database.get_collection(collection)
except KeyError:
return '''
Not found.
The collection \"{}\" is not found. Please check again the name of the collection.
You can use /show_collections to find all collections in the database.
'''.format(collection), 404
rtn = table.find({'_id': str(doc_id)})
if rtn['successful']:
if rtn['results']['doc']:
return jsonify(rtn['results']['doc'][0])
else:
return 'Document not found', 404
else:
return rtn['message'], 406
@app.route('/<string:collection>/_find', methods=['GET', 'POST'])
def collection_find(collection):
"""
Find all documents in the given collection matching the given criterion
"""
# Like elasticsearch's API, we try to implement a lite api using query-string (URL parameters) and a full
# function request body using JSON
try:
table = database.get_collection(collection)
except KeyError:
return '''
Not found.
The collection \"{}\" is not found. Please check again the name of the collection.
You can use /show_collections to find all collections in the database.
'''.format(collection), 404
# Full request body version
if 'Content-Type' in request.headers and request.headers['Content-Type'] == 'application/json':
query = request.json
if not query:
return "Find query can't be empty. Please use _all to query all data.", 400
rtn = table.find(query)
if rtn['successful']:
return jsonify(rtn['results'])
else:
return rtn['message'], 406
# Query string version
else:
query = dict(request.args)
if not query:
return "Find query can't be empty. Please use _all to query all data.", 400
for k in query:
if isinstance(query[k], str) and query[k].isnumeric():
query[k] = eval(query[k])
rtn = table.find(query)
if rtn['successful']:
return jsonify(rtn['results'])
else:
return rtn['message'], 406
@app.route('/<string:collection>/_update', methods=['PUT', 'POST'])
def collection_update(collection):
"""
Update the documents matching query criterion with set, unset, increment, or append
"""
try:
table = database.get_collection(collection)
except KeyError:
return '''
Not found.
The collection \"{}\" is not found. Please check again the name of the collection.
You can use /show_collections to find all collections in the database.
'''.format(collection), 404
# Full request body version
if 'Content-Type' in request.headers and request.headers['Content-Type'] == 'application/json':
query = request.json
if not query:
return "Find query can't be empty. Please use _all to query all data.", 400
if 'criteria' not in query or 'operation' not in query:
return "An update request needs to have \"criteria\" and \"operation\" specified", 400
rtn = table.update(query['criteria'], query['operation'])
if rtn['successful']:
return jsonify(rtn['doc_id'])
else:
return 'Updated {} documents, {} fail.'.format(rtn['successful_cnt'], rtn['unsuccessful_cnt']), 406
# Query string version
else:
query = dict(request.args)
if not query:
return "Find query can't be empty. Please use _all to query all data.", 400
for k in query:
if isinstance(query[k], str) and query[k].isnumeric():
query[k] = eval(query[k])
rtn = table.update(query['criteria'], query['operation'])
if rtn['successful']:
return jsonify(rtn['doc_id'])
else:
return 'Updated {} documents, {} fail.'.format(rtn['successful_cnt'], rtn['unsuccessful_cnt']), 406
@app.route('/<string:collection>/_insert', methods=['POST'])
def collection_insert(collection):
"""
Insert one or a list of documents to the collection.
"""
try:
table = database.get_collection(collection)
except KeyError:
return '''
Not found.
The collection \"{}\" is not found. Please check again the name of the collection.
You can use /show_collections to find all collections in the database.
'''.format(collection), 404
# Full request body version
if 'Content-Type' in request.headers and request.headers['Content-Type'] == 'application/json':
doc = request.json
# Query string version
else:
doc = dict(request.args)
if isinstance(doc, dict):
for k in doc:
if isinstance(doc[k], str) and doc[k].isnumeric():
doc[k] = eval(doc[k])
if not isinstance(doc, (dict, list)):
return "Please either insert a document or an array of document", 400
if isinstance(doc, dict):
rtn = table.insert(doc)
elif isinstance(doc, list):
rtn = table.insert_many(doc)
if rtn['successful']:
return jsonify(rtn['doc_id'])
else:
return rtn['message'], 406
@app.route('/<string:collection>/_remove', methods=['DELETE'])
def collection_remove(collection):
"""
Remove all documents meeting the criterion
"""
try:
table = database.get_collection(collection)
except KeyError:
return '''
Not found.
The collection \"{}\" is not found. Please check again the name of the collection.
You can use /show_collections to find all collections in the database.
'''.format(collection), 404
# Full request body version
if 'Content-Type' in request.headers and request.headers['Content-Type'] == 'application/json':
query = request.json
if not query:
return "Find query can't be empty. Please use _all to query all data.", 400
# Query string version
else:
query = dict(request.args)
if not query:
return "Find query can't be empty. Please use _all to query all data.", 400
for k in query:
if isinstance(query[k], str) and query[k].isnumeric():
query[k] = eval(query[k])
rtn = table.remove(query)
if rtn['successful']:
return jsonify(rtn['doc_id'])
else:
return rtn['message'], 406
return app