/
app.py
553 lines (487 loc) · 15.5 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
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
import os
from flask import (
Flask,
request,
abort,
jsonify
)
from models import (
setup_db,
Region,
Service
)
from flask_cors import CORS
import sys
from auth import (
AuthError,
requires_auth
)
RESULTS_PER_PAGE = 5
def paginate_results(request, results):
page = request.args.get('page', 1, type=int)
start = (page - 1) * RESULTS_PER_PAGE
if(len(results) < RESULTS_PER_PAGE):
end = len(results)-1
else:
end = start + RESULTS_PER_PAGE
formatted_results = [res.format() for res in results]
page_results = formatted_results[start:end]
return page_results
def create_app(test_config=None):
app = Flask(__name__)
setup_db(app)
CORS(app, resources={r"/*": {"origins": "*"}})
# CORS Headers
@app.after_request
def after_request(response):
response.headers.add(
'Access-Control-Allow-Headers',
'Content-Type,Authorization,true')
response.headers.add(
'Access-Control-Allow-Methods',
'GET,PUT,POST,PATCH,DELETE,OPTIONS')
return response
# -----------------------------------------------------------------------------------------
# ROUTE FOR GET all regions
# GET /regions
# -----------------------------------------------------------------------------------------
'''
ROUTE FOR GET /regions
No request Payload
Sample Success Response is below
{
"regions": [
{
"city": "Chennai",
"country": "India",
"name": "West Mambalam",
"regionhead": "Anitha",
"state": "Tamil Nadu"
},
{
"city": "Chennai",
"country": "India",
"name": "Vadapalani",
"regionhead": "Amutha",
"state": "Tamil Nadu"
}
],
"success": true
}
'''
@app.route('/regions', methods=['GET'])
def get_regions():
all_regions = Region.query.order_by(Region.id).all()
total_no_regions = len(all_regions)
if (total_no_regions == 0):
abort(404)
current_regions = paginate_results(request, all_regions)
if (len(current_regions) == 0):
abort(404)
return jsonify({
'regions': current_regions,
'success': True
})
# -----------------------------------------------------------------------------------------
# ROUTE to GET a specific region
# GET / regions/<region_id>
# -----------------------------------------------------------------------------------------
'''
ROUTE FOR GET /regions
No request Payload
Sample Success Response is below
{
"region": {
"city": "Chennai",
"country": "India",
"id": 1,
"name": "West Mambalam",
"regionhead": "Anitha",
"state": "Tamil Nadu"
},
"success": true
} '''
@app.route('/regions/<region_id>', methods=['GET'])
def get_region_by_id(region_id):
region = Region.query.get(region_id)
if region is None:
abort(404)
return jsonify({
"region": Region.format(region),
"success": True
}), 200
# -----------------------------------------------------------------------------------------
# ROUTE to create a new region
# POST /regions
# -----------------------------------------------------------------------------------------
'''
ROUTE FOR POST /regions
Sample Request Payload in Expected Format:
{
'name': 'West Mambalam',
'city': 'Chennai',
'state': 'Tamil Nadu',
'country': 'India',
'regionhead': 'Anitha'
}
Sample Successful JSON Response
{
"created": 2,
"success": true
}
'''
@app.route('/regions', methods=['POST'])
@requires_auth('post:regions')
def create_region(jwt):
try:
body = request.get_json()
name = body.get('name', None)
city = body.get('city', None)
state = body.get('state', None)
country = body.get('country', None)
regionhead = body.get('regionhead', None)
if (name is None) or (city is None) or (
state is None) or (regionhead is None):
abort(422)
new_region = Region(
name=name,
city=city,
state=state,
regionhead=regionhead,
country=country)
new_region.insert()
return jsonify({
'success': True,
'created': new_region.id
}), 200
except BaseException:
print(sys.exc_info())
abort(422)
# -----------------------------------------------------------------------------------------
# ROUTE to update a region
# PATCH /regions/<region_id>
# -----------------------------------------------------------------------------------------
'''
ROUTE TO UPDATE Regions
PATCH /regions/<region_id>
Sample Successful JSON Response
{
"updated": 2,
"success": true
}
'''
@app.route('/regions/<region_id>', methods=['PATCH'])
@requires_auth('patch:regions')
def update_region(jwt, region_id):
body = request.get_json()
try:
name = body.get('name', None)
city = body.get('city', None)
state = body.get('state', None)
country = body.get('country', None)
regionhead = body.get('regionhead', None)
if (name is None) and (city is None) and (
state is None) and (regionhead is None):
abort(422)
region = Region.query.get(region_id)
if (region is None):
abort(402)
if name is not None:
region.name = name
if city is not None:
region.city = city
if state is not None:
region.state = state
if country is not None:
region.country = country
if regionhead is not None:
region.regionhead = regionhead
Region.update(region)
return jsonify({
'success': True,
'updated': region.id
}), 200
except BaseException:
print(sys.exc_info())
abort(500)
'''
ROUTE TO DELETE Region BY ID
DELETE /regions/<region_id>
Sample Successful JSON Response
{
"deleted": 2,
"success": true
}
'''
@app.route('/regions/<region_id>', methods=['DELETE'])
@requires_auth('delete:regions')
def delete_region(jwt, region_id):
region = Region.query.get(region_id)
if region is None:
abort(404)
try:
Region.delete(region)
return jsonify({
'success': True,
'deleted': region.id
}), 200
except BaseException:
print(sys.exc_info())
abort(422)
# ========================================================
'''
ROUTE FOR POST /services
Sample Request Payload in Expected Format:
{
'name': 'SS Resource Management Services',
'type': 'Resource Management Service',
'address': '3, Brinda Street, West Mambalam, Tamil Nadu',
'region_id': 1,
'email': 'info@ssrms.com',
'phone': '+91-1112223344',
'website': 'www.ssrms.com'
}
Sample Successful JSON Response
{
"created": 1,
"success": true
}
'''
@app.route('/services', methods=['POST'])
@requires_auth('post:services')
def create_service(jwt):
body = request.get_json()
try:
name = body.get('name', None)
type = body.get('type', None)
address = body.get('address', None)
region_id = body.get('region_id', None)
email = body.get('email', None)
phone = body.get('phone', None)
website = body.get('website', None)
image = body.get('image', None)
if (name is None) or (type is None) or (
address is None) or (region_id is None):
abort(422)
new_service = Service(name=name, type=type, address=address,
region_id=region_id, email=email,
phone=phone, website=website, image=image)
new_service.insert()
return jsonify({
'success': True,
'created': new_service.id
}), 200
except BaseException:
print(sys.exc_info())
abort(422)
# -----------------------------------------------------------------------------------------
# ROUTE FOR GET all regions
# GET /regions
# -----------------------------------------------------------------------------------------
'''
ROUTE FOR GET /services
No request Payload
Sample Success Response is below:
{
"services": [
{
"address": "3 Brinda StreetWest MambalamTamil Nadu",
"email": "info@ssrms.com",
"id": 1,
"image": null,
"name": "SS Resource Management Services",
"phone": "911112223344",
"region_id": 1,
"type": "Resource Management Service",
"website": "www.ssrms.com"
},
{
"address": "3 Van Street, West Mambalam, Tamil Nadu",
"email": "info@mmrms.com",
"id": 3,
"image": null,
"name": "MM Resource Management Services",
"phone": "911112223355",
"region_id": 2,
"type": "Resource Management Service",
"website": "www.mmrms.com"
}
],
"success": true
}
'''
@app.route('/services', methods=['GET'])
def get_services():
all_services = Service.query.order_by(Service.id).all()
total_no_services = len(all_services)
if (total_no_services == 0):
abort(404)
current_services = paginate_results(request, all_services)
if (len(current_services) == 0):
abort(404)
return jsonify({
'services': current_services,
'success': True
})
# -----------------------------------------------------------------------------------------
# ROUTE to GET a specific region
# GET /services/<service_id>
# -----------------------------------------------------------------------------------------
'''
ROUTE FOR GET /services/1
No request Payload
Sample Success Response is below
{
"service": {
"address": "3 Brinda StreetWest MambalamTamil Nadu",
"email": "info@ssrms.com",
"id": 1,
"image": null,
"name": "SS Resource Management Services",
"phone": "911112223344",
"region_id": 1,
"type": "Resource Management Service",
"website": "www.ssrms.com"
},
"success": true
} '''
@app.route('/services/<service_id>', methods=['GET'])
def get_service_by_id(service_id):
service = Service.query.get(service_id)
if service is None:
abort(404)
return jsonify({
"service": Service.format(service),
"success": True
}), 200
# -----------------------------------------------------------------------------------------
# ROUTE to update a service
# PATCH /services/<service_id>
# -----------------------------------------------------------------------------------------
'''
ROUTE TO UPDATE Services
PATCH /services/<service_id>
Sample Successful JSON Response
{
"updated": 2,
"success": true
}
'''
@app.route('/services/<service_id>', methods=['PATCH'])
@requires_auth('patch:services')
def update_service(jwt, service_id):
body = request.get_json()
try:
name = body.get('name', None)
type = body.get('type', None)
address = body.get('address', None)
region_id = body.get('region_id', None)
email = body.get('email', None)
phone = body.get('phone', None)
website = body.get('website', None)
image = body.get('image', None)
if (name is None) and (type is None) and (address is None) \
and (region_id is None) and (email is None) \
and (phone is None)\
and (website is None) and (image is None):
abort(422)
service = Service.query.get(service_id)
if (service is None):
abort(402)
if name is not None:
service.name = name
if type is not None:
service.type = type
if address is not None:
service.address = address
if region_id is not None:
service.region_id = region_id
if email is not None:
service.email = email
if phone is not None:
service.phone = phone
if image is not None:
service.image = image
if website is not None:
service.website = website
Service.update(service)
return jsonify({
'success': True,
'updated': service.id
}), 200
except BaseException:
print(sys.exc_info())
abort(500)
'''
ROUTE TO DELETE Service BY ID
DELETE /services/<service_id>
Sample Successful JSON Response
{
"deleted": 2,
"success": true
}
'''
@app.route('/services/<service_id>', methods=['DELETE'])
@requires_auth('delete:services')
def delete_service(jwt, service_id):
service = Service.query.get(service_id)
if service is None:
print(sys.exc_info())
abort(404)
try:
Service.delete(service)
return jsonify({
'success': True,
'deleted': service.id
}), 200
except BaseException:
print(sys.exc_info())
abort(422)
'''
ROUTE FOR APPLICATION ROOT
'''
@app.route('/')
def index():
return "Welcome to Environment Services Portal"
# ----------------------------------------------------------------------------#
# Error Handlers
# ----------------------------------------------------------------------------#
@app.errorhandler(404)
def not_found(error):
return jsonify({
'success': False,
'error': 404,
'message': 'resource not found'
}), 404
@app.errorhandler(400)
def bad_request(error):
return jsonify({
'success': False,
'error': 400,
'message': 'bad request'
}), 400
@app.errorhandler(422)
def request_unprocessable(error):
return jsonify({
'success': False,
'error': 422,
'message': 'request is unprocessable'
}), 422
@app.errorhandler(500)
def internal_server_error(error):
return jsonify({
'success': False,
'error': 500,
'message': 'internal server error'
}), 500
@app.errorhandler(AuthError)
def handle_auth_error(ex):
return jsonify({
"success": False,
"error": ex.status_code,
'message': ex.error
}), 401
return app
app = create_app()
# if __name__ == '__main__':
# app.run(host='0.0.0.0', port=8080, debug=True)