- Python Falcon - Discussion
- Python Falcon - Useful Resources
- Python Falcon - Quick Guide
- Python Falcon - Deployment
- Python Falcon - Testing
- Python Falcon - Sqlalchemy Models
- Python Falcon - Websocket
- Python Falcon - CORS
- Python Falcon - Middleware
- Python Falcon - Hooks
- Python Falcon - Error Handling
- Python Falcon - Status Codes
- Python Falcon - Cookies
- Python Falcon - Jinja2 Template
- Python Falcon - Inspect Module
- Falcon - Suffixed Responders
- Python Falcon - Routing
- Python Falcon - App Class
- Python Falcon - Resource Class
- Request & Response
- Python Falcon - API Testing Tools
- Python Falcon - Uvicorn
- Python Falcon - ASGI
- Python Falcon - Waitress
- Python Falcon - Hello World(WSGI)
- Python Falcon - WSGI vs ASGI
- Python Falcon - Environment Setup
- Python Falcon - Introduction
- Python Falcon - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Python Falcon - Cookies
A cookie is stored on a cpent s computer in the form of a text file. Its purpose is to remember and track data pertaining to a cpent s usage for better visitor experience and site statistics.
A Request object contains a cookie s attribute. It is a dictionary object of all the cookie variables and their corresponding values, a cpent has transmitted. In addition to it, a cookie also stores its expiry time, path and domain name of the site.
In Falcon, cookies are set on response object using set_cookie() method.
resp.set_cookie( cookiename , cookievalue )
Additionally, the arguments max_age of cookie in seconds and domain name can also be given.
import falcon import json from waitress import serve class resource1: def on_post(self, req, resp): resp.set_cookie("user", admin ) resp.text = "cookie set successfully." resp.status = falcon.HTTP_OK resp.content_type = falcon.MEDIA_TEXT
From the command pne, invoke the responder method as −
http POST localhost:8000/cookie HTTP/1.1 200 OK Content-Length: 24 Content-Type: text/plain; charset=utf-8 Date: Tue, 26 Apr 2022 06:56:30 GMT Server: waitress Set-Cookie: user=admin; HttpOnly; Secure cookie set successfully.
The cookie Set-cookie header can also be set using append_header() method of response object.
To retrieve the cookies, the request object has request.cookies property as well as get_cookie_values() method.
def on_get(self, req, resp): cookies=req.cookies values = req.get_cookie_values( user ) if values: v = values[0] resp.body={"user":v} resp.status = falcon.HTTP_OK resp.content_type = falcon.MEDIA_JSON
The unset_cookie method of response object clears the cookie for the current request.
resp.unset_cookie( user )
For ASGI apppcations, falcon.asgi.Request implements the same cookie methods and properties as falcon.Request. The ASGI versions of set_cookie() and append_header() are synchronous, so they do not need to be awaited.
Advertisements