示例#1
0
def test_prepared_request_no_cookies_copy():
    p = PreparedRequest()
    p.prepare(method='GET',
              url='http://www.example.com',
              data='foo=bar',
              hooks=default_hooks())
    assert_copy(p, p.copy())
示例#2
0
    def handle_401(self, response, **kwargs):
        """Takes the given response and tries digest-auth, if needed."""

        original_request = response.request.copy()
        www_authenticate = response.headers.get('www-authenticate', '').lower()
        www_auth_schemes = [x.strip().split()[0] for x in www_authenticate.split(',') if x.strip()]
        auths_to_try = [x for x in www_auth_schemes if x in [y.lower() for y in self.auth_map.keys()]]

        for auth_scheme in auths_to_try:
            for auth_instance in self.auth_map[auth_scheme]:
                #print 'trying', auth_instance, 'for', auth_scheme

                # Consume content and release the original connection
                # to allow our new request to reuse the same one.
                response.content
                response.raw.release_conn()
                prepared_request = original_request.copy()
                prepared_request.hooks = default_hooks()
                prepared_request.prepare_auth(auth_instance)

                adapter = HTTPAdapter()
                if self.session:
                    adapter = self.session() or adapter
                new_response = adapter.send(prepared_request, **kwargs)
                new_response.history.append(response)
                new_response.request = prepared_request
        
                if new_response.status_code != 401:
                    #print auth_instance, 'successful for', auth_scheme
                    self.current_auth = auth_instance
                    return new_response
                response = new_response

        return response
示例#3
0
    def __init__(self,
                 url: Optional[str] = None,
                 rules: Optional[str] = None) -> None:
        self.headers = default_headers()

        self.auth = None

        self.proxies = {}

        self.hooks = default_hooks()

        self.params = {}

        self.stream = False

        self.verify = True

        self.cert = None

        self.max_redirects = DEFAULT_REDIRECT_LIMIT

        self.trust_env = True

        self.cookies = cookiejar_from_dict({})

        self.adapters = OrderedDict()

        middlewares = [ResurfaceHTTPAdapter(url=url, rules=rules)]

        adapter = MiddlewareHTTPAdapter(middlewares)

        self.mount("https://", adapter)
        self.mount("http://", adapter)
示例#4
0
    def __init__(self,
                 pool_connections=True,
                 request_hooks=None,
                 timeout=None,
                 logger=_logger,
                 proxy=None,
                 max_retries=None):
        """
        Constructor for the TwilioHttpClient

        :param bool pool_connections
        :param request_hooks
        :param int timeout: Timeout for the requests.
                            Timeout should never be zero (0) or less.
        :param logger
        :param dict proxy: Http proxy for the requests session
        :param int max_retries: Maximum number of retries each request should attempt
        """
        self.session = Session() if pool_connections else None
        if self.session and max_retries is not None:
            self.session.mount('https://',
                               HTTPAdapter(max_retries=max_retries))
        self.last_request = None
        self.last_response = None
        self.logger = logger
        self.request_hooks = request_hooks or hooks.default_hooks()

        if timeout is not None and timeout <= 0:
            raise ValueError(timeout)
        self.timeout = timeout
        self.proxy = proxy
示例#5
0
def pretty_request(request, ctx):

    kwargs = [
        ('method', request.method),
        ('url', request.url),
    ]

    if request.cookies:
        kwargs.append(('cookies', request.cookies))

    if request.auth:
        kwargs.append(('auth', request.auth))

    if request.json:
        kwargs.append(('json', request.json))

    if request.data:
        kwargs.append(('data', request.data))

    if request.files:
        kwargs.append(('files', request.files))

    if request.headers:
        kwargs.append(('headers', request.headers))

    if request.params:
        kwargs.append(('params', request.params))

    if request.hooks:
        from requests.hooks import default_hooks
        if request.hooks != default_hooks():
            kwargs.append(('hooks', request.hooks))

    return pretty_call_alt(ctx, 'requests.Request', kwargs=kwargs)
