【问题标题】:How to make python urllib2 follow redirect and keep post method如何使python urllib2遵循重定向并保持发布方法
【发布时间】:2010-11-18 12:13:11
【问题描述】:

我正在使用 urllib2 将数据发布到表单。问题是表单回复了 302 重定向。根据Python HTTPRedirectHandler,重定向处理程序将接受请求并将其从 POST 转换为 GET 并遵循 301 或 302。我想保留 POST 方法和传递给开启程序的数据。通过简单地将 data=req.get_data() 添加到新请求中,我对自定义 HTTPRedirectHandler 进行了不成功的尝试。

我确定这已经完成了,所以我想我会发一个帖子。

注意:这类似于this postthis one,但我不想阻止重定向,我只想保留 POST 数据。

这是我的 HTTPRedirectHandler 不起作用

class MyHTTPRedirectHandler(urllib2.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
    """Return a Request or None in response to a redirect.

    This is called by the http_error_30x methods when a
    redirection response is received.  If a redirection should
    take place, return a new Request to allow http_error_30x to
    perform the redirect.  Otherwise, raise HTTPError if no-one
    else should try to handle this url.  Return None if you can't
    but another Handler might.
    """
    m = req.get_method()
    if (code in (301, 302, 303, 307) and m in ("GET", "HEAD")
        or code in (301, 302, 303) and m == "POST"):
        # Strictly (according to RFC 2616), 301 or 302 in response
        # to a POST MUST NOT cause a redirection without confirmation
        # from the user (of urllib2, in this case).  In practice,
        # essentially all clients do redirect in this case, so we
        # do the same.
        # be conciliant with URIs containing a space
        newurl = newurl.replace(' ', '%20')
        return Request(newurl,
                       headers=req.headers,
                       data=req.get_data(),
                       origin_req_host=req.get_origin_req_host(),
                       unverifiable=True)
    else:
        raise HTTPError(req.get_full_url(), code, msg, headers, fp)

【问题讨论】:

  • 您使用的表单是在公共互联网上使用的吗?我对如何诊断正在发生的事情有一些想法,但还没有正确的答案;不过,我想调查一下。

标签: python automation urllib2


【解决方案1】:

这实际上是一件非常糟糕的事情,我越想越想。例如,如果我向 http://example.com/add(有post数据添加项目) 并且响应是 302 重定向到 http://example.com/add 并且我发布了我第一次发布的相同数据,我最终将进入无限循环。不知道为什么我以前没有想到这一点。我将把这个问题留在这里,作为对其他考虑这样做的人的警告。

【讨论】:

    猜你喜欢
    • 2012-01-14
    • 1970-01-01
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    相关资源
    最近更新 更多