-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfunctions.py
78 lines (62 loc) · 2.48 KB
/
functions.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
from config import *
import json
import traceback
from flask import make_response
# Accepted Request content types
accepted_request_types = (
'application/json',
'text/plain',
'text/html'
)
# Accepted Response accept_mimetypes
accepted_response_types = (
'application/json',
'text/plain',
'text/html'
)
def respond_with_json(payload):
try:
response = make_response(json.dumps(payload))
response.mimetype = 'application/json'
return response
except Exception as ex:
traceback.print_exc()
return {'status': 'failed', 'error': str(ex)}
def response_type(request):
# filter for accepted response types:
for accepted_response in accepted_response_types:
if request.accept_mimetypes[accepted_response] == 1:
# return response type
return accepted_response
else:
return raise_error("unsupported response type", request)
def request_type(request):
# filter for accepted request types:
if request.content_type in accepted_request_types:
# make sure JSON is valid
if request.content_type == 'application/json':
if not request.is_json:
return raise_error("malformed json", request)
return request.content_type
else:
return raise_error("unsupported request type", request)
# Error handling
def raise_error(error_type, request=""):
def return_formatted(message):
# TODO/Backlog: reformat into JSON outputs
return str(message)
if error_type == "unsupported response type":
message = "Error: Unsupported Accept-Response Type. Supported are: " + ', '.join(accepted_response_types)
if error_type == "unsupported request type":
message = "Error: Unsupported Request Content-Type (" + request.content_type + "). Supported are: " + ', '.join(accepted_request_types)
if error_type == "malformed json":
message = "Error: Malformed JSON"
if error_type == "no text specified":
message = "Error: No input text specified"
if error_type == "no chunk sequence specified":
message = "Error: Chunk sequence expected. Please use a text specific endpoint for single text tasks."
if error_type == "no id specified":
message = "Error: No id specified"
if error_type == "json expected":
message = "Error: Unexpected Request Content-Type (" + request.content_type + "). Expected Content-Type is application/json"
return return_formatted(message)