【问题标题】:Keeping a session in python while making HTTP requests在发出 HTTP 请求时在 python 中保持会话
【发布时间】:2010-10-29 17:26:57
【问题描述】:

我需要编写一个 python 脚本来向同一个站点发出多个 HTTP 请求。除非我错了(我很可能是错的) urllib 为每个请求重新验证。由于我不会进入的原因,我需要能够进行一次身份验证,然后将该会话用于我的其余请求。

我正在使用 python 2.3.4

【问题讨论】:

  • 身份验证由站点驱动。如果他们要求身份验证(通过 401 响应),您的客户可以提供。你可以(有时)阻止它。取决于站点对 Nonce 的使用。

标签: python http authentication


【解决方案1】:

Python 2

如果这是基于 cookie 的身份验证,请使用 HTTPCookieProcessor:

import cookielib, urllib2
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")

如果这是 HTTP 身份验证,请使用 basic or digest AuthHandler:

import urllib2
# Create an OpenerDirector with support for Basic HTTP Authentication...
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(realm='PDQ Application',
                          uri='https://mahler:8092/site-updates.py',
                          user='klem',
                          passwd='kadidd!ehopper')
opener = urllib2.build_opener(auth_handler)
# ...and install it globally so it can be used with urlopen.
urllib2.install_opener(opener)
urllib2.urlopen('http://www.example.com/login.html')

...并为每个请求使用相同的开启器。

Python 3

在 Python3 中,urllib2 和 cookielib 分别移至 http.requesthttp.cookiejar

【讨论】:

  • 我们可以同时管理会话和基本身份验证吗?例如使用更多的处理程序,即: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj), auth_handler) ??
  • @FabianoTarlao 当然可以。这就是 python 的 urllib 的美妙之处 :-)
  • 谢谢你,我正要更新我的评论,但你已经预料到了我——我已经成功地尝试过,并且像一个魅力一样工作。
【解决方案2】:

使用Requests 库。来自http://docs.python-requests.org/en/latest/user/advanced/#session-objects

Session 对象允许你在 要求。它还在从 会话实例。

s = requests.session()

s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get("http://httpbin.org/cookies")

print r.text
# '{"cookies": {"sessioncookie": "123456789"}}'

【讨论】:

【解决方案3】:

如果要保留身份验证,则需要重用 cookie。我不确定 urllib2 在 python 2.3.4 中是否可用,但这里有一个关于如何做到这一点的示例:

req1 = urllib2.Request(url1)
response = urllib2.urlopen(req1)
cookie = response.headers.get('Set-Cookie')

# Use the cookie is subsequent requests
req2 = urllib2.Request(url2)
req2.add_header('cookie', cookie)
response = urllib2.urlopen(req2)

【讨论】:

  • python 2.3.4 确实有 urllib2。谢谢
  • 这并不像你展示的那么简单。请参阅 RFC 6265,第 5.4 Cookie Header 部分,当您发现此语句时 用户代理必须使用与以下算法等效的算法来计算来自 cookie 存储的“cookie-string”,并且一个 request-uri: 使用以下算法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-07
  • 1970-01-01
  • 2021-07-31
  • 2017-11-28
  • 2018-07-21
  • 1970-01-01
  • 2019-11-30
相关资源
最近更新 更多