Python Urllib2를 만드는 방법 리디렉션을 따르고 게시물을 유지하는 방법

StackOverflow https://stackoverflow.com/questions/1258428

  •  12-09-2019
  •  | 
  •  

문제

urllib2를 사용하여 데이터를 양식에 게시하고 있습니다. 문제는 양식이 302 리디렉션으로 응답한다는 것입니다. 에 따르면 파이썬 httpredirecthandler 리디렉션 핸들러는 요청을 가져 와서 포스트에서 301 또는 302를 얻고 따르기 위해이를 변환합니다. 게시물 메소드와 오프너로 전달 된 데이터를 보존하고 싶습니다. 새로운 요청에 데이터 = req.get_data ()를 추가하여 사용자 정의 httpredirecthandler에서 실패한 시도를했습니다.

나는 이것이 전에 이루어 졌다고 확신하므로 게시물을 만들 것이라고 생각했습니다.

참고 : 이것은 유사합니다 이 게시물 그리고 이 하나 그러나 게시물 데이터를 유지하고 싶은 리디렉션을 방지하고 싶지 않습니다.

다음은 작동하지 않는 HTTPREDERECTHANDLER입니다

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)
도움이 되었습니까?

해결책

이것은 실제로 내가 그것에 대해 더 많이 생각할수록 정말 나쁜 일입니다. 예를 들어, 양식을 제출하는 경우http://example.com/add (항목을 추가하기 위해 게시물 데이터와 함께) 응답은 302 리디렉션입니다. http://example.com/add 그리고 처음으로 게시 한 것과 동일한 데이터를 게시하여 무한 루프로 끝날 것입니다. 왜 내가 이것을 전에 생각하지 않았는지 잘 모르겠습니다. 나는 이것을하는 것에 대해 생각하는 다른 사람에게 경고로 여기에 질문을 남겨 둘 것입니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top