Debian Codegraph @

third_party/python/aiohttp/examples/web_classview.py

raw
1 #!/usr/bin/env python3
2 """Example for aiohttp.web class based views."""
3
4
5 import functools
6 import json
7
8 from aiohttp import web
9
10
11 class MyView(web.View):
12 async def get(self):
13 return web.json_response(
14 {
15 "method": "get",
16 "args": dict(self.request.query),
17 "headers": dict(self.request.headers),
18 },
19 dumps=functools.partial(json.dumps, indent=4),
20 )
21
22 async def post(self):
23 data = await self.request.post()
24 return web.json_response(
25 {
26 "method": "post",
27 "args": dict(self.request.query),
28 "data": dict(data),
29 "headers": dict(self.request.headers),
30 },
31 dumps=functools.partial(json.dumps, indent=4),
32 )
33
34
35 async def index(request):
36 txt = """
37 <html>
38 <head>
39 <title>Class based view example</title>
40 </head>
41 <body>
42 <h1>Class based view example</h1>
43 <ul>
44 <li><a href="/">/</a> This page
45 <li><a href="/get">/get</a> Returns GET data.
46 <li><a href="/post">/post</a> Returns POST data.
47 </ul>
48 </body>
49 </html>
50 """
51 return web.Response(text=txt, content_type="text/html")
52
53
54 def init():
55 app = web.Application()
56 app.router.add_get("/", index)
57 app.router.add_get("/get", MyView)
58 app.router.add_post("/post", MyView)
59 return app
60
61
62 web.run_app(init())