http.cookiesHTTP state managementHTTP状态管理

Source code: Lib/http/cookies.py


The http.cookies module defines classes for abstracting the concept of cookies, an HTTP state management mechanism. http.cookies模块定义了用于抽象cookie概念的类,cookie是一种HTTP状态管理机制。It supports both simple string-only cookies, and provides an abstraction for having any serializable data-type as cookie value.它既支持简单的纯字符串cookie,又提供了将任何可序列化的数据类型作为cookie值的抽象。

The module formerly strictly applied the parsing rules described in the RFC 2109 and RFC 2068 specifications. 该模块以前严格应用了RFC 2109RFC 2068规范中描述的解析规则。It has since been discovered that MSIE 3.0x doesn’t follow the character rules outlined in those specs and also many current day browsers and servers have relaxed parsing rules when comes to Cookie handling. As a result, the parsing rules used are a bit less strict.后来人们发现,MSIE 3.0x不遵循这些规范中列出的字符规则,而且许多当前的浏览器和服务器在Cookie处理方面放宽了解析规则。因此,使用的解析规则不那么严格。

The character set, string.ascii_letters, string.digits and !#$%&'*+-.^_`|~: denote the set of valid characters allowed by this module in Cookie name (as key).字符集、string.ascii_lettersstring.digits!#$%&'*+-.^_`|~:表示Cookie名称中此模块允许的有效字符集(作为密钥)。

Changed in version 3.3:版本3.3中更改: Allowed ‘:’ as a valid Cookie name character.允许“:”作为有效的Cookie名称字符。

Note

On encountering an invalid cookie, CookieError is raised, so if your cookie data comes from a browser you should always prepare for invalid data and catch CookieError on parsing.遇到无效cookie时,会引发CookieError,因此,如果您的cookie数据来自浏览器,则应始终为无效数据做好准备,并在解析时捕获CookieError

exceptionhttp.cookies.CookieError

Exception failing because of RFC 2109 invalidity: incorrect attributes, incorrect Set-Cookie header, etc.由于RFC 2109无效而导致异常失败:不正确的属性、不正确的Set Cookie标头等。

classhttp.cookies.BaseCookie([input])

This class is a dictionary-like object whose keys are strings and whose values are Morsel instances. 这个类是一个类似字典的对象,其键是字符串,值是Morsel实例。Note that upon setting a key to a value, the value is first converted to a Morsel containing the key and the value.请注意,在将关键点设置为值时,首先将该值转换为包含关键点和值的Morsel

If input is given, it is passed to the load() method.如果给定了input,则将其传递给load()方法。

classhttp.cookies.SimpleCookie([input])

This class derives from BaseCookie and overrides value_decode() and value_encode(). SimpleCookie supports strings as cookie values. 此类派生自BaseCookie,并重写value_decode()value_encode()。SimpleCookie支持字符串作为cookie值。When setting the value, SimpleCookie calls the builtin str() to convert the value to a string. Values received from HTTP are kept as strings.设置值时,SimpleCookie调用内置的str()将值转换为字符串。从HTTP接收的值将作为字符串保存。

See also

Module http.cookiejar

HTTP cookie handling for web clients. 用于web客户端的HTTP cookie处理。The http.cookiejar and http.cookies modules do not depend on each other.http.cookiejarhttp.cookies模块并不相互依赖。

RFC 2109 - HTTP State Management MechanismHTTP国家管理机制

This is the state management specification implemented by this module.这是由该模块实现的状态管理规范。

Morsel Objects

classhttp.cookies.Morsel

Abstract a key/value pair, which has some RFC 2109 attributes.抽象一个键/值对,它具有一些RFC 2109属性。

Morsels are dictionary-like objects, whose set of keys is constant — the valid RFC 2109 attributes, which areMorsels是类似字典的对象,其密钥集是常量-有效的RFC 2109属性,它们是

  • expires

  • path

  • comment

  • domain

  • max-age

  • secure

  • version

  • httponly

  • samesite

The attribute httponly specifies that the cookie is only transferred in HTTP requests, and is not accessible through JavaScript. This is intended to mitigate some forms of cross-site scripting.httponly属性指定cookie仅在HTTP请求中传输,并且不能通过JavaScript访问。这是为了减少某些形式的跨站点脚本编写。

The attribute samesite specifies that the browser is not allowed to send the cookie along with cross-site requests. This helps to mitigate CSRF attacks. Valid values for this attribute are “Strict” and “Lax”.samesite属性指定浏览器不允许将cookie与跨站点请求一起发送。这有助于减轻CSRF攻击。此属性的有效值为“Strict”和“Lax”。

The keys are case-insensitive and their default value is ''.这些键不区分大小写,其默认值为''

