alexapy.aiohttp.client

HTTP Client for asyncio.

Functions

  • request(): Constructs and sends a request. Returns response object.

alexapy.aiohttp.client.request(method: str, url: typing.Union[str, yarl.URL], *, params: typing.Optional[typing.Mapping[str, str]] = None, data: typing.Any = None, json: typing.Any = None, headers: typing.Optional[typing.Union[typing.Mapping[typing.Union[str, multidict._multidict.istr], str], multidict._multidict.CIMultiDict, multidict._multidict.CIMultiDictProxy]] = None, skip_auto_headers: typing.Optional[typing.Iterable[str]] = None, auth: typing.Optional[alexapy.aiohttp.helpers.BasicAuth] = None, allow_redirects: bool = True, max_redirects: int = 10, compress: typing.Optional[str] = None, chunked: typing.Optional[bool] = None, expect100: bool = False, raise_for_status: typing.Optional[bool] = None, read_until_eof: bool = True, proxy: typing.Optional[typing.Union[str, yarl.URL]] = None, proxy_auth: typing.Optional[alexapy.aiohttp.helpers.BasicAuth] = None, timeout: typing.Union[alexapy.aiohttp.client.ClientTimeout, object] = <object object>, cookies: typing.Optional[typing.Union[typing.Mapping[str, typing.Union[str, BaseCookie[str], Morsel[Any]]], typing.Iterable[typing.Tuple[str, typing.Union[str, BaseCookie[str], Morsel[Any]]]], BaseCookie[str]]] = None, version: alexapy.aiohttp.http_writer.HttpVersion = HttpVersion(major=1, minor=1), connector: typing.Optional[alexapy.aiohttp.connector.BaseConnector] = None, read_bufsize: typing.Optional[int] = None, loop: typing.Optional[asyncio.events.AbstractEventLoop] = None) alexapy.aiohttp.client._SessionRequestContextManager

Constructs and sends a request.

Returns response object. method - HTTP method url - request url params - (optional) Dictionary or bytes to be sent in the query

string of the new request

data - (optional) Dictionary, bytes, or file-like object to

send in the body of the request

json - (optional) Any json compatible python object headers - (optional) Dictionary of HTTP Headers to send with

the request

cookies - (optional) Dict object to send with the request auth - (optional) BasicAuth named tuple represent HTTP Basic Auth auth - aiohttp.helpers.BasicAuth allow_redirects - (optional) If set to False, do not follow

redirects

version - Request HTTP version. compress - Set to True if request has to be compressed

with deflate encoding.

chunked - Set to chunk size for chunked transfer encoding. expect100 - Expect 100-continue response from server. connector - BaseConnector sub-class instance to support

connection pooling.

read_until_eof - Read response until eof if response

does not have Content-Length header.

loop - Optional event loop. timeout - Optional ClientTimeout settings structure, 5min

total timeout by default.

Usage::
>>> import aiohttp
>>> resp = await aiohttp.request('GET', 'http://python.org/')
>>> resp
<ClientResponse(python.org/) [200]>
>>> data = await resp.read()

Classes

class alexapy.aiohttp.client.ClientRequest(method: str, url: yarl.URL, *, params: Optional[Mapping[str, str]] = None, headers: Optional[Union[Mapping[Union[str, multidict._multidict.istr], str], multidict._multidict.CIMultiDict, multidict._multidict.CIMultiDictProxy]] = None, skip_auto_headers: Iterable[str] = frozenset({}), data: Any = None, cookies: Optional[Union[Mapping[str, Union[str, BaseCookie[str], Morsel[Any]]], Iterable[Tuple[str, Union[str, BaseCookie[str], Morsel[Any]]]], BaseCookie[str]]] = None, auth: Optional[alexapy.aiohttp.helpers.BasicAuth] = None, version: alexapy.aiohttp.http_writer.HttpVersion = HttpVersion(major=1, minor=1), compress: Optional[str] = None, chunked: Optional[bool] = None, expect100: bool = False, loop: Optional[asyncio.events.AbstractEventLoop] = None, response_class: Optional[Type[ClientResponse]] = None, proxy: Optional[yarl.URL] = None, proxy_auth: Optional[alexapy.aiohttp.helpers.BasicAuth] = None, timer: Optional[alexapy.aiohttp.helpers.BaseTimerContext] = None, session: Optional[ClientSession] = None, ssl: Optional[Union[ssl.SSLContext, bool, alexapy.aiohttp.client_reqrep.Fingerprint]] = None, proxy_headers: Optional[Union[Mapping[Union[str, multidict._multidict.istr], str], multidict._multidict.CIMultiDict, multidict._multidict.CIMultiDictProxy]] = None, traces: Optional[List[Trace]] = None)

