File: web_rewrite_headers_middleware.py

package info (click to toggle)
python-aiohttp 1.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 2,288 kB
  • ctags: 4,380
  • sloc: python: 27,221; makefile: 236
file content (40 lines) | stat: -rwxr-xr-x 861 bytes parent folder | download
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
#!/usr/bin/env python3
"""
Example for rewriting response headers by middleware.
"""

import asyncio

from aiohttp.web import Application, HTTPException, Response, run_app


@asyncio.coroutine
def handler(request):
    return Response(text="Everything is fine")


@asyncio.coroutine
def middleware_factory(app, next_handler):

    @asyncio.coroutine
    def middleware(request):
        try:
            response = yield from next_handler(request)
        except HTTPException as exc:
            response = exc
        if not response.prepared:
            response.headers['SERVER'] = "Secured Server Software"
        return response

    return middleware


def init(loop):
    app = Application(loop=loop, middlewares=[middleware_factory])
    app.router.add_get('/', handler)
    return app


loop = asyncio.get_event_loop()
app = init(loop)
run_app(app)