All public names from submodules client, connector, errors, parsers, protocol, server, utils, websocket, worker and wsgi are exported into aiohttp namespace.
HTTP Client for asyncio.
Constructs and sends a request. Returns response object.
Parameters: |
|
---|
Usage:
>>> import aiohttp
>>> resp = yield from aiohttp.request('GET', 'http://python.org/')
>>> resp
<ClientResponse(python.org/) [200]>
>>> data = yield from resp.read()
Bases: builtins.object
Allow to use multiple hosts with same path. And automatically mark failed hosts.
Bases: builtins.object
Base connector class.
Parameters: |
---|
Update shared cookies.
Bases: aiohttp.connector.BaseConnector
TCP connector.
Parameters: |
|
---|
Bases: aiohttp.connector.TCPConnector
Http Proxy connector.
Parameters: |
|
---|
Usage:
>>> conn = ProxyConnector(proxy="http://some.proxy.com")
>>> resp = yield from request('GET', 'http://python.org', connector=conn)
Bases: aiohttp.connector.BaseConnector
Unix socket connector.
Parameters: |
|
---|
Usage:
>>> conn = UnixConnector(path='/path/to/socket')
>>> resp = yield from request('GET', 'http://python.org', connector=conn)
Alias of TCPConnector.
Note
Keeped for backward compatibility. May be deprecated in future.
alias of TCPConnector
Alias of UnixConnector.
Note
Keeped for backward compatibility. May be deprecated in future.
alias of UnixConnector
http related errors.
Bases: builtins.Exception
Base http exception class.
Bases: aiohttp.errors.HttpException
Http error.
Shortcut for raising http errors with custom code, message and headers.
Parameters: |
---|
Bases: aiohttp.errors.HttpException
Bases: aiohttp.errors.HttpException
Bases: aiohttp.errors.ConnectionError
OSError error.
Bases: aiohttp.errors.ConnectionError
BadStatusLine error.
Bases: concurrent.futures._base.Error
The operation exceeded the given deadline.
Bases: aiohttp.errors.ClientConnectionError
Proxy connection error.
Raised in aiohttp.connector.ProxyConnector if connection to proxy can not be established.
Bases: aiohttp.errors.HttpErrorException
Http proxy error.
Raised in aiohttp.connector.ProxyConnector if proxy responds with status other than 200 OK on CONNECT request.
Various helper functions
Bases: aiohttp.helpers.BasicAuth
Http basic authentication helper.
Parameters: |
---|
Bases: builtins.object
Helper class for multipart/form-data and application/x-www-form-urlencoded body generation.
Parses a MIME type into its components.
Parameters: | mimetype (str) – MIME type |
---|---|
Returns: | 4 element tuple for MIME type, subtype, suffix and parameters |
Return type: | tuple |
Example:
>>> parse_mimetype('text/html; charset=utf-8')
('text', 'html', '', {'charset': 'utf-8'})
Parser is a generator function (NOT coroutine).
Parser receives data with generator’s send() method and sends data to destination DataQueue. Parser receives ParserBuffer and DataQueue objects as a parameters of the parser call, all subsequent send() calls should send bytes objects. Parser sends parsed term to destination buffer with DataQueue.feed_data() method. DataQueue object should implement two methods. feed_data() - parser uses this method to send parsed protocol data. feed_eof() - parser uses this method for indication of end of parsing stream. To indicate end of incoming data stream EofStream exception should be sent into parser. Parser could throw exceptions.
There are three stages:
Data flow chain:
Application creates StreamParser object for storing incoming data.
StreamParser creates ParserBuffer as internal data buffer.
Application create parser and set it into stream buffer:
parser = HttpRequestParser() data_queue = stream.set_parser(parser)
At this stage StreamParser creates DataQueue object and passes it and internal buffer into parser as an arguments.
- def set_parser(self, parser):
output = DataQueue() self.p = parser(output, self._input) return output
Application waits data on output.read()
- while True:
msg = yield form output.read() ...
Data flow:
- asyncio’s transport reads data from socket and sends data to protocol with data_received() call.
- Protocol sends data to StreamParser with feed_data() call.
- StreamParser sends data into parser with generator’s send() method.
- Parser processes incoming data and sends parsed data to DataQueue with feed_data()
- Application received parsed data from DataQueue.read()
Eof:
- StreamParser receives eof with feed_eof() call.
- StreamParser throws EofStream exception into parser.
- Then it unsets parser.
Bases: builtins.Exception
eof stream indication.
Bases: asyncio.streams.StreamReader
StreamParser manages incoming bytes stream and protocol parsers.
StreamParser uses ParserBuffer as internal buffer.
set_parser() sets current parser, it creates DataQueue object and sends ParserBuffer and DataQueue into parser generator.
unset_parser() sends EofStream into parser and then removes it.
Bases: asyncio.streams.FlowControlMixin, asyncio.protocols.Protocol
Helper class to adapt between Protocol and StreamReader.
Bases: builtins.bytearray
ParserBuffer is a bytearray extension.
ParserBuffer provides helper methods for parsers.
Http related parsers and protocol.
Bases: builtins.object
HttpMessage allows to write headers and payload to a stream.
For example, lets say we want to read file then compress it with deflate compression and then send it with chunked transfer encoding, code may look like this:
>>> response = aiohttp.Response(transport, 200)
We have to use deflate compression first:
>>> response.add_compression_filter('deflate')
Then we want to split output stream into chunks of 1024 bytes size:
>>> response.add_chunking_filter(1024)
We can add headers to response with add_headers() method. add_headers() does not send data to transport, send_headers() sends request/response line and then sends headers:
>>> response.add_headers(
... ('Content-Disposition', 'attachment; filename="..."'))
>>> response.send_headers()
Now we can use chunked writer to write stream to a network stream. First call to write() method sends response status line and headers, add_header() and add_headers() method unavailable at this stage:
>>> with open('...', 'rb') as f:
... chunk = fp.read(8196)
... while chunk:
... response.write(chunk)
... chunk = fp.read(8196)
>>> response.write_eof()
Compress incoming stream with deflate or gzip encoding.
Analyze headers. Calculate content length, removes hop headers, etc.
Writes chunk of data to a stream by using different writers.
writer uses filter to modify chunk of data. write_eof() indicates end of stream. writer can’t be used after write_eof() method being called. write() return drain future.
Bases: aiohttp.protocol.HttpMessage
Bases: aiohttp.protocol.HttpMessage
Create http response message.
Transport is a socket stream transport. status is a response status code, status has to be integer value. http_version is a tuple that represents http version, (1, 0) stands for HTTP/1.0 and (1, 1) is for HTTP/1.1
Bases: builtins.tuple
HttpVersion(major, minor)
Alias for field number 0
Alias for field number 1
Bases: builtins.tuple
RawRequestMessage(method, path, version, headers, should_close, compression)
Alias for field number 5
Alias for field number 3
Alias for field number 0
Alias for field number 1
Alias for field number 4
Alias for field number 2
Bases: builtins.tuple
RawResponseMessage(version, code, reason, headers, should_close, compression)
Alias for field number 1
Alias for field number 5
Alias for field number 3
Alias for field number 2
Alias for field number 4
Alias for field number 0
Bases: builtins.object
Waits for ‘HTTP’ prefix (non destructive)
Bases: aiohttp.protocol.HttpParser
Read request status line. Exception errors.BadStatusLine could be raised in case of any errors in status line. Returns RawRequestMessage.
Bases: aiohttp.protocol.HttpParser
Read response status line and headers.
BadStatusLine could be raised in case of any errors in status line. Returns RawResponseMessage
simple http server.
Bases: aiohttp.parsers.StreamProtocol
Simple http protocol implementation.
ServerHttpProtocol handles incoming http request. It reads request line, request headers and request payload and calls handle_request() method. By default it always returns with 404 response.
ServerHttpProtocol handles errors in incoming request, like bad status line, bad headers or incomplete payload. If any error occurs, connection gets closed.
Parameters: |
|
---|
Worker process is about to exit, we need cleanup everything and stop accepting requests. It is especially important for keep-alive connections.
Handle errors.
Returns http response with specific status code. Logs additional information. It always closes current connection.
Handle a single http request.
Subclass should override this method. By default it always returns 404 response.
Parameters: |
|
---|
Start processing of incoming requests.
It reads request line, request headers and request payload, then calls handle_request() method. Subclass has to override handle_request(). start() handles various exceptions in request or response handling. Connection is being closed always unless keep_alive(True) specified.
Bases: asyncio.streams.StreamReader
Bases: builtins.object
DataQueue is a general-purpose blocking queue with one reader.
Bases: aiohttp.streams.DataQueue
Like a DataQueue, but for binary chunked data transfer.
Bases: aiohttp.streams.StreamReader
Bases: aiohttp.streams.DataQueue
FlowControlDataQueue resumes and pauses an underlying stream.
It is a destination for parsed data.
Bases: aiohttp.streams.FlowControlDataQueue, aiohttp.streams.ChunksQueue
FlowControlChunksQueue resumes and pauses an underlying stream.
WebSocket protocol versions 13 and 8.
Prepare WebSocket handshake. It return http response code, response headers, websocket parser, websocket writer. It does not perform any IO.
protocols is a sequence of known protocols. On successful handshake, the returned response headers contain the first protocol in this list which the server also knows.
wsgi server.
Bases: aiohttp.server.ServerHttpProtocol
HTTP Server that implements the Python WSGI protocol.
It uses ‘wsgi.async’ of ‘True’. ‘wsgi.input’ can behave differently depends on ‘readpayload’ constructor parameter. If readpayload is set to True, wsgi server reads all incoming data into BytesIO object and sends it as ‘wsgi.input’ environ var. If readpayload is set to false ‘wsgi.input’ is a StreamReader and application should read incoming data with “yield from environ[‘wsgi.input’].read()”. It defaults to False.