Inheritance

Inheritance diagram of ClientRequest

update_auth(auth: Optional[alexapy.aiohttp.helpers.BasicAuth]) None

Set basic auth.

update_content_encoding(data: Any) None

Set request content encoding.

update_cookies(cookies: Optional[Union[Mapping[str, Union[str, BaseCookie[str], Morsel[Any]]], Iterable[Tuple[str, Union[str, BaseCookie[str], Morsel[Any]]]], BaseCookie[str]]]) None

Update request cookies header.

update_headers(headers: Optional[Union[Mapping[Union[str, multidict._multidict.istr], str], multidict._multidict.CIMultiDict, multidict._multidict.CIMultiDictProxy]]) None

Update request headers.

update_host(url: yarl.URL) None

Update destination host, port and connection type (ssl).

update_transfer_encoding() None

Analyze transfer-encoding header.

update_version(version: Union[alexapy.aiohttp.http_writer.HttpVersion, str]) None

Convert request version to two elements tuple.

parser HTTP version ‘1.1’ => (1, 1)

async write_bytes(writer: alexapy.aiohttp.abc.AbstractStreamWriter, conn: Connection) None

Support coroutines that yields bytes objects.

class alexapy.aiohttp.client.ClientResponse(method: str, url: yarl.URL, *, writer: asyncio.Task[None], continue100: Optional[asyncio.Future[bool]], timer: alexapy.aiohttp.helpers.BaseTimerContext, request_info: alexapy.aiohttp.client_reqrep.RequestInfo, traces: List[Trace], loop: asyncio.events.AbstractEventLoop, session: ClientSession)

Inheritance

Inheritance diagram of ClientResponse

history

A sequence of of responses, if redirects occurred.

async json(*, encoding: typing.Optional[str] = None, loads: typing.Callable[[str], typing.Any] = <function loads>, content_type: typing.Optional[str] = 'application/json') Any

Read and decodes JSON response.

property ok: bool

Returns True if status is less than 400, False if not.

This is not a check for 200 OK but a check that the response status is under 400.

async read() bytes

Read response payload.

async start(connection: Connection) ClientResponse

Start response processing.

async text(encoding: Optional[str] = None, errors: str = 'strict') str

Read response payload and decode.

class alexapy.aiohttp.client.Fingerprint(fingerprint: bytes)

Inheritance

Inheritance diagram of Fingerprint

class alexapy.aiohttp.client.RequestInfo(url: yarl.URL, method: str, headers: multidict._multidict.CIMultiDictProxy, real_url: yarl.URL = NOTHING)

Inheritance

Inheritance diagram of RequestInfo

class alexapy.aiohttp.client.BaseConnector(*, keepalive_timeout: typing.Union[object, None, float] = <object object>, force_close: bool = False, limit: int = 100, limit_per_host: int = 0, enable_cleanup_closed: bool = False, loop: typing.Optional[asyncio.events.AbstractEventLoop] = None)

Base connector class.

keepalive_timeout - (optional) Keep-alive timeout. force_close - Set to True to force close and do reconnect

after each request (and between redirects).

limit - The total number of simultaneous connections. limit_per_host - Number of simultaneous connections to one host. enable_cleanup_closed - Enables clean-up closed ssl transports.

Disabled by default.

loop - Optional event loop.

Inheritance

Inheritance diagram of BaseConnector

close() Awaitable[None]

Close all opened transports.

property closed: bool

Is connector closed.

A readonly property.

async connect(req: ClientRequest, traces: List[Trace], timeout: ClientTimeout) alexapy.aiohttp.connector.Connection

Get from pool or create new connection.

property force_close: bool

Ultimately close connection on releasing if True.

