Cookies¶
正在获取cookie¶
可以通过以下方式从请求中读取cookie: get_cookie_values()
方法或 cookies
属性 Request
对象。一般来说, get_cookie_values()
除非需要收集请求中的所有cookie,否则应使用方法。
备注
falcon.asgi.Request
实现与相同的cookie方法和属性 falcon.Request
.
下面是一个示例,演示如何从请求中获取cookies:
class Resource:
def on_get(self, req, resp):
# Get a dict of name/value cookie pairs.
cookies = req.cookies
my_cookie_values = req.get_cookie_values('my_cookie')
if my_cookie_values:
# NOTE: If there are multiple values set for the cookie, you
# will need to choose how to handle the additional values.
v = my_cookie_values[0]
class Resource:
async def on_get(self, req, resp):
# Get a dict of name/value cookie pairs.
cookies = req.cookies
# NOTE: Since get_cookie_values() is synchronous, it does
# not need to be await'd.
my_cookie_values = req.get_cookie_values('my_cookie')
if my_cookie_values:
# NOTE: If there are multiple values set for the cookie, you
# will need to choose how to handle the additional values.
v = my_cookie_values[0]
设置cookie¶
可以通过以下方式设置响应的cookie: set_cookie()
或 append_header()
.
应该使用这些方法之一,而不是 set_header()
. 用 set_header()
不能用相同的名称设置多个头(这就是多个cookie发送到客户端的方式)。
备注
falcon.asgi.Request
实现与相同的cookie方法和属性 falcon.Request
. ASGI版本 set_cookie()
和 append_header()
是同步的,所以它们不需要是同步的 await
'天。
简单例子:
# Set the cookie 'my_cookie' to the value 'my cookie value'
resp.set_cookie('my_cookie', 'my cookie value')
当然,您也可以设置cookie的域、路径和生存期。
# Set the maximum age of the cookie to 10 minutes (600 seconds)
# and the cookie's domain to 'example.com'
resp.set_cookie('my_cookie', 'my cookie value',
max_age=600, domain='example.com')
您还可以指示客户端使用 unset_cookie()
方法:
# Set a cookie in middleware or in a previous request.
resp.set_cookie('my_cookie', 'my cookie value')
# -- snip --
# Clear the cookie for the current request and instruct the user agent
# to expire its own copy of the cookie (if any).
resp.unset_cookie('my_cookie')
安全属性¶
默认情况下,falcon设置 secure cookies的属性。这将指示客户端永远不要通过HTTP以明文形式传输cookie,以保护cookie可能包含的任何敏感数据。如果设置了cookie,并且通过HTTP(而不是HTTPS)发出后续请求,则客户端将不会在请求中包含该cookie。
警告
为了使该属性有效,您的Web服务器或负载均衡器在设置cookie时以及在所有后续要求从客户端发送cookie的请求中都需要强制使用https。
在开发环境中运行应用程序时,可以通过设置 secure_cookies_by_default
到 False
通过 falcon.App.resp_options
或 falcon.asgi.App.resp_options
.这允许您在本地测试应用程序,而不必设置TLS。您可以配置此选项,以便在开发和生产环境之间轻松切换。
SameSite属性¶
这个 SameSite attribute may be set on a cookie using the set_cookie()
method. It is generally a good idea to at least set this attribute to 'Lax'
in order to mitigate CSRF attacks .
目前, set_cookie()
未设置 SameSite 默认情况下,尽管这在将来的版本中可能会更改。
备注
标准 http.cookies
模块不支持 SameSite 属性。因此,Falcon在标准库模块上执行了一个简单的monkey补丁,为运行在旧版Python上的应用程序后传这个特性。
当取消设置cookie时, unset_cookie()
,默认设置 SameSite 未设置的Cookie的设置为 'Lax'
,但可以通过设置“Same”kwarg来更改。