32
32
import logging
33
33
from functools import wraps
34
34
from flask import Flask , jsonify , request , url_for , make_response , abort
35
- from models import Pet , DataValidationError
36
- from app import app
35
+ from flask_api import status # HTTP Status Codes
36
+ from service .models import Pet , DataValidationError
37
+ from service import app
37
38
38
39
# Pull options from environment
39
40
DEBUG = (os .getenv ('DEBUG' , 'False' ) == 'True' )
40
41
PORT = os .getenv ('PORT' , '5000' )
41
42
42
- # Status Codes
43
- HTTP_200_OK = 200
44
- HTTP_201_CREATED = 201
45
- HTTP_204_NO_CONTENT = 204
46
- HTTP_400_BAD_REQUEST = 400
47
- HTTP_404_NOT_FOUND = 404
48
- HTTP_409_CONFLICT = 409
49
- HTTP_415_UNSUPPORTED_MEDIA_TYPE = 415
50
-
51
43
######################################################################
52
44
# Error Handlers
53
45
######################################################################
@@ -56,40 +48,51 @@ def request_validation_error(error):
56
48
""" Handles Value Errors from bad data """
57
49
return bad_request (error )
58
50
59
- @app .errorhandler (400 )
51
+ @app .errorhandler (status . HTTP_400_BAD_REQUEST )
60
52
def bad_request (error ):
61
53
""" Handles bad reuests with 400_BAD_REQUEST """
62
- message = error .message or str (error )
63
- app .logger .error (message )
64
- return jsonify (status = 400 , error = 'Bad Request' , message = message ), 400
54
+ message = str (error )
55
+ app .logger .warning (message )
56
+ return jsonify (status = status .HTTP_400_BAD_REQUEST ,
57
+ error = 'Bad Request' ,
58
+ message = message ), status .HTTP_400_BAD_REQUEST
65
59
66
- @app .errorhandler (404 )
60
+ @app .errorhandler (status . HTTP_404_NOT_FOUND )
67
61
def not_found (error ):
68
62
""" Handles resources not found with 404_NOT_FOUND """
69
- message = error .message or str (error )
70
- app .logger .error (message )
71
- return jsonify (status = 404 , error = 'Not Found' , message = message ), 404
63
+ message = str (error )
64
+ app .logger .warning (message )
65
+ return jsonify (status = status .HTTP_404_NOT_FOUND ,
66
+ error = 'Not Found' ,
67
+ message = message ), status .HTTP_404_NOT_FOUND
72
68
73
- @app .errorhandler (405 )
69
+ @app .errorhandler (status . HTTP_405_METHOD_NOT_ALLOWED )
74
70
def method_not_supported (error ):
75
71
""" Handles unsuppoted HTTP methods with 405_METHOD_NOT_SUPPORTED """
76
- message = error .message or str (error )
77
- app .logger .error (message )
78
- return jsonify (status = 405 , error = 'Method not Allowed' , message = message ), 405
72
+ message = str (error )
73
+ app .logger .warning (message )
74
+ return jsonify (status = status .HTTP_405_METHOD_NOT_ALLOWED ,
75
+ error = 'Method not Allowed' ,
76
+ message = message ), status .HTTP_405_METHOD_NOT_ALLOWED
79
77
80
- @app .errorhandler (415 )
78
+ @app .errorhandler (status . HTTP_415_UNSUPPORTED_MEDIA_TYPE )
81
79
def mediatype_not_supported (error ):
82
80
""" Handles unsuppoted media requests with 415_UNSUPPORTED_MEDIA_TYPE """
83
- message = error .message or str (error )
84
- app .logger .error (message )
85
- return jsonify (status = 415 , error = 'Unsupported media type' , message = message ), 415
81
+ message = str (error )
82
+ app .logger .warning (message )
83
+ return jsonify (status = status .HTTP_415_UNSUPPORTED_MEDIA_TYPE ,
84
+ error = 'Unsupported media type' ,
85
+ message = message ), status .HTTP_415_UNSUPPORTED_MEDIA_TYPE
86
86
87
- @app .errorhandler (500 )
87
+ @app .errorhandler (status . HTTP_500_INTERNAL_SERVER_ERROR )
88
88
def internal_server_error (error ):
89
89
""" Handles unexpected server error with 500_SERVER_ERROR """
90
- message = error . message or str (error )
90
+ message = str (error )
91
91
app .logger .error (message )
92
- return jsonify (status = 500 , error = 'Internal Server Error' , message = message ), 500
92
+ return jsonify (status = status .HTTP_500_INTERNAL_SERVER_ERROR ,
93
+ error = 'Internal Server Error' ,
94
+ message = message ), status .HTTP_500_INTERNAL_SERVER_ERROR
95
+
93
96
94
97
######################################################################
95
98
# DECORATORS
@@ -102,15 +105,15 @@ def decorator(func):
102
105
def wrapper (* args , ** kwargs ):
103
106
""" Checks that the content type is correct """
104
107
if not 'Content-Type' in request .headers :
105
- abort (HTTP_415_UNSUPPORTED_MEDIA_TYPE ,
108
+ abort (status . HTTP_415_UNSUPPORTED_MEDIA_TYPE ,
106
109
'Content-Type must be set' )
107
110
108
111
for content_type in content_types :
109
112
if request .headers ['Content-Type' ] == content_type :
110
113
return func (* args , ** kwargs )
111
114
112
115
app .logger .error ('Invalid Content-Type: %s' , request .headers ['Content-Type' ])
113
- abort (HTTP_415_UNSUPPORTED_MEDIA_TYPE ,
116
+ abort (status . HTTP_415_UNSUPPORTED_MEDIA_TYPE ,
114
117
'Content-Type must be {}' .format (content_types ))
115
118
return wrapper
116
119
return decorator
@@ -145,7 +148,7 @@ def list_pets():
145
148
pets = Pet .all ()
146
149
147
150
results = [pet .serialize () for pet in pets ]
148
- return make_response (jsonify (results ), HTTP_200_OK )
151
+ return make_response (jsonify (results ), status . HTTP_200_OK )
149
152
150
153
######################################################################
151
154
# RETRIEVE A PET
@@ -160,8 +163,8 @@ def get_pets(pet_id):
160
163
app .logger .info ('Request to get Pet with id %s' , pet_id )
161
164
pet = Pet .find (pet_id )
162
165
if not pet :
163
- abort (HTTP_404_NOT_FOUND , "Pet with id '{}' was not found." .format (pet_id ))
164
- return make_response (jsonify (pet .serialize ()), HTTP_200_OK )
166
+ abort (status . HTTP_404_NOT_FOUND , "Pet with id '{}' was not found." .format (pet_id ))
167
+ return make_response (jsonify (pet .serialize ()), status . HTTP_200_OK )
165
168
166
169
######################################################################
167
170
# ADD A NEW PET
@@ -192,7 +195,7 @@ def create_pets():
192
195
pet .deserialize (data )
193
196
pet .save ()
194
197
message = pet .serialize ()
195
- return make_response (jsonify (message ), HTTP_201_CREATED ,
198
+ return make_response (jsonify (message ), status . HTTP_201_CREATED ,
196
199
{'Location' : url_for ('get_pets' , pet_id = pet .id , _external = True )})
197
200
198
201
######################################################################
@@ -209,11 +212,11 @@ def update_pets(pet_id):
209
212
app .logger .info ('Request to update Pet with id %s' , pet_id )
210
213
pet = Pet .find (pet_id )
211
214
if not pet :
212
- abort (HTTP_404_NOT_FOUND , "Pet with id '{}' was not found." .format (pet_id ))
215
+ abort (status . HTTP_404_NOT_FOUND , "Pet with id '{}' was not found." .format (pet_id ))
213
216
pet .deserialize (request .get_json ())
214
217
pet .id = pet_id
215
218
pet .save ()
216
- return make_response (jsonify (pet .serialize ()), HTTP_200_OK )
219
+ return make_response (jsonify (pet .serialize ()), status . HTTP_200_OK )
217
220
218
221
219
222
######################################################################
@@ -230,7 +233,7 @@ def delete_pets(pet_id):
230
233
pet = Pet .find (pet_id )
231
234
if pet :
232
235
pet .delete ()
233
- return make_response ('' , HTTP_204_NO_CONTENT )
236
+ return make_response ('' , status . HTTP_204_NO_CONTENT )
234
237
235
238
######################################################################
236
239
# PURCHASE A PET
@@ -241,12 +244,12 @@ def purchase_pets(pet_id):
241
244
app .logger .info ('Request to purchase Pet with id %s' , pet_id )
242
245
pet = Pet .find (pet_id )
243
246
if not pet :
244
- abort (HTTP_404_NOT_FOUND , "Pet with id '{}' was not found." .format (pet_id ))
247
+ abort (status . HTTP_404_NOT_FOUND , "Pet with id '{}' was not found." .format (pet_id ))
245
248
if not pet .available :
246
- abort (HTTP_400_BAD_REQUEST , "Pet with id '{}' is not available." .format (pet_id ))
249
+ abort (status . HTTP_400_BAD_REQUEST , "Pet with id '{}' is not available." .format (pet_id ))
247
250
pet .available = False
248
251
pet .save ()
249
- return make_response (jsonify (pet .serialize ()), HTTP_200_OK )
252
+ return make_response (jsonify (pet .serialize ()), status . HTTP_200_OK )
250
253
251
254
252
255
######################################################################
@@ -273,13 +276,13 @@ def data_reset():
273
276
# if request.headers['Content-Type'] == content_type:
274
277
# return
275
278
# app.logger.error('Invalid Content-Type: %s', request.headers['Content-Type'])
276
- # abort(HTTP_415_UNSUPPORTED_MEDIA_TYPE, 'Content-Type must be {}'.format(content_type))
279
+ # abort(status. HTTP_415_UNSUPPORTED_MEDIA_TYPE, 'Content-Type must be {}'.format(content_type))
277
280
278
281
# @app.before_first_request
279
282
def initialize_logging (log_level = logging .INFO ):
280
283
""" Initialized the default logging to STDOUT """
281
284
if not app .debug :
282
- print 'Setting up logging...'
285
+ print ( 'Setting up logging...' )
283
286
# Set up default logging for submodules to use STDOUT
284
287
# datefmt='%m/%d/%Y %I:%M:%S %p'
285
288
fmt = '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'
@@ -301,8 +304,8 @@ def initialize_logging(log_level=logging.INFO):
301
304
# M A I N
302
305
######################################################################
303
306
if __name__ == "__main__" :
304
- print "************************************************************"
305
- print " P E T R E S T A P I S E R V I C E "
306
- print "************************************************************"
307
+ print ( "************************************************************" )
308
+ print ( " P E T R E S T A P I S E R V I C E " )
309
+ print ( "************************************************************" )
307
310
initialize_logging (app .config ['LOGGING_LEVEL' ])
308
311
app .run (host = '0.0.0.0' , port = int (PORT ), debug = DEBUG )
0 commit comments