6176964bdf
* Reorder and clarify the 'Request Data' guide, adding a section on RequestParameters * Clarify routing guide, adding introduction and HTTP types sections * Clarify the use-cases of middleware * Clean up formatting in the exceptions guide and add some common exceptions. * Fix formatting of blueprints and add use-case example. * Clarify the class-based views guide * Clarify and fix formatting of cookies guide * Clarify static files guide * Clarify the custom protocols guide. * Add more information to the deploying guide * Fix broken list in the community extensions list. * Add introduction and improve warning to contributing guide * Expand getting started guide * Reorder guides and add links between them * Standardise heading capitalisation
1.7 KiB
1.7 KiB
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.
Reading cookies
A user's cookies can be accessed Request
object's cookie
dictionary.
from sanic.response import text
@app.route("/cookie")
async def test(request):
test_cookie = request.cookies.get('test')
return text("Test cookie set to: {}".format(test_cookie))
Writing cookies
When returning a response, cookies can be set on the Response
object.
from sanic.response import text
@app.route("/cookie")
async def test(request):
response = text("There's a cookie up in this response")
response.cookies['test'] = 'It worked!'
response.cookies['test']['domain'] = '.gotta-go-fast.com'
response.cookies['test']['httponly'] = True
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.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.
Previous: Class-based views
Next: Custom protocols