Cookies

Cookies are pieces of data which persist inside a user’s browser. Sanic can both read and write cookies, which are stored as key-value pairs.

警告

Cookies can be freely altered by the client. Therefore you cannot just store data such as login information in cookies as-is, as they can be freely altered by the client. To ensure data you store in cookies is not forged or tampered with by the client, use something like itsdangerous to cryptographically sign the data.

Reading cookies

A user’s cookies can be accessed via the Request object’s cookies dictionary.

  1. from sanic.response import text
  2.  
  3. @app.route("/cookie")
  4. async def test(request):
  5. test_cookie = request.cookies.get('test')
  6. return text("Test cookie set to: {}".format(test_cookie))

Writing cookies

When returning a response, cookies can be set on the Response object.

  1. from sanic.response import text
  2.  
  3. @app.route("/cookie")
  4. async def test(request):
  5. response = text("There's a cookie up in this response")
  6. response.cookies['test'] = 'It worked!'
  7. response.cookies['test']['domain'] = '.gotta-go-fast.com'
  8. response.cookies['test']['httponly'] = True
  9. return response

Deleting cookies

Cookies can be removed semantically or explicitly.

  1. from sanic.response import text
  2.  
  3. @app.route("/cookie")
  4. async def test(request):
  5. response = text("Time to eat some cookies muahaha")
  6.  
  7. # This cookie will be set to expire in 0 seconds
  8. del response.cookies['kill_me']
  9.  
  10. # This cookie will self destruct in 5 seconds
  11. response.cookies['short_life'] = 'Glad to be here'
  12. response.cookies['short_life']['max-age'] = 5
  13. del response.cookies['favorite_color']
  14.  
  15. # This cookie will remain unchanged
  16. response.cookies['favorite_color'] = 'blue'
  17. response.cookies['favorite_color'] = 'pink'
  18. del response.cookies['favorite_color']
  19.  
  20. return response

Response cookies can be set like dictionary values and have the following parameters available:

  • expires (datetime): The time for the cookie to expire on the client’s browser.
  • path (string): The subset of URLs to which this cookie applies. Defaults to /.
  • comment (string): A comment (metadata).
  • domain (string): Specifies the domain for which the cookie is valid. An explicitly specified domain must always start with a dot.
  • max-age (number): Number of seconds the cookie should live for.
  • secure (boolean): Specifies whether the cookie will only be sent via HTTPS.
  • httponly (boolean): Specifies whether the cookie cannot be read by Javascript.

內容目录

Related Topics

本页