property limit: int

The total number for simultaneous connections.

If limit is 0 the connector has no limit. The default limit size is 100.

property limit_per_host: int

The limit for simultaneous connections to the same endpoint.

Endpoints are the same if they are have equal (host, port, is_ssl) triple.

class alexapy.aiohttp.client.TCPConnector(*, verify_ssl: bool = True, fingerprint: typing.Optional[bytes] = None, use_dns_cache: bool = True, ttl_dns_cache: typing.Optional[int] = 10, family: int = 0, ssl_context: typing.Optional[ssl.SSLContext] = None, ssl: typing.Union[None, bool, alexapy.aiohttp.client_reqrep.Fingerprint, ssl.SSLContext] = None, local_addr: typing.Optional[typing.Tuple[str, int]] = None, resolver: typing.Optional[alexapy.aiohttp.abc.AbstractResolver] = None, keepalive_timeout: typing.Union[None, float, object] = <object object>, force_close: bool = False, limit: int = 100, limit_per_host: int = 0, enable_cleanup_closed: bool = False, loop: typing.Optional[asyncio.events.AbstractEventLoop] = None)

TCP connector.

verify_ssl - Set to True to check ssl certifications. fingerprint - Pass the binary sha256

digest of the expected certificate in DER format to verify that the certificate the server presents matches. See also https://en.wikipedia.org/wiki/Transport_Layer_Security#Certificate_pinning

resolver - Enable DNS lookups and use this

resolver

use_dns_cache - Use memory cache for DNS lookups. ttl_dns_cache - Max seconds having cached a DNS entry, None forever. family - socket address family local_addr - local tuple of (host, port) to bind socket to

keepalive_timeout - (optional) Keep-alive timeout. force_close - Set to True to force close and do reconnect

after each request (and between redirects).

limit - The total number of simultaneous connections. limit_per_host - Number of simultaneous connections to one host. enable_cleanup_closed - Enables clean-up closed ssl transports.

Disabled by default.

loop - Optional event loop.

Inheritance

Inheritance diagram of TCPConnector

clear_dns_cache(host: Optional[str] = None, port: Optional[int] = None) None

Remove specified host/port or clear all dns local cache.

close() Awaitable[None]

Close all ongoing DNS calls.

property family: int

Socket family like AF_INET.

property use_dns_cache: bool

True if local DNS caching is enabled.

class alexapy.aiohttp.client.UnixConnector(path: str, force_close: bool = False, keepalive_timeout: typing.Optional[typing.Union[object, float]] = <object object>, limit: int = 100, limit_per_host: int = 0, loop: typing.Optional[asyncio.events.AbstractEventLoop] = None)

Unix socket connector.

path - Unix socket path. keepalive_timeout - (optional) Keep-alive timeout. force_close - Set to True to force close and do reconnect

after each request (and between redirects).

limit - The total number of simultaneous connections. limit_per_host - Number of simultaneous connections to one host. loop - Optional event loop.

Inheritance

Inheritance diagram of UnixConnector

property path: str

Path to unix socket.

class alexapy.aiohttp.client.NamedPipeConnector(path: str, force_close: bool = False, keepalive_timeout: typing.Optional[typing.Union[object, float]] = <object object>, limit: int = 100, limit_per_host: int = 0, loop: typing.Optional[asyncio.events.AbstractEventLoop] = None)

Named pipe connector.

Only supported by the proactor event loop. See also: https://docs.python.org/3.7/library/asyncio-eventloop.html

path - Windows named pipe path. keepalive_timeout - (optional) Keep-alive timeout. force_close - Set to True to force close and do reconnect

after each request (and between redirects).

limit - The total number of simultaneous connections. limit_per_host - Number of simultaneous connections to one host. loop - Optional event loop.

Inheritance

Inheritance diagram of NamedPipeConnector

property path: str

Path to the named pipe.

class alexapy.aiohttp.client.ClientWebSocketResponse(reader: alexapy.aiohttp.streams.FlowControlDataQueue[alexapy.aiohttp.http_websocket.WSMessage], writer: alexapy.aiohttp.http_websocket.WebSocketWriter, protocol: Optional[str], response: alexapy.aiohttp.client_reqrep.ClientResponse, timeout: float, autoclose: bool, autoping: bool, loop: asyncio.events.AbstractEventLoop, *, receive_timeout: Optional[float] = None, heartbeat: Optional[float] = None, compress: int = 0, client_notakeover: bool = False)

