gpt4 book ai didi

Python 2.7 - 重定向处理程序不在重定向时传递参数

转载 作者:太空狗 更新时间:2023-10-29 21:09:44 26 4
gpt4 key购买 nike

我有一个 url,我正在访问一个可以移动的站点,当端点移动时,我需要重新应用 POST/GET 参数。我缺少什么来确保此处理程序执行此操作?

class RedirectHandler(urllib2.HTTPRedirectHandler):


def http_error_301(self, req, fp, code, msg, headers):
result = urllib2.HTTPRedirectHandler.http_error_301(
self, req, fp, code, msg, headers)
result.status = code
return result

def http_error_302(self, req, fp, code, msg, headers):
result = urllib2.HTTPRedirectHandler.http_error_302(
self, req, fp, code, msg, headers)
result.status = code
return result

当我通过 fiddler 观察流量时,我注意到用于身份验证的 token 被丢弃了。

(请注意我不能使用这个解决方案的请求,它只能是标准库)

谢谢

最佳答案

关于 HTTP 1.0 和 1.1 状态码 302、303 和 307 的故事有点复杂。基本上你会看到预期的和 documented行为(您也可以查看 this answer 以获得更详细的描述):

The default implementation of this method does not strictly follow RFC 2616, which says that 301 and 302 responses to POST requests must not be automatically redirected without confirmation by the user. In reality, browsers do allow automatic redirection of these responses, changing the POST to a GET, and the default implementation reproduces this behavior.

你走对了路,却改写了错误的方法。这是 urllib2.HTTPRedirectHandler.redirect_request 的来源:

def redirect_request(self, req, fp, code, msg, headers, newurl):
"""Return a Request or None in response to a redirect.
...
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"):
# ...
newurl = newurl.replace(' ', '%20')
newheaders = dict((k,v) for k,v in req.headers.items()
if k.lower() not in ("content-length", "content-type")
)
return Request(newurl,
headers=newheaders,
origin_req_host=req.get_origin_req_host(),
unverifiable=True)
else:
raise HTTPError(req.get_full_url(), code, msg, headers, fp)

这里有几个观察。它不传递data,因此新请求是GET。它过滤掉 content-lengthcontent-type header ,这是正确的 POST 所必需的。事实上,在我的示例中 req.headers 是一个空字典,所以我求助于 req.header_items()(参见 unredirected_hdrs)。此外,它不处理 POST 和 307 重定向。

这是 POST 和 302 重定向的正确重定向器处理程序实现。这里还有完整的 CherryPy 模拟(之前执行 pip install cherrypy)。

#!/usr/bin/env python
# -*- coding: utf-8 -*-


import urllib2
from urllib2 import HTTPRedirectHandler, Request

import cherrypy


config = {
'global' : {
'server.socket_host' : '127.0.0.1',
'server.socket_port' : 8080,
'server.thread_pool' : 8
}
}


class RedirectHandler(HTTPRedirectHandler):

def redirect_request(self, req, fp, code, msg, headers, newurl):
if code == 302 and req.get_method() == 'POST':
return Request(newurl, headers=dict(req.header_items()), data=req.data,
origin_req_host=req.get_origin_req_host(), unverifiable=True)
else:
return HTTPRedirectHandler.redirect_request(self, req, fp, code, msg,
headers, newurl)


class App:

@cherrypy.expose
def index(self):
opener = urllib2.build_opener(RedirectHandler())
return opener.open('http://localhost:8080/redirect', data='foo=bar')

@cherrypy.expose
def redirect(self, **kwargs):
print('Before redirect {0}'.format(kwargs))
raise cherrypy.HTTPRedirect('/target', 302)

@cherrypy.expose
def target(self, **kwargs):
return 'Target received {0} {1}'.format(cherrypy.request.method, kwargs)


if __name__ == '__main__':
cherrypy.quickstart(App(), '/', config)

关于Python 2.7 - 重定向处理程序不在重定向时传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31852913/

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