Python Falcon - Cookies



A cookie is stored on a client's computer in the form of a text file. Its purpose is to remember and track data pertaining to a client'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 client 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 line, 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 applications, 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