This repository has been archived by the owner on Feb 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 411
/
Copy pathapp.py
370 lines (321 loc) · 13.1 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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
import sys
import typing
import werkzeug
from apistar import exceptions
from apistar.http import HTMLResponse, JSONResponse, PathParams, Response
from apistar.server.adapters import ASGItoWSGIAdapter
from apistar.server.asgi import (
ASGI_COMPONENTS, ASGIReceive, ASGIScope, ASGISend
)
from apistar.server.components import Component, ReturnValue
from apistar.server.core import Route, generate_document
from apistar.server.injector import ASyncInjector, Injector
from apistar.server.router import Router
from apistar.server.staticfiles import ASyncStaticFiles, StaticFiles
from apistar.server.templates import Templates
from apistar.server.validation import VALIDATION_COMPONENTS
from apistar.server.wsgi import (
RESPONSE_STATUS_TEXT, WSGI_COMPONENTS, WSGIEnviron, WSGIStartResponse
)
class App():
interface = 'wsgi'
def __init__(self,
routes,
template_dir=None,
static_dir=None,
packages=None,
schema_url='/schema/',
docs_url='/docs/',
static_url='/static/',
components=None,
event_hooks=None):
packages = tuple() if packages is None else tuple(packages)
if docs_url is not None:
packages += ('apistar',)
if static_dir is None and not packages:
static_url = None
# Guard against some easy misconfiguration.
if components:
msg = 'components must be a list of instances of Component.'
assert all([isinstance(component, Component) for component in components]), msg
if event_hooks:
msg = 'event_hooks must be a list.'
assert isinstance(event_hooks, (list, tuple)), msg
routes = routes + self.include_extra_routes(schema_url, docs_url, static_url)
self.init_document(routes)
self.init_router(routes)
self.init_templates(template_dir, packages)
self.init_staticfiles(static_url, static_dir, packages)
self.init_injector(components)
self.debug = False
self.event_hooks = event_hooks
# Ensure event hooks can all be instantiated.
self.get_event_hooks()
def include_extra_routes(self, schema_url=None, docs_url=None, static_url=None):
extra_routes = []
from apistar.server.handlers import serve_documentation, serve_schema, serve_static_wsgi
if schema_url:
extra_routes += [
Route(schema_url, method='GET', handler=serve_schema, documented=False)
]
if docs_url:
extra_routes += [
Route(docs_url, method='GET', handler=serve_documentation, documented=False)
]
if static_url:
static_url = static_url.rstrip('/') + '/{+filename}'
extra_routes += [
Route(
static_url, method='GET', handler=serve_static_wsgi,
name='static', documented=False, standalone=True
)
]
return extra_routes
def init_document(self, routes):
self.document = generate_document(routes)
def init_router(self, routes):
self.router = Router(routes)
def init_templates(self, template_dir: str=None, packages: typing.Sequence[str]=None):
if not template_dir and not packages:
self.templates = None
else:
template_globals = {
'reverse_url': self.reverse_url,
'static_url': self.static_url
}
self.templates = Templates(template_dir, packages, template_globals)
def init_staticfiles(self, static_url: str, static_dir: str=None, packages: typing.Sequence[str]=None):
if not static_dir and not packages:
self.statics = None
else:
self.statics = StaticFiles(static_url, static_dir, packages)
def init_injector(self, components=None):
components = components if components else []
components = list(WSGI_COMPONENTS + VALIDATION_COMPONENTS) + components
initial_components = {
'environ': WSGIEnviron,
'start_response': WSGIStartResponse,
'exc': Exception,
'app': App,
'path_params': PathParams,
'route': Route,
'response': Response
}
self.injector = Injector(components, initial_components)
def get_event_hooks(self):
event_hooks = []
for hook in self.event_hooks or []:
if isinstance(hook, type):
# New style usage, instantiate hooks on requests.
event_hooks.append(hook())
else:
# Old style usage, to be deprecated on the next version bump.
event_hooks.append(hook)
on_request = [
hook.on_request for hook in event_hooks
if hasattr(hook, 'on_request')
]
on_response = [
hook.on_response for hook in reversed(event_hooks)
if hasattr(hook, 'on_response')
]
on_error = [
hook.on_error for hook in reversed(event_hooks)
if hasattr(hook, 'on_error')
]
return on_request, on_response, on_error
def static_url(self, filename):
return self.router.reverse_url('static', filename=filename)
def reverse_url(self, name: str, **params):
return self.router.reverse_url(name, **params)
def render_template(self, path: str, **context):
return self.templates.render_template(path, **context)
def serve(self, host, port, debug=False, **options):
self.debug = debug
if 'use_debugger' not in options:
options['use_debugger'] = debug
if 'use_reloader' not in options:
options['use_reloader'] = debug
werkzeug.run_simple(host, port, self, **options)
def render_response(self, return_value: ReturnValue) -> Response:
if isinstance(return_value, Response):
return return_value
elif isinstance(return_value, str):
return HTMLResponse(return_value)
return JSONResponse(return_value)
def exception_handler(self, exc: Exception) -> Response:
if isinstance(exc, exceptions.HTTPException):
return JSONResponse(exc.detail, exc.status_code, exc.get_headers())
raise
def error_handler(self) -> Response:
return JSONResponse('Server error', 500, exc_info=sys.exc_info())
def finalize_wsgi(self, response: Response, start_response: WSGIStartResponse):
if self.debug and response.exc_info is not None:
exc_info = response.exc_info
raise exc_info[0].with_traceback(exc_info[1], exc_info[2])
start_response(
RESPONSE_STATUS_TEXT[response.status_code],
list(response.headers),
response.exc_info
)
return [response.content]
def __call__(self, environ, start_response):
state = {
'environ': environ,
'start_response': start_response,
'exc': None,
'app': self,
'path_params': None,
'route': None,
'response': None,
}
method = environ['REQUEST_METHOD'].upper()
path = environ['PATH_INFO']
if self.event_hooks is None:
on_request, on_response, on_error = [], [], []
else:
on_request, on_response, on_error = self.get_event_hooks()
try:
route, path_params = self.router.lookup(path, method)
state['route'] = route
state['path_params'] = path_params
if route.standalone:
funcs = [route.handler]
else:
funcs = (
on_request +
[route.handler, self.render_response] +
on_response +
[self.finalize_wsgi]
)
return self.injector.run(funcs, state)
except Exception as exc:
try:
state['exc'] = exc
funcs = (
[self.exception_handler] +
on_response +
[self.finalize_wsgi]
)
return self.injector.run(funcs, state)
except Exception as inner_exc:
try:
state['exc'] = inner_exc
self.injector.run(on_error, state)
finally:
funcs = [self.error_handler, self.finalize_wsgi]
return self.injector.run(funcs, state)
class ASyncApp(App):
interface = 'asgi'
def include_extra_routes(self, schema_url=None, docs_url=None, static_url=None):
extra_routes = []
from apistar.server.handlers import serve_documentation, serve_schema, serve_static_asgi
if schema_url:
extra_routes += [
Route(schema_url, method='GET', handler=serve_schema, documented=False)
]
if docs_url:
extra_routes += [
Route(docs_url, method='GET', handler=serve_documentation, documented=False)
]
if static_url:
static_url = static_url.rstrip('/') + '/{+filename}'
extra_routes += [
Route(
static_url, method='GET', handler=serve_static_asgi,
name='static', documented=False, standalone=True
)
]
return extra_routes
def init_injector(self, components=None):
components = components if components else []
components = list(ASGI_COMPONENTS + VALIDATION_COMPONENTS) + components
initial_components = {
'scope': ASGIScope,
'receive': ASGIReceive,
'send': ASGISend,
'exc': Exception,
'app': App,
'path_params': PathParams,
'route': Route,
'response': Response,
}
self.injector = ASyncInjector(components, initial_components)
def init_staticfiles(self, static_url: str, static_dir: str=None, packages: typing.Sequence[str]=None):
if not static_dir and not packages:
self.statics = None
else:
self.statics = ASyncStaticFiles(static_url, static_dir, packages)
def __call__(self, scope):
async def asgi_callable(receive, send):
state = {
'scope': scope,
'receive': receive,
'send': send,
'exc': None,
'app': self,
'path_params': None,
'route': None
}
method = scope['method']
path = scope['path']
if self.event_hooks is None:
on_request, on_response, on_error = [], [], []
else:
on_request, on_response, on_error = self.get_event_hooks()
try:
route, path_params = self.router.lookup(path, method)
state['route'] = route
state['path_params'] = path_params
if route.standalone:
funcs = [route.handler]
else:
funcs = (
on_request +
[route.handler, self.render_response] +
on_response +
[self.finalize_asgi]
)
await self.injector.run_async(funcs, state)
except Exception as exc:
try:
state['exc'] = exc
funcs = (
[self.exception_handler] +
on_response +
[self.finalize_asgi]
)
await self.injector.run_async(funcs, state)
except Exception as inner_exc:
try:
state['exc'] = inner_exc
await self.injector.run_async(on_error, state)
finally:
funcs = [self.error_handler, self.finalize_asgi]
await self.injector.run_async(funcs, state)
return asgi_callable
async def finalize_asgi(self, response: Response, send: ASGISend, scope: ASGIScope):
if response.exc_info is not None:
if self.debug or scope.get('raise_exceptions', False):
exc_info = response.exc_info
raise exc_info[0].with_traceback(exc_info[1], exc_info[2])
await send({
'type': 'http.response.start',
'status': response.status_code,
'headers': [
[key.encode(), value.encode()]
for key, value in response.headers
]
})
await send({
'type': 'http.response.body',
'body': response.content
})
def serve(self, host, port, debug=False, **options):
self.debug = debug
if 'use_debugger' not in options:
options['use_debugger'] = debug
if 'use_reloader' not in options:
options['use_reloader'] = debug
wsgi = ASGItoWSGIAdapter(self, raise_exceptions=debug)
werkzeug.run_simple(host, port, wsgi, **options)