如何从Python中的HTTP cookie中提取特定密钥?

Jua*_*oto 4 python cookies parsing http request

尝试从Python中的HTTP请求的cookie字符串中获取特定值.我相信可能使用requests图书馆或者urllib2是个好主意.

例:

假设

headers['cookie'] = 'somekey=somevalue;someotherkey=someothervalue'
Run Code Online (Sandbox Code Playgroud)

试图检索的价值somekey.

非常感谢!

Chr*_*row 8

Cookie可以很少%*$%ards.每次我尝试使用它们时,总会有一些小问题我做错了而且它们都不起作用.最好使用包装库.

使用WSGI,您可以使用python"cookie"库:

import Cookie

# The function that receives the request
def application(environ, start_response):
    cookie = Cookie.SimpleCookie()
    cookie.load(environ['HTTP_COOKIE'])
    some_value = cookie['some_key'].value
Run Code Online (Sandbox Code Playgroud)

  • 注意:`Cookie` 模块已在 Python 3 - [docs.python.org](https://docs.python.org/2/library/cookie.html) 中重命名为 `http.cookies` (2认同)