-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathviews.py
More file actions
206 lines (151 loc) · 5.37 KB
/
views.py
File metadata and controls
206 lines (151 loc) · 5.37 KB
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
"""
Calls CTS REST classes, functions linked to
CTS REST URLs - Swagger UI
"""
from cts_app.cts_api import cts_rest
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpRequest, HttpResponse
from django.template.loader import render_to_string
from django.shortcuts import render
import json
from django.conf import settings
import logging
import os
import bleach
root_path = os.path.abspath(os.path.dirname(__file__))
@csrf_exempt
def getSwaggerJsonContent(request):
"""
Opens up swagger.json content
"""
swag = open(root_path + '/static/cts_api/swagger.json', 'r').read()
swag_filtered = swag.replace('\n', '').strip()
swag_obj = json.loads(swag_filtered)
response = HttpResponse()
response.write(json.dumps(swag_obj))
return response
@csrf_exempt
def showSwaggerPage(request):
"""
display swagger.json with swagger UI
for CTS API docs/endpoints
"""
return render(request, 'cts_api/swagger_index.html')
@csrf_exempt
def showSwaggerPageV2(request):
return render(request, 'cts_api/swagger_index_v2.html')
@csrf_exempt
def getSwaggerJsonContentV2(request):
"""
Opens up swagger.json content
"""
swag = open(root_path + '/static/cts_api/swagger-v2.json', 'r').read()
swag_filtered = swag.replace('\n', '').strip()
swag_obj = json.loads(swag_filtered)
response = HttpResponse()
response.write(json.dumps(swag_obj))
return response
@csrf_exempt
def getCTSEndpoints(request):
"""
CTS REST calculator endpoints
"""
cts_obj = cts_rest.CTS_REST()
return cts_obj.getCTSREST()
@csrf_exempt
def getCalcEndpoints(request, endpoint=None):
cts_obj = cts_rest.CTS_REST()
if not endpoint in cts_obj.endpoints:
return HttpResponse(json.dumps({'error': "endpoint not recognized"}), content_type='application/json')
else:
return cts_rest.CTS_REST().getCalcEndpoints(endpoint)
@csrf_exempt
def getCalcInputs(request, calc=None):
request_params = json.loads(request.body)
prop, chemical = None, None
if 'prop' in request_params:
prop = request_params['prop']
if 'chemical' in request_params:
chemical = request_params['chemical']
try:
return cts_rest.CTS_REST().getCalcInputs(chemical, calc, prop)
except Exception as e:
return HttpResponse(json.dumps({'error': "{}".format(e)}), content_type='application/json')
@csrf_exempt
def runCalc(request, calc=None):
logging.warning("VIEWS RUN CALC CALLED")
request_params = smiles_backslash_fix_for_swagger(request)
request_params = bleach_request(request_params)
# try:
return cts_rest.CTS_REST().runCalc(calc, request_params)
# except Exception as e:
# logging.warning("~~~ exception occurring at cts_api views runCalc!")
# logging.warning("exception: {}".format(e))
# return HttpResponse(json.dumps({'error': "Error requesting data from {}".format(calc)}), content_type='application/json')
@csrf_exempt
def get_chem_info(request):
request_post = {}
if 'message' in request.POST:
# accounts for request from nodejs (e.g., cts_stress)
request_post = json.loads(request.POST.get('message'))
else:
request_post = request.POST
if len(request_post) < 1 and len(request.body) > 1:
# accounts for request being in body (e.g., postman)
request_post = json.loads(request.body.decode('utf-8'))
request_post = bleach_request(request_post)
try:
return cts_rest.getChemicalEditorData(request_post)
except Exception as e:
logging.warning("cts rest exception: {}".format(e))
return HttpResponse(json.dumps({'error": "Error getting chemical information'}))
@csrf_exempt
def cts_rest_proxy(request):
"""
CTS API v2 entry point.
"""
request_params = smiles_backslash_fix_for_swagger(request)
if request.method == "GET":
# handle get request (return calc info)
try:
return cts_rest.CTS_REST().getCalcInputs(request_params['chemical'], request_params['calc'], request_params['prop'])
except Exception as e:
return HttpResponse(json.dumps({'error': "{}".format(e)}), content_type='application/json')
elif request.method == "POST":
# run calc model
try:
return cts_rest.CTS_REST().runCalc(calc, request_params)
except Exception as e:
logging.warning("exception: {}".format(e))
return HttpResponse(json.dumps({'error': "Error requesting data from {}".format(calc)}), content_type='application/json')
def smiles_backslash_fix_for_swagger(request):
"""
Workaround for backslash encoding issue that occurs when using
Swagger API docs.
"""
try:
request_body = request.body
request_params = json.loads(request_body)
except ValueError as ve:
# swagger api issue with not encoding backslash in smiles properly
logging.warning("trouble converting request body to json obj, checking for backslashes in smiles..")
request_string = str(request_body, 'utf-8')
if '\\' in request_string:
logging.warning("backslash found, temporarily replacing with '_', parsing, then re-replacing..")
request_string = request_string.replace('\\', '_') # temp replace backslash for json parse
request_params = json.loads(request_string)
request_params['chemical'] = request_params['chemical'].replace('_', '\\') # put backslash back
else:
request_params = request.POST
return request_params
def bleach_request(request_post):
"""
Loops request key:vals and sanitizes them with bleach.
"""
bleached_request = {}
for key, val in request_post.items():
if type(val) == str:
bleached_request[key] = bleach.clean(val)
else:
bleached_request[key] = val
return bleached_request