-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrest-server.py
88 lines (78 loc) · 2.68 KB
/
rest-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
#!/usr/bin/env python3
##
## Sample Flask REST server implementing two methods
##
## Endpoint /api/image is a POST method taking a body containing an image
## It returns a JSON document providing the 'width' and 'height' of the
## image that was provided. The Python Image Library (pillow) is used to
## proce#ss the image
##
## Endpoint /api/add/X/Y is a post or get method returns a JSON body
## containing the sum of 'X' and 'Y'. The body of the request is ignored
##
##
from flask import Flask, request, Response
import jsonpickle
from PIL import Image
import base64
import io
# Initialize the Flask application
app = Flask(__name__)
import logging
log = logging.getLogger('werkzeug')
log.setLevel(logging.DEBUG)
@app.route('/api/add/<int:a>/<int:b>', methods=['GET', 'POST'])
def add(a,b):
response = {'sum' : str( a + b)}
response_pickled = jsonpickle.encode(response)
return Response(response=response_pickled, status=200, mimetype="application/json")
# route http posts to this method
@app.route('/api/rawimage', methods=['POST'])
def rawimage():
r = request
# convert the data to a PIL image type so we can extract dimensions
try:
ioBuffer = io.BytesIO(r.data)
img = Image.open(ioBuffer)
# build a response dict to send back to client
response = {
'width' : img.size[0],
'height' : img.size[1]
}
except:
response = { 'width' : 0, 'height' : 0}
# encode response using jsonpickle
response_pickled = jsonpickle.encode(response)
return Response(response=response_pickled, status=200, mimetype="application/json")
@app.route('/api/dotproduct', methods=['POST'])
def dotproduct():
r = request
try:
json = jsonpickle.decode(r.data)
c = 0
for a,b in zip(json['a'],json['b']):
c += a*b
response = {'dotproduct' : str( c )}
except:
response = {'dotproduct' : 'Something Wrong!'}
# encode response using jsonpickle
response_pickled = jsonpickle.encode(response)
return Response(response=response_pickled, status=200, mimetype="application/json")
# route http posts to this method
@app.route('/api/jsonimage', methods=['POST'])
def jsonimage():
r=request
try:
ioBuffer = io.BytesIO(base64.b64decode(r.data))
img=Image.open(ioBuffer)
response = {
'width' : img.size[0],
'height' : img.size[1]
}
except Exception as e:
print (e)
response = { 'width' : 0, 'height' : 0}
response_pickled = jsonpickle.encode(response)
return Response(response=response_pickled, status=200, mimetype="application/json")
# start flask app
app.run(host="0.0.0.0", port=5000)