Inheritance

Inheritance diagram of ClientWebSocketResponse

get_extra_info(name: str, default: Optional[Any] = None) Any

extra info from connection transport

class alexapy.aiohttp.client.ClientSession(base_url: typing.Optional[typing.Union[str, yarl.URL]] = None, *, connector: typing.Optional[alexapy.aiohttp.connector.BaseConnector] = None, loop: typing.Optional[asyncio.events.AbstractEventLoop] = None, cookies: typing.Optional[typing.Union[typing.Mapping[str, typing.Union[str, BaseCookie[str], Morsel[Any]]], typing.Iterable[typing.Tuple[str, typing.Union[str, BaseCookie[str], Morsel[Any]]]], BaseCookie[str]]] = None, headers: typing.Optional[typing.Union[typing.Mapping[typing.Union[str, multidict._multidict.istr], str], multidict._multidict.CIMultiDict, multidict._multidict.CIMultiDictProxy]] = None, skip_auto_headers: typing.Optional[typing.Iterable[str]] = None, auth: typing.Optional[alexapy.aiohttp.helpers.BasicAuth] = None, json_serialize: typing.Callable[[typing.Any], str] = <function dumps>, request_class: typing.Type[alexapy.aiohttp.client_reqrep.ClientRequest] = <class 'alexapy.aiohttp.client_reqrep.ClientRequest'>, response_class: typing.Type[alexapy.aiohttp.client_reqrep.ClientResponse] = <class 'alexapy.aiohttp.client_reqrep.ClientResponse'>, ws_response_class: typing.Type[alexapy.aiohttp.client_ws.ClientWebSocketResponse] = <class 'alexapy.aiohttp.client_ws.ClientWebSocketResponse'>, version: alexapy.aiohttp.http_writer.HttpVersion = HttpVersion(major=1, minor=1), cookie_jar: typing.Optional[alexapy.aiohttp.abc.AbstractCookieJar] = None, connector_owner: bool = True, raise_for_status: bool = False, read_timeout: typing.Union[float, object] = <object object>, conn_timeout: typing.Optional[float] = None, timeout: typing.Union[object, alexapy.aiohttp.client.ClientTimeout] = <object object>, auto_decompress: bool = True, trust_env: bool = False, requote_redirect_url: bool = True, trace_configs: typing.Optional[typing.List[alexapy.aiohttp.tracing.TraceConfig]] = None, read_bufsize: int = 65536)

First-class interface for making HTTP requests.

Inheritance

Inheritance diagram of ClientSession

property auth: Optional[alexapy.aiohttp.helpers.BasicAuth]

An object that represents HTTP Basic Authorization

property auto_decompress: bool

Should the body response be automatically decompressed.

async close() None

Close underlying connector.

Release all acquired resources.

property closed: bool

Is client session closed.

A readonly property.

property connector: Optional[alexapy.aiohttp.connector.BaseConnector]

Connector instance used for the session.

property connector_owner: bool

Should connector be closed on session closing

property cookie_jar: alexapy.aiohttp.abc.AbstractCookieJar

The session cookies.

delete(url: Union[str, yarl.URL], **kwargs: Any) alexapy.aiohttp.client._RequestContextManager

Perform HTTP DELETE request.

detach() None

Detach connector from session without closing the former.

Session is switched to closed state anyway.

get(url: Union[str, yarl.URL], *, allow_redirects: bool = True, **kwargs: Any) alexapy.aiohttp.client._RequestContextManager

Perform HTTP GET request.

head(url: Union[str, yarl.URL], *, allow_redirects: bool = False, **kwargs: Any) alexapy.aiohttp.client._RequestContextManager

Perform HTTP HEAD request.

property headers: multidict._multidict.CIMultiDict

The default headers of the client session.

property json_serialize: Callable[[Any], str]

Json serializer callable

property loop: asyncio.events.AbstractEventLoop

Session’s loop.

