Debian Codegraph @

third_party/python/aiohttp/examples/web_srv_route_table.py

raw
1 #!/usr/bin/env python3
2 """Example for aiohttp.web basic server with table definition for routes."""
3
4 import textwrap
5
6 from aiohttp import web
7
8
9 async def intro(request):
10 txt = textwrap.dedent(
11 """\
12 Type {url}/hello/John {url}/simple or {url}/change_body
13 in browser url bar
14 """
15 ).format(url="127.0.0.1:8080")
16 binary = txt.encode("utf8")
17 resp = web.StreamResponse()
18 resp.content_length = len(binary)
19 resp.content_type = "text/plain"
20 await resp.prepare(request)
21 await resp.write(binary)
22 return resp
23
24
25 async def simple(request):
26 return web.Response(text="Simple answer")
27
28
29 async def change_body(request):
30 resp = web.Response()
31 resp.body = b"Body changed"
32 resp.content_type = "text/plain"
33 return resp
34
35
36 async def hello(request):
37 resp = web.StreamResponse()
38 name = request.match_info.get("name", "Anonymous")
39 answer = ("Hello, " + name).encode("utf8")
40 resp.content_length = len(answer)
41 resp.content_type = "text/plain"
42 await resp.prepare(request)
43 await resp.write(answer)
44 await resp.write_eof()
45 return resp
46
47
48 def init():
49 app = web.Application()
50 app.router.add_routes(
51 [
52 web.get("/", intro),
53 web.get("/simple", simple),
54 web.get("/change_body", change_body),
55 web.get("/hello/{name}", hello),
56 web.get("/hello", hello),
57 ]
58 )
59 return app
60
61
62 web.run_app(init())