File: web_rewrite_headers_middleware.py

package info (click to toggle)
python-aiohttp 0.17.2-1~bpo8%2B1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 2,368 kB
  • sloc: python: 19,899; makefile: 205
file content (47 lines) | stat: -rwxr-xr-x 1,220 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
41
42
43
44
45
46
47
#!/usr/bin/env python3
"""
Example for rewriting response headers by middleware.
"""

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


@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.started:
            response.headers['SERVER'] = "Secured Server Software"
        return response

    return middleware


@asyncio.coroutine
def init(loop):
    app = Application(loop=loop, middlewares=[middleware_factory])
    app.router.add_route('GET', '/', handler)

    requests_handler = app.make_handler()
    srv = yield from loop.create_server(requests_handler, '127.0.0.1', 8080)
    print("Server started at http://127.0.0.1:8080")
    return srv, requests_handler


loop = asyncio.get_event_loop()
srv, requests_handler = loop.run_until_complete(init(loop))
try:
    loop.run_forever()
except KeyboardInterrupt:
    loop.run_until_complete(requests_handler.finish_connections())