options(url: Union[str, yarl.URL], *, allow_redirects: bool = True, **kwargs: Any) alexapy.aiohttp.client._RequestContextManager

Perform HTTP OPTIONS request.

patch(url: Union[str, yarl.URL], *, data: Optional[Any] = None, **kwargs: Any) alexapy.aiohttp.client._RequestContextManager

Perform HTTP PATCH request.

post(url: Union[str, yarl.URL], *, data: Optional[Any] = None, **kwargs: Any) alexapy.aiohttp.client._RequestContextManager

Perform HTTP POST request.

put(url: Union[str, yarl.URL], *, data: Optional[Any] = None, **kwargs: Any) alexapy.aiohttp.client._RequestContextManager

Perform HTTP PUT request.

property raise_for_status: Union[bool, Callable[[alexapy.aiohttp.client_reqrep.ClientResponse], Awaitable[None]]]

Should ClientResponse.raise_for_status() be called for each response.

request(method: str, url: Union[str, yarl.URL], **kwargs: Any) alexapy.aiohttp.client._RequestContextManager

Perform HTTP request.

property requote_redirect_url: bool

Do URL requoting on redirection handling.

property skip_auto_headers: FrozenSet[multidict._multidict.istr]

Headers for which autogeneration should be skipped

property timeout: Union[object, alexapy.aiohttp.client.ClientTimeout]

Timeout for the session.

property trace_configs: List[alexapy.aiohttp.tracing.TraceConfig]

A list of TraceConfig instances used for client tracing

property trust_env: bool

Should proxies information from environment or netrc be trusted.

Information is from HTTP_PROXY / HTTPS_PROXY environment variables or ~/.netrc file if present.

property version: Tuple[int, int]

The session HTTP protocol version.

ws_connect(url: Union[str, yarl.URL], *, method: str = 'GET', protocols: Iterable[str] = (), timeout: float = 10.0, receive_timeout: Optional[float] = None, autoclose: bool = True, autoping: bool = True, heartbeat: Optional[float] = None, auth: Optional[alexapy.aiohttp.helpers.BasicAuth] = None, origin: Optional[str] = None, params: Optional[Mapping[str, str]] = None, headers: Optional[Union[Mapping[Union[str, multidict._multidict.istr], str], multidict._multidict.CIMultiDict, multidict._multidict.CIMultiDictProxy]] = None, proxy: Optional[Union[str, yarl.URL]] = None, proxy_auth: Optional[alexapy.aiohttp.helpers.BasicAuth] = None, ssl: Union[None, bool, alexapy.aiohttp.client_reqrep.Fingerprint, ssl.SSLContext] = None, verify_ssl: Optional[bool] = None, fingerprint: Optional[bytes] = None, ssl_context: Optional[ssl.SSLContext] = None, proxy_headers: Optional[Union[Mapping[Union[str, multidict._multidict.istr], str], multidict._multidict.CIMultiDict, multidict._multidict.CIMultiDictProxy]] = None, compress: int = 0, max_msg_size: int = 4194304) alexapy.aiohttp.client._WSRequestContextManager

Initiate websocket connection.

class alexapy.aiohttp.client.ClientTimeout(total: Optional[float] = None, connect: Optional[float] = None, sock_read: Optional[float] = None, sock_connect: Optional[float] = None)

Inheritance

Inheritance diagram of ClientTimeout

Exceptions

exception alexapy.aiohttp.client.ClientConnectionError

Base class for client socket errors.

Inheritance

Inheritance diagram of ClientConnectionError

exception alexapy.aiohttp.client.ClientConnectorCertificateError(connection_key: None, certificate_error: Exception)

Response certificate error.

Inheritance

Inheritance diagram of ClientConnectorCertificateError

exception alexapy.aiohttp.client.ClientConnectorError(connection_key: None, os_error: OSError)

Client connector error.

Raised in aiohttp.connector.TCPConnector if

connection to proxy can not be established.

Inheritance

Inheritance diagram of ClientConnectorError

exception alexapy.aiohttp.client.ClientConnectorSSLError(connection_key: None, os_error: OSError)

Response ssl error.

Inheritance

Inheritance diagram of ClientConnectorSSLError

exception alexapy.aiohttp.client.ClientError

Base class for client connection errors.

