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 HTTP
(self, req, fp, code, msg, headers, newurl)
| 621 | max_redirections = 10 |
| 622 | |
| 623 | def redirect_request(self, req, fp, code, msg, headers, newurl): |
| 624 | """Return a Request or None in response to a redirect. |
| 625 | |
| 626 | This is called by the http_error_30x methods when a |
| 627 | redirection response is received. If a redirection should |
| 628 | take place, return a new Request to allow http_error_30x to |
| 629 | perform the redirect. Otherwise, raise HTTPError if no-one |
| 630 | else should try to handle this url. Return None if you can't |
| 631 | but another Handler might. |
| 632 | """ |
| 633 | m = req.get_method() |
| 634 | if (not (code in (301, 302, 303, 307, 308) and m in ("GET", "HEAD") |
| 635 | or code in (301, 302, 303) and m == "POST")): |
| 636 | raise HTTPError(req.full_url, code, msg, headers, fp) |
| 637 | |
| 638 | # Strictly (according to RFC 2616), 301 or 302 in response to |
| 639 | # a POST MUST NOT cause a redirection without confirmation |
| 640 | # from the user (of urllib.request, in this case). In practice, |
| 641 | # essentially all clients do redirect in this case, so we do |
| 642 | # the same. |
| 643 | |
| 644 | # Be conciliant with URIs containing a space. This is mainly |
| 645 | # redundant with the more complete encoding done in http_error_302(), |
| 646 | # but it is kept for compatibility with other callers. |
| 647 | newurl = newurl.replace(' ', '%20') |
| 648 | |
| 649 | CONTENT_HEADERS = ("content-length", "content-type") |
| 650 | newheaders = {k: v for k, v in req.headers.items() |
| 651 | if k.lower() not in CONTENT_HEADERS} |
| 652 | return Request(newurl, |
| 653 | method="HEAD" if m == "HEAD" else "GET", |
| 654 | headers=newheaders, |
| 655 | origin_req_host=req.origin_req_host, |
| 656 | unverifiable=True) |
| 657 | |
| 658 | # Implementation note: To avoid the server sending us into an |
| 659 | # infinite loop, the request object needs to track what URLs we |