-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfalcon_gateway.py
74 lines (63 loc) · 2.92 KB
/
falcon_gateway.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
# falcon_gateway.py
import falcon
import os
import json
import pickle
from data_handler import invoke_predict
# Falcon follows the REST architectural style, meaning (among
# other things) that you think in terms of resources and state
# transitions, which map to HTTP verbs.
class InfoResource(object):
def on_get(self, req, resp):
"""Handles GET requests"""
resp.status = falcon.HTTP_200 # This is the default status
resp.body = ('\nThis is an API for a deployed Datmo model, '
'where it takes flower lengths as input and returns the predicted Iris species.\n'
'To learn more about this model, send a GET request to the /predicts endpoint or visit the repository online at: \n\n'
'https://datmo.com/nmwalsh/falcon-api-model\n\n')
class PredictsResource(object):
def on_get(self, req, resp):
"""Handles GET requests"""
resp.status = falcon.HTTP_200 # This is the default status
resp.body = ('\nThis is the PREDICT endpoint. \n'
'Both requests and responses are served in JSON. \n'
'\n'
'INPUT: Flower Lengths (in cm) \n'
' "sepal_length":[num] \n'
' "sepal_width": [num] \n'
' "petal_length":[num] \n'
' "petal_width": [num] \n\n'
'OUTPUT: Prediction (Species) \n'
' "Species": [string] \n\n')
def on_post(self, req, resp):
"""Handles POST requests"""
try:
raw_json = req.stream.read()
except Exception as ex:
raise falcon.HTTPError(falcon.HTTP_400,
'Error',
ex.message)
try:
result_json = json.loads(raw_json.decode(), encoding='utf-8')
# For Python 2.x, replace with
# result_json = json.loads(raw_json, encoding='utf-8')
except ValueError:
raise falcon.HTTPError(falcon.HTTP_400,
'Malformed JSON',
'Could not decode the request body. The '
'JSON was incorrect.')
# loading model file
model_filename = os.path.join('model.dat')
model = pickle.load(open(model_filename, 'rb'))
resp.status = falcon.HTTP_200
resp.body = json.dumps(invoke_predict(model, raw_json))
# For Python 2.x, replace with
# resp.body = json.dumps(invoke_predict(model, raw_json), encoding='utf-8') encoding not necessary in python3.
# falcon.API instances are callable WSGI apps. Never change this.
app = falcon.API()
# Resources are represented by long-lived class instances. Each Python class becomes a different "URL directory"
info = InfoResource()
predicts = PredictsResource()
# things will handle all requests to the '/things' URL path
app.add_route('/info', info)
app.add_route('/predicts', predicts)