Inheritance

Inheritance diagram of ClientError

exception alexapy.aiohttp.client.ClientHttpProxyError(request_info: None, history: Tuple[None, ...], *, code: Optional[int] = None, status: Optional[int] = None, message: str = '', headers: Optional[Union[Mapping[Union[str, multidict._multidict.istr], str], multidict._multidict.CIMultiDict, multidict._multidict.CIMultiDictProxy]] = None)

HTTP proxy error.

Raised in aiohttp.connector.TCPConnector if proxy responds with status other than 200 OK on CONNECT request.

Inheritance

Inheritance diagram of ClientHttpProxyError

exception alexapy.aiohttp.client.ClientOSError

OSError error.

Inheritance

Inheritance diagram of ClientOSError

exception alexapy.aiohttp.client.ClientPayloadError

Response payload error.

Inheritance

Inheritance diagram of ClientPayloadError

exception alexapy.aiohttp.client.ClientProxyConnectionError(connection_key: None, os_error: OSError)

Proxy connection error.

Raised in aiohttp.connector.TCPConnector if

connection to proxy can not be established.

Inheritance

Inheritance diagram of ClientProxyConnectionError

exception alexapy.aiohttp.client.ClientResponseError(request_info: None, history: Tuple[None, ...], *, code: Optional[int] = None, status: Optional[int] = None, message: str = '', headers: Optional[Union[Mapping[Union[str, multidict._multidict.istr], str], multidict._multidict.CIMultiDict, multidict._multidict.CIMultiDictProxy]] = None)

Connection error during reading response.

request_info: instance of RequestInfo

Inheritance

Inheritance diagram of ClientResponseError

exception alexapy.aiohttp.client.ClientSSLError(connection_key: None, os_error: OSError)

Base error for ssl.*Errors.

Inheritance

Inheritance diagram of ClientSSLError

exception alexapy.aiohttp.client.ContentTypeError(request_info: None, history: Tuple[None, ...], *, code: Optional[int] = None, status: Optional[int] = None, message: str = '', headers: Optional[Union[Mapping[Union[str, multidict._multidict.istr], str], multidict._multidict.CIMultiDict, multidict._multidict.CIMultiDictProxy]] = None)

ContentType found is not valid.

Inheritance

Inheritance diagram of ContentTypeError

exception alexapy.aiohttp.client.InvalidURL(url: Any)

Invalid URL.

URL used for fetching is malformed, e.g. it doesn’t contains host part.

Inheritance

Inheritance diagram of InvalidURL

exception alexapy.aiohttp.client.ServerConnectionError

Server connection errors.

Inheritance

Inheritance diagram of ServerConnectionError

exception alexapy.aiohttp.client.ServerDisconnectedError(message: Optional[Union[alexapy.aiohttp.http_parser.RawResponseMessage, str]] = None)

Server disconnected.

Inheritance

Inheritance diagram of ServerDisconnectedError

exception alexapy.aiohttp.client.ServerFingerprintMismatch(expected: bytes, got: bytes, host: str, port: int)

SSL certificate does not match expected fingerprint.

Inheritance

Inheritance diagram of ServerFingerprintMismatch

exception alexapy.aiohttp.client.ServerTimeoutError

Server timeout error.

Inheritance

Inheritance diagram of ServerTimeoutError

exception alexapy.aiohttp.client.TooManyRedirects(request_info: None, history: Tuple[None, ...], *, code: Optional[int] = None, status: Optional[int] = None, message: str = '', headers: Optional[Union[Mapping[Union[str, multidict._multidict.istr], str], multidict._multidict.CIMultiDict, multidict._multidict.CIMultiDictProxy]] = None)

Client was redirected too many times.

Inheritance

Inheritance diagram of TooManyRedirects

exception alexapy.aiohttp.client.WSServerHandshakeError(request_info: None, history: Tuple[None, ...], *, code: Optional[int] = None, status: Optional[int] = None, message: str = '', headers: Optional[Union[Mapping[Union[str, multidict._multidict.istr], str], multidict._multidict.CIMultiDict, multidict._multidict.CIMultiDictProxy]] = None)

websocket server handshake error.

Inheritance

Inheritance diagram of WSServerHandshakeError