Skip to content

Commit 48dbaf5

Browse files
committed
Add example for server-side cookies
1 parent 78616dc commit 48dbaf5

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

examples/web_cookies.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
#!/usr/bin/env python3
2+
"""Example for aiohttp.web basic server with cookies.
3+
"""
4+
5+
import asyncio
6+
from aiohttp import web
7+
8+
9+
tmpl = '''\
10+
<html>
11+
<body>
12+
<a href="/login">Login</a><br/>
13+
<a href="/logout">Logout</a><br/>
14+
{}
15+
</body>
16+
</html>'''
17+
18+
19+
@asyncio.coroutine
20+
def root(request):
21+
resp = web.Response(content_type='text/html')
22+
resp.text = tmpl.format(request.cookies)
23+
return resp
24+
25+
26+
@asyncio.coroutine
27+
def login(request):
28+
resp = web.HTTPFound(location='/')
29+
resp.set_cookie('AUTH', 'secret')
30+
return resp
31+
32+
33+
@asyncio.coroutine
34+
def logout(request):
35+
resp = web.HTTPFound(location='/')
36+
resp.del_cookie('AUTH')
37+
return resp
38+
39+
40+
@asyncio.coroutine
41+
def init(loop):
42+
app = web.Application(loop=loop)
43+
app.router.add_route('GET', '/', root)
44+
app.router.add_route('GET', '/login', login)
45+
app.router.add_route('GET', '/logout', logout)
46+
47+
handler = app.make_handler()
48+
srv = yield from loop.create_server(handler, '127.0.0.1', 8080)
49+
print("Server started at http://127.0.0.1:8080")
50+
return srv, handler
51+
52+
loop = asyncio.get_event_loop()
53+
srv, handler = loop.run_until_complete(init(loop))
54+
try:
55+
loop.run_forever()
56+
except KeyboardInterrupt:
57+
loop.run_until_complete(handler.finish_connections())

0 commit comments

Comments
 (0)