forked from ExposuresProvider/icees-api
-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
217 lines (178 loc) · 5.63 KB
/
app.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
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
207
208
209
210
211
212
213
214
215
216
217
"""ICEES API entrypoint."""
from functools import wraps
import inspect
import json
import logging
from logging.handlers import TimedRotatingFileHandler
import os
from pathlib import Path
from time import strftime
from typing import Any
from jsonschema import ValidationError
from fastapi import FastAPI, Request
from fastapi.encoders import jsonable_encoder
from fastapi.openapi.utils import get_openapi
from starlette.responses import Response, JSONResponse
from structlog import wrap_logger
from structlog.processors import JSONRenderer
import yaml
from features import format_
from features.knowledgegraph import TOOL_VERSION
from handlers import ROUTER
with open("static/api_description.html", "r") as stream:
description = stream.read()
OPENAPI_HOST = os.getenv('OPENAPI_HOST', 'localhost:8080')
OPENAPI_SCHEME = os.getenv('OPENAPI_SCHEME', 'http')
class NaNResponse(JSONResponse):
"""JSONResponse subclass inserting null for NaNs."""
media_type = "application/json"
def render(self, content: Any) -> bytes:
"""Convert to str."""
return json.dumps(
content,
ensure_ascii=False,
allow_nan=True,
indent=None,
separators=(",", ":"),
).replace(":NaN,", ":null,").encode("utf-8")
APP = FastAPI(
title="ICEES API",
description=description,
version=TOOL_VERSION,
servers=[
{"url": f"{OPENAPI_SCHEME}://{OPENAPI_HOST}"},
],
docs_url="/apidocs",
default_response_class=NaNResponse,
redoc_url=None,
)
def custom_openapi():
"""Build custom OpenAPI schema."""
if APP.openapi_schema:
return APP.openapi_schema
extra_info_file = Path(__file__).parent / "openapi-info.yml"
with open(extra_info_file) as stream:
extra_info = yaml.load(stream, Loader=yaml.SafeLoader)
openapi_schema = get_openapi(
title=APP.title,
description=APP.description,
version=APP.version,
servers=APP.servers,
routes=APP.routes,
tags=[
{
"name": "translator",
},
{
"name": "reasoner",
}
],
)
openapi_schema["info"].update(extra_info)
APP.openapi_schema = openapi_schema
return APP.openapi_schema
APP.openapi = custom_openapi
with open('terms.txt', 'r') as content_file:
terms_and_conditions = content_file.read()
LOGGER = logging.getLogger()
LOGGER.setLevel(logging.INFO)
HANDLER = TimedRotatingFileHandler(os.path.join(
os.environ["ICEES_API_LOG_PATH"],
"server",
))
LOGGER.addHandler(HANDLER)
LOGGER = wrap_logger(LOGGER, processors=[JSONRenderer()])
@APP.middleware("http")
async def fix_tabular_outputs(request: Request, call_next):
"""Fix tabular outputs."""
response = await call_next(request)
timestamp = strftime('%Y-%b-%d %H:%M:%S')
LOGGER.info(
event="request",
timestamp=timestamp,
remote_addr=request.client.host,
method=request.method,
schema=request.url.scheme,
full_path=request.url.path,
# data=(await request.body()).decode('utf-8'),
response_status=response.status_code,
# x_forwarded_for=request.headers.getlist("X-Forwarded-For"),
)
return response
def jsonable_safe(obj):
"""Convert to JSON-able, if possible.
Based on fastapi.encoders.jsonable_encoder.
"""
try:
return jsonable_encoder(obj)
except:
return obj
def prepare_output(func):
"""Prepare output."""
@wraps(func)
def wrapper(*args, request=None, **kwargs):
"""Wrap func."""
# convert arguments to jsonable, where possible
args = [jsonable_safe(arg) for arg in args]
kwargs = {
key: jsonable_safe(value) if key != "conn" else value
for key, value in kwargs.items()
}
# run func, logging errors
try:
return_value = func(*args, **kwargs)
except ValidationError as err:
LOGGER.exception(err)
return_value = {"return value": e.message}
except Exception as err:
LOGGER.exception(err)
return_value = {"return value": str(err)}
# return tabular data, if requested
if request.headers["accept"] == "text/tabular":
content = format_.format_tabular(
terms_and_conditions,
return_value.get("return value", return_value),
)
return Response(
content,
media_type="text/tabular"
)
# add terms and conditions
return {
"terms and conditions": terms_and_conditions,
**return_value,
}
# add `request` to function signature
# without this, FastAPI will not send it
wrapper.__signature__ = inspect.Signature(
[inspect.Parameter(
"request",
inspect.Parameter.POSITIONAL_OR_KEYWORD,
annotation=Request,
)]
+ list(inspect.signature(func).parameters.values())
)
wrapper.__annotations__ = {
**func.__annotations__,
"request": Request,
}
return wrapper
for route in ROUTER.routes:
APP.add_api_route(
route.path,
(
prepare_output(route.endpoint)
if route.path != "/predicates" else
route.endpoint
),
responses={
200: {
"content": {"text/tabular": {}},
"description": "Return the tabular output.",
}
},
response_model=route.response_model,
tags=route.tags,
deprecated=route.deprecated,
methods=route.methods,
)