Changed in version 3.5:版本3.5中更改: __eq__() now takes key and value into account.__eq__()现在将keyvalue考虑在内。

Changed in version 3.7:版本3.7中更改: Attributes key, value and coded_value are read-only. 属性keyvaluecoded_value是只读的。Use set() for setting them.使用set()进行设置。

Changed in version 3.8:版本3.8中更改: Added support for the samesite attribute.添加了对samesite属性的支持。

Morsel.value

The value of the cookie.cookie的值。

Morsel.coded_value

The encoded value of the cookie — this is what should be sent.cookie的编码值——这是应该发送的内容。

Morsel.key

The name of the cookie.cookie的名称。

Morsel.set(key, value, coded_value)

Set the key, value and coded_value attributes.设置keyvaluecoded_value属性。

Morsel.isReservedKey(K)

Whether K is a member of the set of keys of a Morsel.K是否是Morsel的键集的成员。

Morsel.output(attrs=None, header='Set-Cookie:')

Return a string representation of the Morsel, suitable to be sent as an HTTP header. 返回Morsel的字符串表示形式,适合作为HTTP头发送。By default, all the attributes are included, unless attrs is given, in which case it should be a list of attributes to use. 默认情况下,所有属性都包括在内,除非给出了attrs,在这种情况下,它应该是要使用的属性列表。header is by default "Set-Cookie:".header默认为"Set-Cookie:"

Morsel.js_output(attrs=None)

Return an embeddable JavaScript snippet, which, if run on a browser which supports JavaScript, will act the same as if the HTTP header was sent.返回一个可嵌入的JavaScript片段,如果该片段在支持JavaScript的浏览器上运行,其行为将与发送HTTP标头时相同。

The meaning for attrs is the same as in output().attrs的含义与output()中的相同。

Morsel.OutputString(attrs=None)

Return a string representing the Morsel, without any surrounding HTTP or JavaScript.返回一个表示Morsel的字符串,不包含任何环绕的HTTP或JavaScript。

The meaning for attrs is the same as in output().attrs的含义与output()中的相同。

Morsel.update(values)

Update the values in the Morsel dictionary with the values in the dictionary values. 使用字典值中的values更新Morsel字典中的值。Raise an error if any of the keys in the values dict is not a valid RFC 2109 attribute.如果values字典中的任何键不是有效的RFC 2109属性,则引发错误。

Changed in version 3.5:版本3.5中更改: an error is raised for invalid keys.针对无效密钥引发错误。

Morsel.copy(value)

Return a shallow copy of the Morsel object.返回Morsel对象的浅层副本。

Changed in version 3.5:版本3.5中更改: return a Morsel object instead of a dict.返回一个Morsel对象,而不是dict。

Morsel.setdefault(key, value=None)

Raise an error if key is not a valid RFC 2109 attribute, otherwise behave the same as dict.setdefault().如果密钥不是有效的RFC 2109属性,则引发错误,否则行为与dict.setdefault()相同。

Example实例

The following example demonstrates how to use the http.cookies module.以下示例演示了如何使用http.cookies模块。

>>> from http import cookies
>>> C = cookies.SimpleCookie()
>>> C["fig"] = "newton"
>>> C["sugar"] = "wafer"
>>> print(C) # generate HTTP headers
Set-Cookie: fig=newton
Set-Cookie: sugar=wafer
>>> print(C.output()) # same thing
Set-Cookie: fig=newton
Set-Cookie: sugar=wafer
>>> C = cookies.SimpleCookie()
>>> C["rocky"] = "road"
>>> C["rocky"]["path"] = "/cookie"
>>> print(C.output(header="Cookie:"))
Cookie: rocky=road; Path=/cookie
>>> print(C.output(attrs=[], header="Cookie:"))
Cookie: rocky=road
>>> C = cookies.SimpleCookie()
>>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header)
>>> print(C)
Set-Cookie: chips=ahoy
Set-Cookie: vienna=finger
>>> C = cookies.SimpleCookie()
>>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
>>> print(C)
Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
>>> C = cookies.SimpleCookie()
>>> C["oreo"] = "doublestuff"
>>> C["oreo"]["path"] = "/"
>>> print(C)
Set-Cookie: oreo=doublestuff; Path=/
>>> C = cookies.SimpleCookie()
>>> C["twix"] = "none for you"
>>> C["twix"].value
'none for you'
>>> C = cookies.SimpleCookie()
>>> C["number"] = 7 # equivalent to C["number"] = str(7)
>>> C["string"] = "seven"
>>> C["number"].value
'7'
>>> C["string"].value
'seven'
>>> print(C)
Set-Cookie: number=7
Set-Cookie: string=seven