2009-08-11 55 views
2

我正在使用urllib2將數據發佈到表單。問題是表單回覆302重定向。根據Python HTTPRedirectHandler重定向處理程序將採取請求並將其從POST轉換爲GET並遵循301或302.我想保留POST方法和傳遞給opener的數據。通過簡單地將data = req.get_data()添加到新的請求中,我在自定義HTTPRedirectHandler上做了一次不成功的嘗試。如何使python urllib2遵循重定向並保留post方法

我確信這已經完成了,所以我想我會發一個帖子。

注意:這與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) 
+0

您是在公共互聯網上使用的表單嗎?我對如何診斷正在發生的事情有一些想法,但還沒有正確的答案。不過,我想調查一下。 – 2009-08-11 04:38:50

回答

6

這其實是一個非常糟糕的事情,我越想過這個問題。例如,如果我向 http://example.com/add(包含發佈數據添加項目)提交表單 ,並且回覆是302重定向到http://example.com/add,並且我發佈了第一次發佈的相同數據,我將以無限循環結束。不知道爲什麼我以前沒有想到這一點。我將這裏的問題留給任何其他人考慮這樣做的警告。