本文整理匯總了Python中httpx.Client方法的典型用法代碼示例。如果您正苦於以下問題:Python httpx.Client方法的具體用法?Python httpx.Client怎麽用?Python httpx.Client使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類httpx
的用法示例。
在下文中一共展示了httpx.Client方法的14個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
# 需要導入模塊: import httpx [as 別名]
# 或者: from httpx import Client [as 別名]
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
示例2: _create_session
# 需要導入模塊: import httpx [as 別名]
# 或者: from httpx import Client [as 別名]
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
示例3: test_override_headers
# 需要導入模塊: import httpx [as 別名]
# 或者: from httpx import Client [as 別名]
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)
示例4: raise_for_status
# 需要導入模塊: import httpx [as 別名]
# 或者: from httpx import Client [as 別名]
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)
示例5: monkeypatch
# 需要導入模塊: import httpx [as 別名]
# 或者: from httpx import Client [as 別名]
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
示例6: __init__
# 需要導入模塊: import httpx [as 別名]
# 或者: from httpx import Client [as 別名]
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
)
示例7: __init__
# 需要導入模塊: import httpx [as 別名]
# 或者: from httpx import Client [as 別名]
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)
示例8: _make_session
# 需要導入模塊: import httpx [as 別名]
# 或者: from httpx import Client [as 別名]
def _make_session(self) -> httpx.Client:
return httpx.Client(**self._session_kwargs)
示例9: open
# 需要導入模塊: import httpx [as 別名]
# 或者: from httpx import Client [as 別名]
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)
示例10: __init__
# 需要導入模塊: import httpx [as 別名]
# 或者: from httpx import Client [as 別名]
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
示例11: test_update_compatibility_fail
# 需要導入模塊: import httpx [as 別名]
# 或者: from httpx import Client [as 別名]
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
示例12: __init__
# 需要導入模塊: import httpx [as 別名]
# 或者: from httpx import Client [as 別名]
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)
示例13: __repr__
# 需要導入模塊: import httpx [as 別名]
# 或者: from httpx import Client [as 別名]
def __repr__(self):
return f"<AudibleAPI Client async={self.is_async}>"
示例14: _request
# 需要導入模塊: import httpx [as 別名]
# 或者: from httpx import Client [as 別名]
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