Debian Codegraph @

third_party/python/aiohttp/examples/web_srv_route_deco.py

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