gpt4 book ai didi

python - 如何使用 urlfetch 获取所有 cookie?

转载 作者:太空宇宙 更新时间:2023-11-03 13:49:16 24 4
gpt4 key购买 nike

根据GAE fetch documentation , cookie 不使用重定向处理:

Cookies are not handled upon redirection. If cookie handling is needed, set follow_redirects to False and handle both cookies and redirects manually.

因此,我正在尝试实现手动解决方案:

page = urlfetch.Fetch(
url = url,
payload = form_data,
method = urlfetch.POST,
headers = headers,
follow_redirects = False,
deadline = 60)
cookies = ''
while page.status_code == 302:
url = page.headers.get('location')
if page.headers.get('set-cookie'):
cookies = page.headers.get('set-cookie')
headers['cookie'] = cookies
page = urlfetch.Fetch(
url = url,
method = urlfetch.GET,
headers = headers,
follow_redirects = False,
deadline = 60)
if page.status_code == 200 and page.content:
self.response.out.write(page.content)

但它并没有像预期的那样工作。看来我不见了 some cookies :

header_msg An instance of httplib.HTTPMessage containing the response headers. If there may be multiple headers with the same name (for example, Set-Cookie headers), call header_msg.get_headers(header_name) to retrieve the values as a list.

但是我应该如何使用那个header_msg

最佳答案

如果我理解这个问题,您想从每个响应中收集(并累积传递)cookie,但是带有 follow_redirects=True 的 URLFetch 只返回最后一个响应中的 cookie。此外,默认行为不会实现 cookie jar,这将导致后面的请求使用与先前响应中的 Set-Cookie 相对应的正确 Cookie header 发送。据推测,最初的 POST 是一个登录表单,它重定向到一个需要 cookie 的页面,这种方案不能与这些限制一起使用。

为此,您的代码很接近,但 cookies = page.headers.get('set-cookie') 会在每次请求后清除之前收集的 cookie。这应该会更好:

page = urlfetch.Fetch(
url = url,
headers = headers,
follow_redirects = False)
cookies = []
while page.status_code == 302:
url = page.headers.get('location')
if page.headers.get('set-cookie'):
cookies.extend(page.header_msg.getheaders('set-cookie'))
headers['cookie'] = '; '.join(cookies)
page = urlfetch.Fetch(
url = url,
method = urlfetch.GET,
headers = headers,
follow_redirects = False)
if page.status_code == 200 and page.content:
self.response.out.write(page.content)

一些注意事项:

  • 如果 Location 是相对路径,您需要修复 url
  • 如果任何 Set-Cookie header 不仅仅是键=值(例如,它有过期时间),您将需要解析 header 值,以便您可以只发送键/值对。查看Cookie帮助解析的库。
  • 如果针对特定键看到多个 Set-Cookie,此代码将愉快地发送重复的 cookie。
  • 如果重定向在一个单独的域结束,这将错误地从原始域向它发送 cookie。这可能是一个安全问题。适当的 cookie jar 实现可以推断域和路径限制,以确定何时接受和发出 cookie。您可能想要合并 cookielib.CookieJar图书馆。如果您希望请求序列在同一个域中,则在检测到切换时中止可能就足够了。

关于python - 如何使用 urlfetch 获取所有 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12884618/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com