【问题标题】:Python GAE Requests not returning cookies after get requestPython GAE请求在获取请求后不返回cookie
【发布时间】:2017-05-21 23:48:05
【问题描述】:

我已经用 python 编写了一个项目,我现在正在迁移到谷歌应用引擎。出现的问题是当我在 GAE 上运行此代码时:

import requests
from google.appengine.api import urlfetch

def retrievePage(url, id):
    response = 'http://online2.citybreak.com/Book/Package/Result.aspx?onlineid=%s' % id
    # Set the timeout to 60 seconds
    urlfetch.set_default_fetch_deadline(60)

    # Send the first request
    r1 = requests.get(url)

    cookies = r1.cookies

    print 'Cookies: %s' % r1.cookies

    # Retrieve the content
    r2 = requests.get(response, cookies=cookies)
    return r2.text

在 GAE 上运行代码时,第一个请求中的 cookie 丢失。也就是说,r1.cookies 只是一个空的 cookie jar。相同的代码在我的 django 服务器上运行良好,其中 cookie 应包含 asp.net 会话 ID。

我有两个请求的原因是因为第一个请求重定向用户并且只有在会话 cookie 相同的情况下才会检索正确的页面。

在 GAE 上打印输出:

Cookies: <<class 'requests.cookies.RequestsCookieJar'>[]>

在 Django 上打印输出:

Cookies: <<class 'requests.cookies.RequestsCookieJar'>[<Cookie ASP.NET_SessionId=dhmk1vt3ujgmhhhmbwsclukb for online2.citybreak.com/>]>

有人知道问题可能是什么吗? GAE 是否会剥离 cookie 信息?我也愿意接受有关另一种检索页面的方法的任何建议,我只是发现请求模块比我找到的替代方法更容易。

【问题讨论】:

    标签: python google-app-engine python-requests


    【解决方案1】:

    我尝试了 urlfetch 它似乎显示了 cookie 标头:

    import logging
    from google.appengine.api import urlfetch
    
    response = urlfetch.fetch(url)
    logging.info(response.headers)
    

    【讨论】:

    • 似乎 urlfetch 确实显示了 cookie 标头。我将尝试使用 urlfetch 而不是请求,看看是否能改善这种情况。非常感谢
    【解决方案2】:

    这里有一个 PR(补丁):https://github.com/kennethreitz/requests/pull/4044 用于解决您(和许多其他人)遇到的问题。在生产和开发中通过 GAE 测试。

    【讨论】:

      猜你喜欢
      • 2018-07-08
      • 2019-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多