2009-08-11 2 views
2

urllib2를 사용하여 데이터를 양식에 게시하고 있습니다. 문제는 양식이 302 리디렉션으로 응답한다는 것입니다. Python HTTPRedirectHandler에 따르면 리디렉션 처리기는 요청을 가져와 POST에서 GET으로 변환하고 301 또는 302를 따릅니다. POST 메서드를 유지하고 데이터를 오프너에 전달하고 싶습니다. 나는 단순히 새로운 request에 data = req.get_data()를 추가함으로써 커스텀 HTTPRedirectHandler에 실패했다.python urllib2를 리디렉션하고 POST 메서드를 유지하는 방법

나는 이것이 내가 전에 게시물을 만들 거라 생각 했으니 까.

참고 : this postthis one과 유사하지만 POST 데이터를 유지하려는 리디렉션을 방지하고 싶지 않습니다.

다음은이 실제로 그것에 대해 생각보다 할 수있는 정말 나쁜 일이

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

공용 인터넷에서 사용중인 양식입니까? 나는 어떤 일이 벌어지고 있는지 진단하는 방법에 관해서 몇 가지 생각을 가지고있다. 그러나 아직 적절한 대답은 아직 없다. 그래도 조사하고 싶습니다. –

답변

6

작동하지 않습니다 내 HTTPRedirectHandler입니다. 예를 들어 http://example.com/add (게시물을 추가하여 데이터를 추가) 양식을 제출하면 이고 응답은 http://example.com/add으로 302 리디렉션되며 처음 게시 한 것과 동일한 데이터를 게시합니다. 무한 루프로 끝납니다. . 왜 내가 전에 이것을 생각하지 않았는지 모르겠다. 나는 여기에 질문을 남겨두고이 일에 대해 생각하는 다른 누군가에게 경고로 남겨 둘 것입니다.

관련 문제