Python Falcon 简明教程

Python Falcon - Cookies

Cookie 以文本文件形式存储在客户端计算机上。其目的是记住并跟踪与客户端使用相关的数据,以便提供更好的访问者体验和网站统计信息。

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.

请求对象包含 Cookie 的属性。它是客户端已传输的所有 Cookie 变量及其相应值的字典对象。此外,Cookie 还存储其过期时间、路径和网站的域名。

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.

在 Falcon 中,使用 set_cookie() 方法在响应对象上设置 Cookie。

In Falcon, cookies are set on response object using set_cookie() method.

resp.set_cookie('cookiename', 'cookievalue')

此外,Cookie 的参数 max_age (以秒为单位)和域名也可以给出。

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.

也可以使用响应对象的 append_header() 方法设置 Cookie Set-cookie 头。

The cookie Set-cookie header can also be set using append_header() method of response object.

要检索 Cookie,请求对象具有 request.cookies 属性以及 get_cookie_values() 方法。

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

响应对象的 unset_cookie 方法用于清除当前请求的 Cookie。

The unset_cookie method of response object clears the cookie for the current request.

resp.unset_cookie('user')

对于 ASGI 应用程序, falcon.asgi.Requestfalcon.Request 实现了相同的 Cookie 方法和属性。 set_cookie()append_header() 的 ASGI 版本是同步的,因此不需要等候。

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.