-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.py
44 lines (28 loc) · 994 Bytes
/
middleware.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
import aiohttp_jinja2
from aiohttp import web
# 404 and 500 error handling
async def handle_404(request):
return aiohttp_jinja2.render_template('404.html', request, {})
async def handle_500(request):
return aiohttp_jinja2.render_template('500.html', request, {})
def create_error_middleware(overrides):
@web.middleware
async def error_middleware(request, handler):
try:
response = await handler(request)
override = overrides.get(response.status)
if override:
return await override(request)
return response
except web.HTTPException as ex:
override = overrides.get(ex.status)
if override:
return await override(request)
raise
return error_middleware
def setup_middleware(app):
error_middleware = create_error_middleware({
404: handle_404,
500: handle_500
})
app.middlewares.append(error_middleware)