Cookie
获取Cookie
使用aiohttp.web.Request
的cookies
对象,可以获取已设置的Cookie键值对的dict。
设置Cookie
使用aiohttp.web.Response
的set_cookie(...)
方法,可以设置Cookie。参数含义如下:
- name (str) - cookie的名称。
- value (str) - cookie的值。
- expires (int) - 设置多少秒后cookie会失效。默认是关闭浏览器后失效。
- domain (str) - 设置cookie生效的domain。
- secure (bool) - 如果为True,则cookie只能在HTTPS下生效。
- path (str) - 设置cookie生效的路径。
示例
from aiohttp.web import Request, Response
from lessweb import Bridge, post_mapping, get_mapping
@post_mapping('/set')
async def set_user(*, name: str):
resp = Response(text='ok', content_type='text/html', charset='utf-8')
resp.set_cookie('username', name)
return resp
@get_mapping('/get')
async def get_user(request: Request):
username = request.cookies.get('username')
return {'user': username}
if __name__ == '__main__':
bridge = Bridge()
bridge.add_route(set_user)
bridge.add_route(get_user)
bridge.run_app()
请求1: curl -i -X POST "http://localhost:8080/set?name=John"
返回:
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 2
Set-Cookie: username=John; Path=/
...
ok
请求2: curl --cookie "username=John" "http://localhost:8080/get"
返回: {"user": "John"}