Python httpx.Client() Examples

The following are 14 code examples of httpx.Client(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module httpx , or try the search function .
Example #1
Source File: client.py    From Audible with GNU Affero General Public License v3.0 9 votes vote down vote up
def __init__(self, auth: Optional[Union[LoginAuthenticator, FileAuthenticator]] = None,
                 session=None, is_async=False, **options) -> None:
        self.auth = auth

        self.is_async = is_async
        self.session = (session or (httpx.AsyncClient() if is_async
                        else httpx.Client()))
        headers = {
            "Accept": "application/json",
            "Content-Type": "application/json"
        }
        self.session.headers.update(headers)

        locale = test_convert("locale", options.get("locale", auth.locale))
        domain = options.get("domain", locale.domain)
        self.api_root_url = options.get("url", f"https://api.audible.{domain}")

        self.timeout = options.get('timeout', 10) 
Example #2
Source File: client.py    From tiktok_bot with MIT License 7 votes vote down vote up
def __init__(
        self,
        base_url: str,
        default_headers: Optional[dict] = None,
        default_params: Optional[dict] = None,
        history_len: int = 30,
    ):
        self.base_url = base_url
        self.default_headers = default_headers or {}
        self.default_params = default_params or {}

        self.history: Deque[Response] = deque(maxlen=history_len)

        self.http_client = Client(
            base_url=self.base_url, headers=default_headers, params=self.default_params
        ) 
Example #3
Source File: client.py    From py-googletrans with MIT License 6 votes vote down vote up
def __init__(self, service_urls=None, user_agent=DEFAULT_USER_AGENT,
                 raise_exception=DEFAULT_RAISE_EXCEPTION,
                 proxies: typing.Dict[str, httpcore.SyncHTTPTransport] = None, timeout: Timeout = None):

        self.client = httpx.Client()
        if proxies is not None:  # pragma: nocover
            self.client.proxies = proxies

        self.client.headers.update({
            'User-Agent': user_agent,
        })

        if timeout is not None:
            self.client.timeout = timeout

        self.service_urls = service_urls or ['translate.google.com']
        self.token_acquirer = TokenAcquirer(client=self.client, host=self.service_urls[0])
        self.raise_exception = raise_exception 
Example #4
Source File: client.py    From python-schema-registry-client with MIT License 6 votes vote down vote up
def _create_session(self) -> httpx.Client:
        """
        Create a httpx Client session
        Returns:
            httpx.Client
        """
        verify = self.conf.get(utils.SSL_CA_LOCATION, False)
        certificate = self._configure_client_tls(self.conf)
        auth = self._configure_basic_auth(self.conf)

        return httpx.Client(
            cert=certificate,
            verify=verify,  # type: ignore
            auth=auth,
            headers=self.extra_headers,
            timeout=self.timeout,
            pool_limits=self.pool_limits,
        )  # type: ignore 
Example #5
Source File: test_http_client.py    From python-schema-registry-client with MIT License 6 votes vote down vote up
def test_override_headers(client, deployment_schema, mocker, response_klass):
    extra_headers = {"custom-serialization": "application/x-avro-json"}
    client = SchemaRegistryClient("https://127.0.0.1:65534", extra_headers=extra_headers)

    assert client.session.headers.get("custom-serialization") == "application/x-avro-json"

    subject = "test"
    override_header = {"custom-serialization": "application/avro"}

    request_patch = mocker.patch.object(httpx.Client, "request", return_value=response_klass(200, content={"id": 1}))
    client.register(subject, deployment_schema, headers=override_header)

    prepare_headers = client.prepare_headers(body="1")
    prepare_headers["custom-serialization"] = "application/avro"

    request_patch.assert_called_once_with("POST", mocker.ANY, headers=prepare_headers, json=mocker.ANY, timeout=UNSET) 
Example #6
Source File: http.py    From mergify-engine with Apache License 2.0 6 votes vote down vote up
def raise_for_status(resp):
    if httpx.StatusCode.is_client_error(resp.status_code):
        error_type = "Client Error"
        default_exception = HTTPClientSideError
    elif httpx.StatusCode.is_server_error(resp.status_code):
        error_type = "Server Error"
        default_exception = HTTPServerSideError
    else:
        return

    try:
        details = resp.json().get("message")
    except json.JSONDecodeError:
        details = None

    if details is None:
        details = resp.text if resp.text else "<empty-response>"

    message = f"{resp.status_code} {error_type}: {resp.reason_phrase} for url `{resp.url}`\nDetails: {details}"
    exc_class = STATUS_CODE_TO_EXC.get(resp.status_code, default_exception)
    raise exc_class(message, response=resp) 
Example #7
Source File: httpx_vcr_stubs.py    From mergify-engine with Apache License 2.0 6 votes vote down vote up
def monkeypatch():
    @CassettePatcherBuilder._build_patchers_from_mock_triples_decorator
    def _async_httpx(self):
        new_async_client_send = async_vcr_send(self._cassette, httpx.AsyncClient.send)
        yield httpx.AsyncClient, "send", new_async_client_send

    @CassettePatcherBuilder._build_patchers_from_mock_triples_decorator
    def _sync_httpx(self):
        new_sync_client_send = sync_vcr_send(self._cassette, httpx.Client.send)
        yield httpx.Client, "send", new_sync_client_send

    real_build = CassettePatcherBuilder.build

    def patched_build(self):
        return itertools.chain(real_build(self), _sync_httpx(self), _async_httpx(self))

    CassettePatcherBuilder.build = patched_build 
Example #8
Source File: http_httpx.py    From py-ipfs-http-client with MIT License 5 votes vote down vote up
def _make_session(self) -> httpx.Client:
		return httpx.Client(**self._session_kwargs) 
Example #9
Source File: transport.py    From linepy-modified with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def open(self):
        if self.request == 'hyper':
            if self.http2:
                self.__http = hyper.HTTP20Connection(self.host, self.port, proxy_host=self.realhost, proxy_port=self.realport, proxy_headers=self.proxy_headers)
            else:
                self.__http = hyper.HTTPConnection(self.host, self.port, proxy_host=self.realhost, proxy_port=self.realport, proxy_headers=self.proxy_headers)
        elif self.request == 'httpx':
            if self.http2:
                self.__http = httpx.AsyncClient(base_url='%s://%s' % (self.scheme, self.host), http2=self.http2)
            else:
                self.__http = httpx.Client(base_url='%s://%s' % (self.scheme, self.host))
        elif self.request == 'requests':
            self.__http = requests.Session()
            if self.using_proxy():
                self.__http.proxies = urllib.request.getproxies()
        elif self.request == 'requests-futures':
            self.__http = FuturesSession()
            if self.using_proxy():
                self.__http.proxies = urllib.request.getproxies()
        elif self.request == 'httplib2':
            self.__http = httplib2.Http()
        else:
            if self.scheme == 'http':
                self.__http = http_client.HTTPConnection(self.host, self.port)
            elif self.scheme == 'https':
                self.__http = http_client.HTTPSConnection(self.host, self.port)
                if self.using_proxy():
                    self.__http.set_tunnel(self.realhost, self.realport, self.proxy_headers) 
Example #10
Source File: gtoken.py    From py-googletrans with MIT License 5 votes vote down vote up
def __init__(self, tkk='0', client: httpx.Client = None, host='translate.google.com'):
        self.client = client or httpx.Client()
        self.tkk = tkk
        self.host = host if 'http' in host else 'https://' + host 
Example #11
Source File: test_schema_compatibility.py    From python-schema-registry-client with MIT License 5 votes vote down vote up
def test_update_compatibility_fail(client, response_klass, mocker):
    http_code = 404
    mocker.patch.object(httpx.Client, "request", return_value=response_klass(http_code))

    with pytest.raises(errors.ClientError) as excinfo:
        client.update_compatibility("FULL", "test-user-schema")

        assert excinfo.http_code == http_code 
Example #12
Source File: resource.py    From python-simple-rest-client with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.client = httpx.Client(verify=self.ssl_verify)
        for action_name in self.actions.keys():
            self.add_action(action_name) 
Example #13
Source File: client.py    From Audible with GNU Affero General Public License v3.0 5 votes vote down vote up
def __repr__(self):
        return f"<AudibleAPI Client async={self.is_async}>" 
Example #14
Source File: http_httpx.py    From py-ipfs-http-client with MIT License 4 votes vote down vote up
def _request(
			self, method: str, path: str, params: ty.Sequence[ty.Tuple[str, str]], *,
			auth: auth_t,
			data: reqdata_sync_t,
			headers: headers_t,
			timeout: timeout_t,
			chunk_size: ty.Optional[int],
	) -> ty.Tuple[ty.List[Closable], ty.Iterator[bytes]]:
		# Ensure path is relative so that it is resolved relative to the base
		while path.startswith("/"):
			path = path[1:]
		
		try:
			# Determine session object to use
			closables: ty.List[Closable]
			session: httpx.Client
			closables, session = self._access_session()
			
			# Do HTTP request (synchronously) and map exceptions
			try:
				res: httpx.Response = session.stream(
					method=method,
					url=path,
					**map_args_to_httpx(
						params=params,
						auth=auth,
						data=data,
						headers=headers,
						timeout=timeout,
					)
				).__enter__()
				closables.insert(0, res)
			except (httpx.ConnectTimeout, httpx.ReadTimeout, httpx.WriteTimeout) as error:
				raise exceptions.TimeoutError(error) from error
			except httpx.NetworkError as error:
				raise exceptions.ConnectionError(error) from error
			except httpx.ProtocolError as error:
				raise exceptions.ProtocolError(error) from error
			
			# Raise exception for response status
			# (optionally incorporating the response message, if available)
			self._do_raise_for_status(res)
			
			return closables, res.iter_bytes()
		except:
			for closable in closables:
				closable.close()
			raise