Client Reference¶
Client Session¶
Client session is the recommended interface for making HTTP requests.
Session encapsulates a connection pool (connector instance) and supports keepalives by default. Unless you are connecting to a large, unknown number of different servers over the lifetime of your application, it is suggested you use a single session for the lifetime of your application to benefit from connection pooling.
Usage example:
import aiohttp
import asyncio
async def fetch(client):
async with client.get('http://python.org') as resp:
assert resp.status == 200
return await resp.text()
async def main():
async with aiohttp.ClientSession() as client:
html = await fetch(client)
print(html)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
The client session supports the context manager protocol for self closing.
-
class
aiohttp.ClientSession(*, connector=None, loop=None, cookies=None, headers=None, skip_auto_headers=None, auth=None, json_serialize=json.dumps, version=aiohttp.HttpVersion11, cookie_jar=None, read_timeout=None, conn_timeout=None, timeout=sentinel, raise_for_status=False, connector_owner=True, auto_decompress=True, proxies=None)¶ The class for creating client sessions and making requests.
Parameters: - connector (aiohttp.connector.BaseConnector) – BaseConnector sub-class instance to support connection pooling.
- loop –
event loop used for processing HTTP requests.
If loop is
Nonethe constructor borrows it from connector if specified.asyncio.get_event_loop()is used for getting default event loop otherwise.Deprecated since version 2.0.
- cookies (dict) – Cookies to send with the request (optional)
- headers –
HTTP Headers to send with every request (optional).
May be either iterable of key-value pairs or
Mapping(e.g.dict,CIMultiDict). - skip_auto_headers –
set of headers for which autogeneration should be skipped.
aiohttp autogenerates headers like
User-AgentorContent-Typeif these headers are not explicitly passed. Usingskip_auto_headersparameter allows to skip that generation. Note thatContent-Lengthautogeneration can’t be skipped.Iterable of
stroristr(optional) - auth (aiohttp.BasicAuth) – an object that represents HTTP Basic Authorization (optional)
- version – supported HTTP version,
HTTP 1.1by default. - cookie_jar –
Cookie Jar,
AbstractCookieJarinstance.By default every session instance has own private cookie jar for automatic cookies processing but user may redefine this behavior by providing own jar implementation.
One example is not processing cookies at all when working in proxy mode.
If no cookie processing is needed, a
aiohttp.DummyCookieJarinstance can be provided. - json_serialize (callable) –
Json serializer callable.
By default
json.dumps()function. - raise_for_status (bool) –
Automatically call
ClientResponse.raise_for_status()for each response,Falseby default.This parameter can be overridden when you making a request, e.g.:
client_session = aiohttp.ClientSession(raise_for_status=True) resp = await client_session.get(url, raise_for_status=False) async with resp: assert resp.status == 200
Set the parameter to
Trueif you needraise_for_statusfor most of cases but overrideraise_for_statusfor those requests where you need to handle responses with status 400 or higher. - timeout –
- a
ClientTimeoutsettings structure, 5min - total timeout by default.
New in version 3.3.
- a
- read_timeout (float) –
Request operations timeout.
read_timeoutis cumulative for all request operations (request, redirects, responses, data consuming). By default, the read timeout is 5*60 seconds. UseNoneor0to disable timeout checks.Deprecated since version 3.3: Use
timeoutparameter instead. - conn_timeout (float) –
timeout for connection establishing (optional). Values
0orNonemean no timeout.Deprecated since version 3.3: Use
timeoutparameter instead. - connector_owner (bool) –
Close connector instance on session closing.
Setting the parameter to
Falseallows to share connection pool between sessions without sharing session state: cookies etc. - auto_decompress (bool) –
- Automatically decompress response body,
Trueby default
New in version 2.3.
- trust_env (bool) –
Get proxies information from HTTP_PROXY / HTTPS_PROXY environment variables if the parameter is
True(Falseby default).Get proxy credentials from
~/.netrcfile if present.See also
.netrcdocumentation: https://www.gnu.org/software/inetutils/manual/html_node/The-_002enetrc-file.htmlNew in version 2.3.
Changed in version 3.0: Added support for
~/.netrcfile.
-
closed¶ Trueif the session has been closed,Falseotherwise.A read-only property.
-
connector¶
aiohttp.connector.BaseConnectorderived instance usedfor the session.
A read-only property.
The session cookies,
AbstractCookieJarinstance.Gives access to cookie jar’s content and modifiers.
A read-only property.
-
requote_redirect_url¶ aiohttp re quote’s redirect urls by default, but some servers require exact url from location header. To disable re-quote system set
requote_redirect_urlattribute toFalse.New in version 2.1.
Note
This parameter affects all subsequent requests.
-
loop¶ A loop instance used for session creation.
A read-only property.
-
coroutine async-with
request(method, url, *, params=None, data=None, json=None, headers=None, skip_auto_headers=None, auth=None, allow_redirects=True, max_redirects=10, compress=None, chunked=None, expect100=False, raise_for_status=None, read_until_eof=True, proxy=None, proxy_auth=None, timeout=sentinel, ssl=None, verify_ssl=None, fingerprint=None, ssl_context=None, proxy_headers=None)¶ Performs an asynchronous HTTP request. Returns a response object.
Parameters: - method (str) – HTTP method
- url – Request URL,
strorURL. - params –
Mapping, iterable of tuple of key/value pairs or string to be sent as parameters in the query string of the new request. Ignored for subsequent redirected requests (optional)
Allowed values are:
collections.abc.Mappinge.g.dict,aiohttp.MultiDictoraiohttp.MultiDictProxycollections.abc.Iterablee.g.tupleorliststrwith preferably url-encoded content (Warning: content will not be encoded by aiohttp)
- data – Dictionary, bytes, or file-like object to send in the body of the request (optional)
- json – Any json compatible python object (optional). json and data parameters could not be used at the same time.
- headers (dict) – HTTP Headers to send with the request (optional)
- skip_auto_headers –
set of headers for which autogeneration should be skipped.
aiohttp autogenerates headers like
User-AgentorContent-Typeif these headers are not explicitly passed. Usingskip_auto_headersparameter allows to skip that generation.Iterable of
stroristr(optional) - auth (aiohttp.BasicAuth) – an object that represents HTTP Basic Authorization (optional)
- allow_redirects (bool) – If set to
False, do not follow redirects.Trueby default (optional). - max_redirects (int) – Maximum number of redirects to follow.
10by default. - compress (bool) – Set to
Trueif request has to be compressed with deflate encoding. If compress can not be combined with a Content-Encoding and Content-Length headers.Noneby default (optional). - chunked (int) – Enable chunked transfer encoding.
It is up to the developer
to decide how to chunk data streams. If chunking is enabled, aiohttp
encodes the provided chunks in the “Transfer-encoding: chunked” format.
If chunked is set, then the Transfer-encoding and content-length
headers are disallowed.
Noneby default (optional). - expect100 (bool) – Expect 100-continue response from server.
Falseby default (optional). - raise_for_status (bool) –
- Automatically call
ClientResponse.raise_for_status()for - response if set to
True. If set toNonevalue fromClientSessionwill be used.Noneby default (optional).
New in version 3.4.
- Automatically call
- read_until_eof (bool) – Read response until EOF if response
does not have Content-Length header.
Trueby default (optional). - proxy – Proxy URL,
strorURL(optional) - proxy_auth (aiohttp.BasicAuth) – an object that represents proxy HTTP Basic Authorization (optional)
- timeout (int) –
override the session’s timeout.
Changed in version 3.3: The parameter is
ClientTimeoutinstance,floatis still supported for sake of backward compatibility.If
floatis passed it is a total timeout. - ssl –
- SSL validation mode.
Nonefor default SSL check - (
ssl.create_default_context()is used),Falsefor skip SSL certificate validation,aiohttp.Fingerprintfor fingerprint validation,ssl.SSLContextfor custom SSL certificate validation.Supersedes verify_ssl, ssl_context and fingerprint parameters.
New in version 3.0.
- SSL validation mode.
- verify_ssl (bool) –
Perform SSL certificate validation for HTTPS requests (enabled by default). May be disabled to skip validation for sites with invalid certificates.
New in version 2.3.
Deprecated since version 3.0: Use
ssl=False - fingerprint (bytes) –
Pass the SHA256 digest of the expected certificate in DER format to verify that the certificate the server presents matches. Useful for certificate pinning.
Warning: use of MD5 or SHA1 digests is insecure and removed.
New in version 2.3.
Deprecated since version 3.0: Use
ssl=aiohttp.Fingerprint(digest) - ssl_context (ssl.SSLContext) –
ssl context used for processing HTTPS requests (optional).
ssl_context may be used for configuring certification authority channel, supported SSL options etc.
New in version 2.3.
Deprecated since version 3.0: Use
ssl=ssl_context - proxy_headers (abc.Mapping) –
HTTP headers to send to the proxy if the parameter proxy has been provided.
New in version 2.3.
- trace_request_ctx –
Object used to give as a kw param for each new
TraceConfigobject instantiated, used to give information to the tracers that is only available at request time.New in version 3.0.
Return ClientResponse: a
client responseobject.
-
coroutine async-with
get(url, *, allow_redirects=True, **kwargs)¶ Perform a
GETrequest.In order to modify inner
requestparameters, provide kwargs.Parameters: Return ClientResponse: a
client responseobject.
-
coroutine async-with
post(url, *, data=None, **kwargs)¶ Perform a
POSTrequest.In order to modify inner
requestparameters, provide kwargs.Parameters: Return ClientResponse: a
client responseobject.
-
coroutine async-with
put(url, *, data=None, **kwargs)¶ Perform a
PUTrequest.In order to modify inner
requestparameters, provide kwargs.Parameters: Return ClientResponse: a
client responseobject.
-
coroutine async-with
delete(url, **kwargs)¶ Perform a
DELETErequest.In order to modify inner
requestparameters, provide kwargs.Parameters: url – Request URL, strorURLReturn ClientResponse: a client responseobject.
-
coroutine async-with
head(url, *, allow_redirects=False, **kwargs)¶ Perform a
HEADrequest.In order to modify inner
requestparameters, provide kwargs.Parameters: Return ClientResponse: a
client responseobject.
-
coroutine async-with
options(url, *, allow_redirects=True, **kwargs)¶ Perform an
OPTIONSrequest.In order to modify inner
requestparameters, provide kwargs.Parameters: Return ClientResponse: a
client responseobject.
-
coroutine async-with
patch(url, *, data=None, **kwargs)¶ Perform a
PATCHrequest.In order to modify inner
requestparameters, provide kwargs.Parameters: Return ClientResponse: a
client responseobject.
-
coroutine async-with
ws_connect(url, *, protocols=(), timeout=10.0, receive_timeout=None, auth=None, autoclose=True, autoping=True, heartbeat=None, origin=None, headers=None, proxy=None, proxy_auth=None, ssl=None, verify_ssl=None, fingerprint=None, ssl_context=None, proxy_headers=None, compress=0, max_msg_size=4194304)¶ Create a websocket connection. Returns a
ClientWebSocketResponseobject.Parameters: - url – Websocket server url,
strorURL - protocols (tuple) – Websocket protocols
- timeout (float) – Timeout for websocket to close.
10seconds by default - receive_timeout (float) – Timeout for websocket to receive
complete message.
None(unlimited) seconds by default - auth (aiohttp.BasicAuth) – an object that represents HTTP Basic Authorization (optional)
- autoclose (bool) – Automatically close websocket connection on close
message from server. If autoclose is False
then close procedure has to be handled manually.
Trueby default - autoping (bool) – automatically send pong on ping
message from server.
Trueby default - heartbeat (float) – Send ping message every heartbeat seconds and wait pong response, if pong response is not received then close connection. The timer is reset on any data reception.(optional)
- origin (str) – Origin header to send to server(optional)
- headers (dict) – HTTP Headers to send with the request (optional)
- proxy (str) – Proxy URL,
strorURL(optional) - proxy_auth (aiohttp.BasicAuth) – an object that represents proxy HTTP Basic Authorization (optional)
- ssl –
- SSL validation mode.
Nonefor default SSL check - (
ssl.create_default_context()is used),Falsefor skip SSL certificate validation,aiohttp.Fingerprintfor fingerprint validation,ssl.SSLContextfor custom SSL certificate validation.Supersedes verify_ssl, ssl_context and fingerprint parameters.
New in version 3.0.
- SSL validation mode.
- verify_ssl (bool) –
Perform SSL certificate validation for HTTPS requests (enabled by default). May be disabled to skip validation for sites with invalid certificates.
New in version 2.3.
Deprecated since version 3.0: Use
ssl=False - fingerprint (bytes) –
Pass the SHA256 digest of the expected certificate in DER format to verify that the certificate the server presents matches. Useful for certificate pinning.
Note: use of MD5 or SHA1 digests is insecure and deprecated.
New in version 2.3.
Deprecated since version 3.0: Use
ssl=aiohttp.Fingerprint(digest) - ssl_context (ssl.SSLContext) –
ssl context used for processing HTTPS requests (optional).
ssl_context may be used for configuring certification authority channel, supported SSL options etc.
New in version 2.3.
Deprecated since version 3.0: Use
ssl=ssl_context - proxy_headers (dict) –
HTTP headers to send to the proxy if the parameter proxy has been provided.
New in version 2.3.
- compress (int) –
- Enable Per-Message Compress Extension support.
- 0 for disable, 9 to 15 for window bit support. Default value is 0.
New in version 2.3.
- max_msg_size (int) –
- maximum size of read websocket message,
- 4 MB by default. To disable the size
limit use
0.
New in version 3.3.
- url – Websocket server url,
-
coroutine
close()¶ Close underlying connector.
Release all acquired resources.
-
detach()¶ Detach connector from session without closing the former.
Session is switched to closed state anyway.
Basic API¶
While we encourage ClientSession usage we also provide simple
coroutines for making HTTP requests.
Basic API is good for performing simple HTTP requests without keepaliving, cookies and complex connection stuff like properly configured SSL certification chaining.
-
coroutine
aiohttp.request(method, url, *, params=None, data=None, json=None, headers=None, cookies=None, auth=None, allow_redirects=True, max_redirects=10, encoding='utf-8', version=HttpVersion(major=1, minor=1), compress=None, chunked=None, expect100=False, raise_for_status=None, connector=None, loop=None, read_until_eof=True)¶ Async-with: Asynchronous context manager for performing an asynchronous HTTP request. Returns a
ClientResponseresponse object.Parameters: - method (str) – HTTP method
- url – Requested URL,
strorURL - params (dict) – Parameters to be sent in the query string of the new request (optional)
- data – Dictionary, bytes, or file-like object to send in the body of the request (optional)
- json – Any json compatible python object (optional). json and data parameters could not be used at the same time.
- headers (dict) – HTTP Headers to send with the request (optional)
- cookies (dict) – Cookies to send with the request (optional)
- auth (aiohttp.BasicAuth) – an object that represents HTTP Basic Authorization (optional)
- allow_redirects (bool) – If set to
False, do not follow redirects.Trueby default (optional). - version (aiohttp.protocol.HttpVersion) – Request HTTP version (optional)
- compress (bool) – Set to
Trueif request has to be compressed with deflate encoding.Falseinstructs aiohttp to not compress data.Noneby default (optional). - chunked (int) – Enables chunked transfer encoding.
Noneby default (optional). - expect100 (bool) – Expect 100-continue response from server.
Falseby default (optional). - raise_for_status (bool) –
- Automatically call
ClientResponse.raise_for_status()for response if set toTrue. If set toNonevalue fromClientSessionwill be used.Noneby default (optional).
New in version 3.4.
- connector (aiohttp.connector.BaseConnector) – BaseConnector sub-class instance to support connection pooling.
- read_until_eof (bool) – Read response until EOF if response
does not have Content-Length header.
Trueby default (optional). - loop –
- event loop
- used for processing HTTP requests.
If param is
None,asyncio.get_event_loop()is used for getting default event loop.
Deprecated since version 2.0.
Return ClientResponse: a
client responseobject.Usage:
import aiohttp async def fetch(): async with aiohttp.request('GET', 'http://python.org/') as resp: assert resp.status == 200 print(await resp.text())
Connectors¶
Connectors are transports for aiohttp client API.
There are standard connectors:
TCPConnectorfor regular TCP sockets (both HTTP and HTTPS schemes supported).UnixConnectorfor connecting via UNIX socket (it’s used mostly for testing purposes).
All connector classes should be derived from BaseConnector.
By default all connectors support keep-alive connections (behavior is controlled by force_close constructor’s parameter).
BaseConnector¶
-
class
aiohttp.BaseConnector(*, keepalive_timeout=15, force_close=False, limit=100, limit_per_host=0, enable_cleanup_closed=False, loop=None)¶ Base class for all connectors.
Parameters: - keepalive_timeout (float) – timeout for connection reusing
after releasing (optional). Values
0. For disabling keep-alive feature useforce_close=Trueflag. - limit (int) – total number simultaneous connections. If limit is
Nonethe connector has no limit (default: 100). - limit_per_host (int) – limit simultaneous connections to the same
endpoint. Endpoints are the same if they are
have equal
(host, port, is_ssl)triple. If limit is0the connector has no limit (default: 0). - force_close (bool) – close underlying sockets after connection releasing (optional).
- enable_cleanup_closed (bool) – some SSL servers do not properly complete SSL shutdown process, in that case asyncio leaks ssl connections. If this parameter is set to True, aiohttp additionally aborts underlining transport after 2 seconds. It is off by default.
- loop –
event loop used for handling connections. If param is
None,asyncio.get_event_loop()is used for getting default event loop.Deprecated since version 2.0.
-
closed¶ Read-only property,
Trueif connector is closed.
-
force_close¶ Read-only property,
Trueif connector should ultimately close connections on releasing.
-
limit¶ The total number for simultaneous connections. If limit is 0 the connector has no limit. The default limit size is 100.
-
limit_per_host¶ The limit for simultaneous connections to the same endpoint.
Endpoints are the same if they are have equal
(host, port, is_ssl)triple.If limit_per_host is
Nonethe connector has no limit per host.Read-only property.
-
close()¶ Close all opened connections.
-
coroutine
connect(request)¶ Get a free connection from pool or create new one if connection is absent in the pool.
The call may be paused if
limitis exhausted until used connections returns to pool.Parameters: request (aiohttp.ClientRequest) – request object which is connection initiator. Returns: Connectionobject.
-
coroutine
_create_connection(req)¶ Abstract method for actual connection establishing, should be overridden in subclasses.
- keepalive_timeout (float) – timeout for connection reusing
after releasing (optional). Values
TCPConnector¶
-
class
aiohttp.TCPConnector(*, ssl=None, verify_ssl=True, fingerprint=None, use_dns_cache=True, ttl_dns_cache=10, family=0, ssl_context=None, local_addr=None, resolver=None, keepalive_timeout=sentinel, force_close=False, limit=100, limit_per_host=0, enable_cleanup_closed=False, loop=None)¶ Connector for working with HTTP and HTTPS via TCP sockets.
The most common transport. When you don’t know what connector type to use, use a
TCPConnectorinstance.TCPConnectorinherits fromBaseConnector.Constructor accepts all parameters suitable for
BaseConnectorplus several TCP-specific ones:param ssl: - SSL validation mode.
Nonefor default SSL check (
ssl.create_default_context()is used),Falsefor skip SSL certificate validation,aiohttp.Fingerprintfor fingerprint validation,ssl.SSLContextfor custom SSL certificate validation.Supersedes verify_ssl, ssl_context and fingerprint parameters.
New in version 3.0.
Parameters: - verify_ssl (bool) –
perform SSL certificate validation for HTTPS requests (enabled by default). May be disabled to skip validation for sites with invalid certificates.
Deprecated since version 2.3: Pass verify_ssl to
ClientSession.get()etc. - fingerprint (bytes) –
pass the SHA256 digest of the expected certificate in DER format to verify that the certificate the server presents matches. Useful for certificate pinning.
Note: use of MD5 or SHA1 digests is insecure and deprecated.
Deprecated since version 2.3: Pass verify_ssl to
ClientSession.get()etc. - use_dns_cache (bool) –
use internal cache for DNS lookups,
Trueby default.Enabling an option may speedup connection establishing a bit but may introduce some side effects also.
- ttl_dns_cache (int) –
expire after some seconds the DNS entries,
Nonemeans cached forever. By default 10 seconds.By default DNS entries are cached forever, in some environments the IP addresses related to a specific HOST can change after a specific time. Use this option to keep the DNS cache updated refreshing each entry after N seconds.
- limit (int) – total number simultaneous connections. If limit is
Nonethe connector has no limit (default: 100). - limit_per_host (int) – limit simultaneous connections to the same
endpoint. Endpoints are the same if they are
have equal
(host, port, is_ssl)triple. If limit is0the connector has no limit (default: 0). - resolver (aiohttp.abc.AbstractResolver) –
custom resolver instance to use.
aiohttp.DefaultResolverby default (asynchronous ifaiodns>=1.1is installed).Custom resolvers allow to resolve hostnames differently than the way the host is configured.
The resolver is
aiohttp.ThreadedResolverby default, asynchronous version is pretty robust but might fail in very rare cases. - family (int) –
TCP socket family, both IPv4 and IPv6 by default. For IPv4 only use
socket.AF_INET, for IPv6 only –socket.AF_INET6.family is
0by default, that means both IPv4 and IPv6 are accepted. To specify only concrete version please passsocket.AF_INETorsocket.AF_INET6explicitly. - ssl_context (ssl.SSLContext) –
SSL context used for processing HTTPS requests (optional).
ssl_context may be used for configuring certification authority channel, supported SSL options etc.
- local_addr (tuple) – tuple of
(local_host, local_port)used to bind socket locally if specified. - force_close (bool) – close underlying sockets after connection releasing (optional).
- enable_cleanup_closed (bool) – Some ssl servers do not properly complete SSL shutdown process, in that case asyncio leaks SSL connections. If this parameter is set to True, aiohttp additionally aborts underlining transport after 2 seconds. It is off by default.
-
family¶ TCP socket family e.g.
socket.AF_INETorsocket.AF_INET6Read-only property.
-
cached_hosts¶ The cache of resolved hosts if
dns_cacheis enabled.Read-only
types.MappingProxyTypeproperty.
-
clear_dns_cache(self, host=None, port=None)¶ Clear internal DNS cache.
Remove specific entry if both host and port are specified, clear all cache otherwise.
- SSL validation mode.
UnixConnector¶
-
class
aiohttp.UnixConnector(path, *, conn_timeout=None, keepalive_timeout=30, limit=100, force_close=False, loop=None)¶ Unix socket connector.
Use
UnixConnectorfor sending HTTP/HTTPS requests through UNIX Sockets as underlying transport.UNIX sockets are handy for writing tests and making very fast connections between processes on the same host.
UnixConnectoris inherited fromBaseConnector.Usage:
conn = UnixConnector(path='/path/to/socket') session = ClientSession(connector=conn) async with session.get('http://python.org') as resp: ...
Constructor accepts all parameters suitable for
BaseConnectorplus UNIX-specific one:Parameters: path (str) – Unix socket path
Connection¶
-
class
aiohttp.Connection¶ Encapsulates single connection in connector object.
End user should never create
Connectioninstances manually but get it byBaseConnector.connect()coroutine.-
loop¶ Event loop used for connection
-
transport¶ Connection transport
-
close()¶ Close connection with forcibly closing underlying socket.
-
release()¶ Release connection back to connector.
Underlying socket is not closed, the connection may be reused later if timeout (30 seconds by default) for connection was not expired.
-
Response object¶
-
class
aiohttp.ClientResponse¶ Client response returned be
ClientSession.request()and family.User never creates the instance of ClientResponse class but gets it from API calls.
ClientResponsesupports async context manager protocol, e.g.:resp = await client_session.get(url) async with resp: assert resp.status == 200
After exiting from
async withblock response object will be released (seerelease()coroutine).-
version¶ Response’s version,
HttpVersioninstance.
-
connection¶ Connectionused for handling response.
-
content¶ Payload stream, which contains response’s BODY (
StreamReader). It supports various reading methods depending on the expected format. When chunked transfer encoding is used by the server, allows retrieving the actual http chunks.Reading from the stream may raise
aiohttp.ClientPayloadErrorif the response object is closed before response receives all data or in case if any transfer encoding related errors like misformed chunked encoding of broken compression data.
HTTP cookies of response (Set-Cookie HTTP header,
SimpleCookie).
-
headers¶ A case-insensitive multidict proxy with HTTP headers of response,
CIMultiDictProxy.
-
raw_headers¶ Unmodified HTTP headers of response as unconverted bytes, a sequence of
(key, value)pairs.
-
links¶ Link HTTP header parsed into a
MultiDictProxy.For each link, key is link param rel when it exists, or link url as
strotherwise, and value isMultiDictProxyof link params and url at key url asURLinstance.New in version 3.2.
-
content_type¶ Read-only property with content part of Content-Type header.
Note
Returns value is
'application/octet-stream'if no Content-Type header present in HTTP headers according to RFC 2616. To make sure Content-Type header is not present in the server reply, useheadersorraw_headers, e.g.'CONTENT-TYPE' not in resp.headers.
-
charset¶ Read-only property that specifies the encoding for the request’s BODY.
The value is parsed from the Content-Type HTTP header.
Returns
strlike'utf-8'orNoneif no Content-Type header present in HTTP headers or it has no charset information.
-
content_disposition¶ Read-only property that specified the Content-Disposition HTTP header.
Instance of
ContentDispositionorNoneif no Content-Disposition header present in HTTP headers.
-
history¶ A
SequenceofClientResponseobjects of preceding requests (earliest request first) if there were redirects, an empty sequence otherwise.
-
close()¶ Close response and underlying connection.
For keep-alive support see
release().
-
coroutine
read()¶ Read the whole response’s body as
bytes.Close underlying connection if data reading gets an error, release connection otherwise.
Raise an
aiohttp.ClientResponseErrorif the data can’t be read.Return bytes: read BODY.
-
coroutine
release()¶ It is not required to call release on the response object. When the client fully receives the payload, the underlying connection automatically returns back to pool. If the payload is not fully read, the connection is closed
-
raise_for_status()¶ Raise an
aiohttp.ClientResponseErrorif the response status is 400 or higher.Do nothing for success responses (less than 400).
-
coroutine
text(encoding=None)¶ Read response’s body and return decoded
strusing specified encoding parameter.If encoding is
Nonecontent encoding is autocalculated usingContent-TypeHTTP header and chardet tool if the header is not provided by server.cchardet is used with fallback to chardet if cchardet is not available.
Close underlying connection if data reading gets an error, release connection otherwise.
Parameters: encoding (str) – text encoding used for BODY decoding, or Nonefor encoding autodetection (default).Return str: decoded BODY Raises: LookupError – if the encoding detected by chardet or cchardet is unknown by Python (e.g. VISCII).
-
coroutine
json(*, encoding=None, loads=json.loads, content_type='application/json')¶ Read response’s body as JSON, return
dictusing specified encoding and loader. If data is not still available areadcall will be done,If encoding is
Nonecontent encoding is autocalculated using cchardet or chardet as fallback if cchardet is not available.if response’s content-type does not match content_type parameter
aiohttp.ContentTypeErrorget raised. To disable content type check passNonevalue.Parameters: - encoding (str) –
text encoding used for BODY decoding, or
Nonefor encoding autodetection (default).By the standard JSON encoding should be
UTF-8but practice beats purity: some servers return non-UTF responses. Autodetection works pretty fine anyway. - loads (callable) –
callable()used for loading JSON data,json.loads()by default. - content_type (str) – specify response’s content-type, if content type
does not match raise
aiohttp.ClientResponseError. To disable content-type check, passNoneas value. (default: application/json).
Returns: BODY as JSON data parsed by loads parameter or
Noneif BODY is empty or contains white-spaces only.- encoding (str) –
-
request_info¶ A namedtuple with request URL and headers from
ClientRequestobject,aiohttp.RequestInfoinstance.
-
get_encoding()¶ Automatically detect content encoding using
charsetinfo inContent-TypeHTTP header. If this info is not exists or there are no appropriate codecs for encoding then cchardet / chardet is used.Beware that it is not always safe to use the result of this function to decode a response. Some encodings detected by cchardet are not known by Python (e.g. VISCII).
New in version 3.0.
-
ClientWebSocketResponse¶
To connect to a websocket server aiohttp.ws_connect() or
aiohttp.ClientSession.ws_connect() coroutines should be used, do
not create an instance of class ClientWebSocketResponse
manually.
-
class
aiohttp.ClientWebSocketResponse¶ Class for handling client-side websockets.
-
closed¶ Read-only property,
Trueifclose()has been called orCLOSEmessage has been received from peer.
-
protocol¶ Websocket subprotocol chosen after
start()call.May be
Noneif server and client protocols are not overlapping.
-
get_extra_info(name, default=None)¶ Reads extra info from connection’s transport
-
exception()¶ Returns exception if any occurs or returns None.
-
coroutine
ping(message=b'')¶ Send
PINGto peer.Parameters: message – optional payload of ping message, str(converted to UTF-8 encoded bytes) orbytes.Changed in version 3.0: The method is converted into coroutine
-
coroutine
pong(message=b'')¶ Send
PONGto peer.Parameters: message – optional payload of pong message, str(converted to UTF-8 encoded bytes) orbytes.Changed in version 3.0: The method is converted into coroutine
-
coroutine
send_str(data, compress=None)¶ Send data to peer as
TEXTmessage.Parameters: Raises: Changed in version 3.0: The method is converted into coroutine, compress parameter added.
-
coroutine
send_bytes(data, compress=None)¶ Send data to peer as
BINARYmessage.Parameters: - data – data to send.
- compress (int) – sets specific level of compression for
single message,
Nonefor not overriding per-socket setting.
Raises: TypeError – if data is not
bytes,bytearrayormemoryview.Changed in version 3.0: The method is converted into coroutine, compress parameter added.
-
coroutine
send_json(data, compress=None, *, dumps=json.dumps)¶ Send data to peer as JSON string.
Parameters: - data – data to send.
- compress (int) – sets specific level of compression for
single message,
Nonefor not overriding per-socket setting. - dumps (callable) – any callable that accepts an object and
returns a JSON string
(
json.dumps()by default).
Raises: - RuntimeError – if connection is not started or closing
- ValueError – if data is not serializable object
- TypeError – if value returned by
dumps(data)is notstr
Changed in version 3.0: The method is converted into coroutine, compress parameter added.
-
coroutine
close(*, code=1000, message=b'')¶ A coroutine that initiates closing handshake by sending
CLOSEmessage. It waits for close response from server. To add a timeout to close() call just wrap the call with asyncio.wait() or asyncio.wait_for().Parameters:
-
coroutine
receive()¶ A coroutine that waits upcoming data message from peer and returns it.
The coroutine implicitly handles
PING,PONGandCLOSEwithout returning the message.It process ping-pong game and performs closing handshake internally.
Returns: WSMessage
-
coroutine
receive_str()¶ A coroutine that calls
receive()but also asserts the message type isTEXT.Return str: peer’s message content. Raises: TypeError – if message is BINARY.
-
coroutine
receive_bytes()¶ A coroutine that calls
receive()but also asserts the message type isBINARY.Return bytes: peer’s message content. Raises: TypeError – if message is TEXT.
-
coroutine
receive_json(*, loads=json.loads)¶ A coroutine that calls
receive_str()and loads the JSON string to a Python dict.Parameters: loads (callable) – any callable that accepts
strand returnsdictwith parsed JSON (json.loads()by default).Return dict: loaded JSON content
Raises: - TypeError – if message is
BINARY. - ValueError – if message is not valid JSON.
- TypeError – if message is
-
Utilities¶
ClientTimeout¶
-
class
aiohttp.ClientTimeout(*, total=None, connect=None, sock_connect, sock_read=None)¶ A data class for client timeout settings.
See Timeouts for usage examples.
-
connect¶ Total timeout for acquiring a connection from pool. The time consists connection establishment for a new connection or waiting for a free connection from a pool if pool connection limits are exceeded.
For pure socket connection establishment time use
sock_connect.float,Noneby default.
-
sock_connect¶ A timeout for connecting to a peer for a new connection, not given from a pool. See also
connect.float,Noneby default.
New in version 3.3.
-
RequestInfo¶
-
class
aiohttp.RequestInfo¶ A data class with request URL and headers from
ClientRequestobject, available asClientResponse.request_infoattribute.-
headers¶ HTTP headers for request,
multidict.CIMultiDictinstance.
-
BasicAuth¶
-
class
aiohttp.BasicAuth(login, password='', encoding='latin1')¶ HTTP basic authentication helper.
Parameters: Should be used for specifying authorization data in client API, e.g. auth parameter for
ClientSession.request().-
classmethod
decode(auth_header, encoding='latin1')¶ Decode HTTP basic authentication credentials.
Parameters: Returns: decoded authentication data,
BasicAuth.
-
classmethod
CookieJar¶
-
class
aiohttp.CookieJar(*, unsafe=False, loop=None)¶ The cookie jar instance is available as
ClientSession.cookie_jar.The jar contains
Morselitems for storing internal cookie data.API provides a count of saved cookies:
len(session.cookie_jar)
These cookies may be iterated over:
for cookie in session.cookie_jar: print(cookie.key) print(cookie["domain"])
The class implements
collections.abc.Iterable,collections.abc.Sizedandaiohttp.AbstractCookieJarinterfaces.Implements cookie storage adhering to RFC 6265.
Parameters: - unsafe (bool) – (optional) Whether to accept cookies from IPs.
- loop (bool) –
an event loop instance. See
aiohttp.abc.AbstractCookieJarDeprecated since version 2.0.
Update cookies returned by server in
Set-Cookieheader.Parameters: - cookies – a
collections.abc.Mapping(e.g.dict,SimpleCookie) or iterable of pairs with cookies returned by server’s response. - response_url (str) – URL of response,
Nonefor shared cookies. Regular cookies are coupled with server’s URL and are sent only to this server, shared ones are sent in every client request.
- cookies – a
Return jar’s cookies acceptable for URL and available in
Cookieheader for sending client requests for given URL.Parameters: response_url (str) – request’s URL for which cookies are asked. Returns: http.cookies.SimpleCookiewith filtered cookies for given URL.
-
save(file_path)¶ Write a pickled representation of cookies into the file at provided path.
Parameters: file_path – Path to file where cookies will be serialized, strorpathlib.Pathinstance.
-
load(file_path)¶ Load a pickled representation of cookies from the file at provided path.
Parameters: file_path – Path to file from where cookies will be imported, strorpathlib.Pathinstance.
-
class
aiohttp.DummyCookieJar(*, loop=None)¶ Dummy cookie jar which does not store cookies but ignores them.
Could be useful e.g. for web crawlers to iterate over Internet without blowing up with saved cookies information.
To install dummy cookie jar pass it into session instance:
jar = aiohttp.DummyCookieJar() session = aiohttp.ClientSession(cookie_jar=DummyCookieJar())
-
class
aiohttp.Fingerprint(digest)¶ Fingerprint helper for checking SSL certificates by SHA256 digest.
Parameters: digest (bytes) – SHA256 digest for certificate in DER-encoded binary form (see ssl.SSLSocket.getpeercert()).To check fingerprint pass the object into
ClientSession.get()call, e.g.:import hashlib with open(path_to_cert, 'rb') as f: digest = hashlib.sha256(f.read()).digest() await session.get(url, ssl=aiohttp.Fingerprint(digest))
New in version 3.0.
Client exceptions¶
Exception hierarchy has been significantly modified in version
2.0. aiohttp defines only exceptions that covers connection handling
and server response misbehaviors. For developer specific mistakes,
aiohttp uses python standard exceptions like ValueError or
TypeError.
Reading a response content may raise a ClientPayloadError
exception. This exception indicates errors specific to the payload
encoding. Such as invalid compressed data, malformed chunked-encoded
chunks or not enough data that satisfy the content-length header.
All exceptions are available as members of aiohttp module.
-
exception
aiohttp.ClientError¶ Base class for all client specific exceptions.
Derived from
Exception
-
class
aiohttp.ClientPayloadError¶ This exception can only be raised while reading the response payload if one of these errors occurs:
- invalid compression
- malformed chunked encoding
- not enough data that satisfy
Content-LengthHTTP header.
Derived from
ClientError
-
exception
aiohttp.InvalidURL¶ URL used for fetching is malformed, e.g. it does not contain host part.
Derived from
ClientErrorandValueError
-
class
aiohttp.ContentDisposition¶ Represent Content-Disposition header
-
value¶
A
strinstance. Value of Content-Disposition header itself, e.g.attachment.-
filename¶
A
strinstance. Content filename extracted from parameters. May beNone.-
parameters¶
Read-only mapping contains all parameters.
-
Response errors¶
-
exception
aiohttp.ClientResponseError¶ These exceptions could happen after we get response from server.
Derived from
ClientError-
request_info¶ Instance of
RequestInfoobject, contains information about request.
-
headers¶ Headers in response, a list of pairs.
-
history¶ History from failed response, if available, else empty tuple.
A
tupleofClientResponseobjects used for handle redirection responses.
-
-
class
aiohttp.WSServerHandshakeError¶ Web socket server response error.
Derived from
ClientResponseError
-
class
aiohttp.WSServerHandshakeError Web socket server response error.
Derived from
ClientResponseError
-
class
aiohttp.ContentTypeError¶ Invalid content type.
Derived from
ClientResponseErrorNew in version 2.3.
-
class
aiohttp.TooManyRedirects¶ Client was redirected too many times.
Maximum number of redirects can be configured by using parameter
max_redirectsinrequest.Derived from
ClientResponseErrorNew in version 3.2.
Connection errors¶
-
class
aiohttp.ClientConnectionError¶ These exceptions related to low-level connection problems.
Derived from
ClientError
-
class
aiohttp.ClientOSError¶ Subset of connection errors that are initiated by an
OSErrorexception.Derived from
ClientConnectionErrorandOSError
-
class
aiohttp.ClientConnectorError¶ Connector related exceptions.
Derived from
ClientOSError
-
class
aiohttp.ClientProxyConnectionError¶ Derived from
ClientConnectorError
-
class
aiohttp.ServerConnectionError¶ Derived from
ClientConnectionError
-
class
aiohttp.ClientSSLError¶ Derived from
ClientConnectorError
-
class
aiohttp.ClientConnectorSSLError¶ Response ssl error.
Derived from
ClientSSLErrorandssl.SSLError
-
class
aiohttp.ClientConnectorCertificateError¶ Response certificate error.
Derived from
ClientSSLErrorandssl.CertificateError
-
class
aiohttp.ServerDisconnectedError¶ Server disconnected.
Derived from
ServerDisconnectionError-
message¶ Partially parsed HTTP message (optional).
-
-
class
aiohttp.ServerTimeoutError¶ Server operation timeout: read timeout, etc.
Derived from
ServerConnectionErrorandasyncio.TimeoutError
-
class
aiohttp.ServerFingerprintMismatch¶ Server fingerprint mismatch.
Derived from
ServerConnectionError