示例#6
0
def pretty_prepared_request(request, ctx):
    from requests.hooks import default_hooks

    kwargs = [
        ('method', request.method),
        ('url', request.url),
    ]

    if request.headers:
        kwargs.append(('headers', request.headers))

    if request.body is not None:
        count_bytes = len(request.body)

        count_display_bytes = 10
        count_bytes = len(request.body)

        if count_bytes > count_display_bytes:
            truncated_body = comment(
                request.body[:count_display_bytes],
                '... and {} more bytes'.format(count_bytes -
                                               count_display_bytes))
        else:
            truncated_body = request.body

        kwargs.append(('body', truncated_body))

    if request.hooks != default_hooks():
        kwargs.append(('hooks', request.hooks))

    return pretty_call_alt(ctx, 'requests.PreparedRequest', kwargs=kwargs)
 def test_no_keep_alive_by_default(self):
     p = PreparedRequest()
     p.prepare(
         method='GET',
         url='http://www.example.com',
         hooks=default_hooks()
     )
     assert 'Connection' not in p.headers
示例#8
0
 def reset_all(self):
     self.url = None
     self.headers = self.headers.clear() if self.headers else {}
     self.method = "GET"
     self.body = None
     self._cookies = self._cookies if self._cookies else None
     self.hooks = default_hooks()
     self._body_position = None
     return self
def test_prepared_request_no_cookies_copy():
    p = PreparedRequest()
    p.prepare(
        method='GET',
        url='http://www.example.com',
        data='foo=bar',
        hooks=default_hooks()
    )
    assert_copy(p, p.copy())
示例#10
0
def test_data_argument_accepts_tuples(list_of_tuples):
    """
    Ensure that the data argument will accept tuples of strings
    and properly encode them.
    """
    for data in list_of_tuples:
        p = PreparedRequest()
        p.prepare(method="GET", url="http://www.example.com", data=data, hooks=default_hooks())
        assert p.body == urlencode(data)
def test_data_argument_accepts_tuples(data):
    """Ensure that the data argument will accept tuples of strings
    and properly encode them.
    """
    p = PreparedRequest()
    p.prepare(method='GET',
              url='http://www.example.com',
              data=data,
              hooks=default_hooks())
    assert p.body == urlencode(data)
示例#12
0
def test_data_argument_accepts_tuples(data):
    """Ensure that the data argument will accept tuples of strings
    and properly encode them.
    """
    p = PreparedRequest()
    p.prepare(
        method='GET',
        url='http://www.example.com',
        data=data,
        hooks=default_hooks()
    )
    assert p.body == urlencode(data)
示例#13
0
 def __init__(self):
     self.headers = default_headers()
     self.auth = None
     self.proxies = {}
     self.hooks = default_hooks()
     self.params = {}
     self.stream = False
     self.verify = True
     self.cert = None
     self.max_redirects = DEFAULT_REDIRECT_LIMIT
     self.trust_env = True
     self.cookies = cookiejar_from_dict({})
     self.adapter = HTTPAdapter()
示例#14
0
 def __init__(self):
     self.auth = None
     self.proxies = {}
     self.hooks = default_hooks()
     self.stream = False
     self.verify = True
     self.cert = None
     self.max_redirects = 30
     self.trust_env = True
     self.cookies = cookiejar_from_dict({})
     self.adapters = OrderedDict()
     self.mount("https://", HTTPAdapter())
     self.mount("http://", HTTPAdapter())
     self.retryCallback = None
     self.Request = None
示例#15
0
    def __init__(self, pool_connections=True, request_hooks=None, timeout=None):
        """
        Constructor for the TwilioHttpClient

        :param bool pool_connections
        :param request_hooks
        :param int timeout: Timeout for the requests.
                            Timeout should never be zero (0) or less.
        """
        self.session = Session() if pool_connections else None
        self.last_request = None
        self.last_response = None
        self.request_hooks = request_hooks or hooks.default_hooks()

        if timeout is not None and timeout <= 0:
            raise ValueError(timeout)
        self.timeout = timeout
示例#16
0
    def _perhaps_relogin(self, r, **kwargs):
        if r.status_code == 401:
            self._login(r.headers.copy())
            req = r.request.copy()
            req.hooks = hooks.default_hooks()
            req.headers['Authorization'] = 'Basic ' + self.access_token

            adapter = self._adapter
            if self._session:
                session = self.session()
                if session:
                    adapter = session.get_adapter(req.url)

            response = adapter.send(req, **kwargs)
            response.history.append(r)

            return response

        return r
示例#17
0
    def _perhaps_relogin(self, r, **kwargs):
        if r.status_code == 401:
            self._login(r.headers.copy())
            req = r.request.copy()
            req.hooks = hooks.default_hooks()
            req.headers['Authorization'] = 'Basic ' + self.access_token

            adapter = self._adapter
            if self._session:
                session = self.session()
                if session:
                    adapter = session.get_adapter(req.url)

            response = adapter.send(req, **kwargs)
            response.history.append(r)

            return response

        return r
