urls.py 文件源码

python
阅读 27 收藏 0 点赞 0 评论 0

项目:ansible-provider-docs 作者: alibaba 项目源码 文件源码
def RedirectHandlerFactory(follow_redirects=None, validate_certs=True):
    """This is a class factory that closes over the value of
    ``follow_redirects`` so that the RedirectHandler class has access to
    that value without having to use globals, and potentially cause problems
    where ``open_url`` or ``fetch_url`` are used multiple times in a module.
    """

    class RedirectHandler(urllib_request.HTTPRedirectHandler):
        """This is an implementation of a RedirectHandler to match the
        functionality provided by httplib2. It will utilize the value of
        ``follow_redirects`` that is passed into ``RedirectHandlerFactory``
        to determine how redirects should be handled in urllib2.
        """

        def redirect_request(self, req, fp, code, msg, hdrs, newurl):
            handler = maybe_add_ssl_handler(newurl, validate_certs)
            if handler:
                urllib_request._opener.add_handler(handler)

            if follow_redirects == 'urllib2':
                return urllib_request.HTTPRedirectHandler.redirect_request(self, req, fp, code, msg, hdrs, newurl)
            elif follow_redirects in ['no', 'none', False]:
                raise urllib_error.HTTPError(newurl, code, msg, hdrs, fp)

            do_redirect = False
            if follow_redirects in ['all', 'yes', True]:
                do_redirect = (code >= 300 and code < 400)

            elif follow_redirects == 'safe':
                m = req.get_method()
                do_redirect = (code >= 300 and code < 400 and m in ('GET', 'HEAD'))

            if do_redirect:
                # be conciliant with URIs containing a space
                newurl = newurl.replace(' ', '%20')
                newheaders = dict((k, v) for k, v in req.headers.items()
                                  if k.lower() not in ("content-length", "content-type"))
                try:
                    # Python 2-3.3
                    origin_req_host = req.get_origin_req_host()
                except AttributeError:
                    # Python 3.4+
                    origin_req_host = req.origin_req_host
                return urllib_request.Request(newurl,
                                              headers=newheaders,
                                              origin_req_host=origin_req_host,
                                              unverifiable=True)
            else:
                raise urllib_error.HTTPError(req.get_full_url(), code, msg, hdrs, fp)

    return RedirectHandler
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号