示例#18
0
    def handle_401(self, response, **kwargs):
        """Takes the given response and tries digest-auth, if needed."""

        original_request = response.request.copy()
        www_authenticate = response.headers.get('www-authenticate', '').lower()
        www_auth_schemes = [
            x.strip().split()[0] for x in www_authenticate.split(',')
            if x.strip()
        ]
        auths_to_try = [
            x for x in www_auth_schemes
            if x in [y.lower() for y in self.auth_map.keys()]
        ]

        for auth_scheme in auths_to_try:
            for auth_instance in self.auth_map[auth_scheme]:
                # Consume content and release the original connection
                # to allow our new request to reuse the same one.
                response.content
                response.raw.release_conn()
                prepared_request = original_request.copy()
                prepared_request.hooks = default_hooks()
                prepared_request.prepare_auth(auth_instance)

                adapter = HTTPAdapter()
                if self.session:
                    adapter = self.session() or adapter
                new_response = adapter.send(prepared_request, **kwargs)
                new_response.history.append(response)
                new_response.request = prepared_request

                if new_response.status_code != 401:
                    self.current_auth = auth_instance
                    return new_response
                response = new_response

        return response
示例#19
0
def test_prepared_request_complete_copy():
    p = PreparedRequest()
    p.prepare(method="GET", url="http://www.example.com", data="foo=bar", hooks=default_hooks(), cookies={"foo": "bar"})
    assert_copy(p, p.copy())
示例#20
0
 def __init__(self, pool_connections=True, request_hooks=None):
     self.session = Session() if pool_connections else None
     self.last_request = None
     self.last_response = None
     self.request_hooks = request_hooks or hooks.default_hooks()
示例#21
0
        method='GET',
        url='http://www.example.com',
        data=data,
        hooks=default_hooks()
    )
    assert p.body == urlencode(data)


@pytest.mark.parametrize(
    'kwargs', (
        None,
        {
            'method': 'GET',
            'url': 'http://www.example.com',
            'data': 'foo=bar',
            'hooks': default_hooks()
        },
        {
            'method': 'GET',
            'url': 'http://www.example.com',
            'data': 'foo=bar',
            'hooks': default_hooks(),
            'cookies': {'foo': 'bar'}
        },
        {
            'method': 'GET',
            'url': u('http://www.example.com/üniçø∂é')
        },
    ))
def test_prepared_copy(kwargs):
    p = PreparedRequest()
示例#22
0
def test_default_hooks():
    assert hooks.default_hooks() == {'response': []}
示例#23
0
    """
    p = PreparedRequest()
    p.prepare(method='GET',
              url='http://www.example.com',
              data=data,
              hooks=default_hooks())
    assert p.body == urlencode(data)


@pytest.mark.parametrize('kwargs', (
    None,
    {
        'method': 'GET',
        'url': 'http://www.example.com',
        'data': 'foo=bar',
        'hooks': default_hooks()
    },
    {
        'method': 'GET',
        'url': 'http://www.example.com',
        'data': 'foo=bar',
        'hooks': default_hooks(),
        'cookies': {
            'foo': 'bar'
        }
    },
    {
        'method': 'GET',
        'url': u('http://www.example.com/üniçø∂é')
    },
))
示例#24
0
 def __init__(self, auth_token, request_hooks=None, timeout=None):
     self.auth = IdentixOneAuth(token=auth_token)
     self.session = Session()
     self.request_hooks = request_hooks or hooks.default_hooks()
     self.timeout = timeout or constants.HTTP_CLIENT_TIMEOUT
     self.base_url = constants.HTTP_CLIENT_BASE_URL
示例#25
0
def test_default_hooks():
    assert hooks.default_hooks() == {'response': []}
示例#26
0
def test_default_hooks():
    assert hooks.default_hooks() == {"response": []}
示例#27
0
 def __init__(self, pool_connections=True, request_hooks=None):
     self.session = Session() if pool_connections else None
     self.last_request = None
     self.last_response = None
     self.request_hooks = request_hooks or hooks.default_hooks()
示例#28
0
 def __init__(self, pool_connections=True, request_hooks=None):
     # client specific info goes here.
     self.base_url = PYPI_BASE_URL
     self.session = Session() if pool_connections else None
     # default_hooks() returns {'response': []}
     self.request_hooks = request_hooks or hooks.default_hooks()