Server Reference

Request and Base Request

The Request object contains all the information about an incoming HTTP request.

BaseRequest is used for Low-Level Servers (which have no applications, routers, signals and middlewares) and Request has an application and match info attributes.

A BaseRequest/Request are dict-like objects, allowing them to be used for sharing data among Middlewares and Signals handlers.

class aiohttp.web.BaseRequest[source]
version

HTTP version of request, Read-only property.

Returns aiohttp.protocol.HttpVersion instance.

method

HTTP method, read-only property.

The value is upper-cased str like "GET", "POST", "PUT" etc.

url

A URL instance with absolute URL to resource (scheme, host and port are included).

Note

In case of malformed request (e.g. without "HOST" HTTP header) the absolute url may be unavailable.

rel_url

A URL instance with relative URL to resource (contains path, query and fragment parts only, scheme, host and port are excluded).

The property is equal to .url.relative() but is always present.

See also

A note from url.

scheme

A string representing the scheme of the request.

The scheme is 'https' if transport for request handling is SSL, if secure_proxy_ssl_header is matching (deprecated), if the proto portion of a Forward header is present and contains https, or if an X-Forwarded-Proto header is present and contains https.

'http' otherwise.

Read-only str property.

Deprecated since version 1.1: Use url (request.url.scheme) instead.

secure

Shorthand for request.url.scheme == 'https'

Read-only bool property.

See also

scheme

forwarded

A tuple containing all parsed Forwarded header(s).

Makes an effort to parse Forwarded headers as specified by RFC 7239:

  • It adds one (immutable) dictionary per Forwarded field-value, i.e. per proxy. The element corresponds to the data in the Forwarded field-value added by the first proxy encountered by the client. Each subsequent item corresponds to those added by later proxies.
  • It checks that every value has valid syntax in general as specified in RFC 7239#section-4: either a token or a quoted-string.
  • It un-escapes quoted-pairs.
  • It does NOT validate ‘by’ and ‘for’ contents as specified in RFC 7239#section-6.
  • It does NOT validate host contents (Host ABNF).
  • It does NOT validate proto contents for valid URI scheme names.

Returns a tuple containing one or more MappingProxy objects

See also

scheme

See also

host

host

Host name of the request.

Host name is resolved through the following headers, in this order:

  • Forwarded
  • X-Forwarded-Host
  • Host

Returns str, or None if no host name is found in the headers.

path_qs

The URL including PATH_INFO and the query string. e.g., /app/blog?id=10

Read-only str property.

path

The URL including PATH INFO without the host or scheme. e.g., /app/blog. The path is URL-unquoted. For raw path info see raw_path.

Read-only str property.

raw_path

The URL including raw PATH INFO without the host or scheme. Warning, the path may be quoted and may contains non valid URL characters, e.g. /my%2Fpath%7Cwith%21some%25strange%24characters.

For unquoted version please take a look on path.

Read-only str property.

query

A multidict with all the variables in the query string.

Read-only MultiDictProxy lazy property.

query_string

The query string in the URL, e.g., id=10

Read-only str property.

headers

A case-insensitive multidict proxy with all headers.

Read-only CIMultiDictProxy property.

raw_headers

HTTP headers of response as unconverted bytes, a sequence of (key, value) pairs.

keep_alive

True if keep-alive connection enabled by HTTP client and protocol version supports it, otherwise False.

Read-only bool property.

transport

An transport used to process request, Read-only property.

The property can be used, for example, for getting IP address of client’s peer:

peername = request.transport.get_extra_info('peername')
if peername is not None:
    host, port = peername
cookies

A multidict of all request’s cookies.

Read-only MultiDictProxy lazy property.

content

A StreamReader instance, input stream for reading request’s BODY.

Read-only property.

has_body

Return True if request has HTTP BODY, False otherwise.

Read-only bool property.

New in version 0.16.

content_type

Read-only property with content part of Content-Type header.

Returns str like 'text/html'

Note

Returns value is 'application/octet-stream' if no Content-Type header present in HTTP headers according to RFC 2616

charset

Read-only property that specifies the encoding for the request’s BODY.

The value is parsed from the Content-Type HTTP header.

Returns str like 'utf-8' or None if Content-Type has no charset information.

content_length

Read-only property that returns length of the request’s BODY.

The value is parsed from the Content-Length HTTP header.

Returns int or None if Content-Length is absent.

http_range

Read-only property that returns information about Range HTTP header.

Returns a slice where .start is left inclusive bound, .stop is right exclusive bound and .step is 1.

The property might be used in two manners:

  1. Attribute-access style (example assumes that both left and right borders are set, the real logic for case of open bounds is more complex):

    rng = request.http_range
    with open(filename, 'rb') as f:
        f.seek(rng.start)
        return f.read(rng.stop-rng.start)
    
  2. Slice-style:

    return buffer[request.http_range]
    

New in version 1.2.

if_modified_since

Read-only property that returns the date specified in the If-Modified-Since header.

Returns datetime.datetime or None if If-Modified-Since header is absent or is not a valid HTTP date.

clone(*, method=…, rel_url=…, headers=…)[source]

Clone itself with replacement some attributes.

Creates and returns a new instance of Request object. If no parameters are given, an exact copy is returned. If a parameter is not passed, it will reuse the one from the current request object.

Parameters:
  • method (str) – http method
  • rel_url – url to use, str or URL
  • headersCIMultidict or compatible headers container.
Returns:

a cloned Request instance.

coroutine read()[source]

Read request body, returns bytes object with body content.

Note

The method does store read data internally, subsequent read() call will return the same value.

coroutine text()[source]

Read request body, decode it using charset encoding or UTF-8 if no encoding was specified in MIME-type.

Returns str with body content.

Note

The method does store read data internally, subsequent text() call will return the same value.

coroutine json(*, loads=json.loads)[source]

Read request body decoded as json.

The method is just a boilerplate coroutine implemented as:

async def json(self, *, loads=json.loads):
    body = await self.text()
    return loads(body)
Parameters:loads (callable) – any callable that accepts str and returns dict with parsed JSON (json.loads() by default).

Note

The method does store read data internally, subsequent json() call will return the same value.

coroutine multipart(*, reader=aiohttp.multipart.MultipartReader)[source]

Returns aiohttp.multipart.MultipartReader which processes incoming multipart request.

The method is just a boilerplate coroutine implemented as:

async def multipart(self, *, reader=aiohttp.multipart.MultipartReader):
    return reader(self.headers, self._payload)

This method is a coroutine for consistency with the else reader methods.

Warning

The method does not store read data internally. That means once you exhausts multipart reader, you cannot get the request payload one more time.

coroutine post()[source]

A coroutine that reads POST parameters from request body.

Returns MultiDictProxy instance filled with parsed data.

If method is not POST, PUT, PATCH, TRACE or DELETE or content_type is not empty or application/x-www-form-urlencoded or multipart/form-data returns empty multidict.

Note

The method does store read data internally, subsequent post() call will return the same value.

coroutine release()[source]

Release request.

Eat unread part of HTTP BODY if present.

Note

User code may never call release(), all required work will be processed by aiohttp.web internal machinery.

class aiohttp.web.Request[source]

An request used for receiving request’s information by web handler.

Every handler accepts a request instance as the first positional parameter.

The class in derived from BaseRequest, shares all parent’s attributes and methods but has a couple of additional properties:

match_info

Read-only property with AbstractMatchInfo instance for result of route resolving.

Note

Exact type of property depends on used router. If app.router is UrlDispatcher the property contains UrlMappingMatchInfo instance.

app

An Application instance used to call request handler, Read-only property.

Note

You should never create the Request instance manually – aiohttp.web does it for you. But clone() may be used for cloning modified request copy with changed path, method etc.

Response classes

For now, aiohttp.web has three classes for the HTTP response: StreamResponse, Response and FileResponse.

Usually you need to use the second one. StreamResponse is intended for streaming data, while Response contains HTTP BODY as an attribute and sends own content as single piece with the correct Content-Length HTTP header.

For sake of design decisions Response is derived from StreamResponse parent class.

The response supports keep-alive handling out-of-the-box if request supports it.

You can disable keep-alive by force_close() though.

The common case for sending an answer from web-handler is returning a Response instance:

def handler(request):
    return Response("All right!")

StreamResponse

class aiohttp.web.StreamResponse(*, status=200, reason=None)[source]

The base class for the HTTP response handling.

Contains methods for setting HTTP response headers, cookies, response status code, writing HTTP response BODY and so on.

The most important thing you should know about response — it is Finite State Machine.

That means you can do any manipulations with headers, cookies and status code only before prepare() coroutine is called.

Once you call prepare() any change of the HTTP header part will raise RuntimeError exception.

Any write() call after write_eof() is also forbidden.

Parameters:
  • status (int) – HTTP status code, 200 by default.
  • reason (str) – HTTP reason. If param is None reason will be calculated basing on status parameter. Otherwise pass str with arbitrary status explanation..
prepared

Read-only bool property, True if prepare() has been called, False otherwise.

New in version 0.18.

task

A task that serves HTTP request handling.

May be useful for graceful shutdown of long-running requests (streaming, long polling or web-socket).

New in version 1.2.

status

Read-only property for HTTP response status code, int.

200 (OK) by default.

reason

Read-only property for HTTP response reason, str.

set_status(status, reason=None)[source]

Set status and reason.

reason value is auto calculated if not specified (None).

keep_alive

Read-only property, copy of Request.keep_alive by default.

Can be switched to False by force_close() call.

force_close()[source]

Disable keep_alive for connection. There are no ways to enable it back.

compression

Read-only bool property, True if compression is enabled.

False by default.

enable_compression(force=None)[source]

Enable compression.

When force is unset compression encoding is selected based on the request’s Accept-Encoding header.

Accept-Encoding is not checked if force is set to a ContentCoding.

See also

compression

chunked

Read-only property, indicates if chunked encoding is on.

Can be enabled by enable_chunked_encoding() call.

enable_chunked_encoding()[source]

Enables chunked encoding for response. There are no ways to disable it back. With enabled chunked encoding each write() operation encoded in separate chunk.

Warning

chunked encoding can be enabled for HTTP/1.1 only.

Setting up both content_length and chunked encoding is mutually exclusive.

See also

chunked

headers

CIMultiiDct instance for outgoing HTTP headers.

cookies

An instance of http.cookies.SimpleCookie for outgoing cookies.

Warning

Direct setting up Set-Cookie header may be overwritten by explicit calls to cookie manipulation.

We are encourage using of cookies and set_cookie(), del_cookie() for cookie manipulations.

Convenient way for setting cookies, allows to specify some additional properties like max_age in a single call.

Parameters:
  • name (str) – cookie name
  • value (str) – cookie value (will be converted to str if value has another type).
  • expires – expiration date (optional)
  • domain (str) – cookie domain (optional)
  • max_age (int) – defines the lifetime of the cookie, in seconds. The delta-seconds value is a decimal non- negative integer. After delta-seconds seconds elapse, the client should discard the cookie. A value of zero means the cookie should be discarded immediately. (optional)
  • path (str) – specifies the subset of URLs to which this cookie applies. (optional, '/' by default)
  • secure (bool) – attribute (with no value) directs the user agent to use only (unspecified) secure means to contact the origin server whenever it sends back this cookie. The user agent (possibly under the user’s control) may determine what level of security it considers appropriate for “secure” cookies. The secure should be considered security advice from the server to the user agent, indicating that it is in the session’s interest to protect the cookie contents. (optional)
  • httponly (bool) – True if the cookie HTTP only (optional)
  • version (int) – a decimal integer, identifies to which version of the state management specification the cookie conforms. (Optional, version=1 by default)

Warning

In HTTP version 1.1, expires was deprecated and replaced with the easier-to-use max-age, but Internet Explorer (IE6, IE7, and IE8) does not support max-age.

Deletes cookie.

Parameters:
  • name (str) – cookie name
  • domain (str) – optional cookie domain
  • path (str) – optional cookie path, '/' by default

Changed in version 1.0: Fixed cookie expiration support for Internet Explorer (version less than 11).

content_length

Content-Length for outgoing response.

content_type

Content part of Content-Type for outgoing response.

charset

Charset aka encoding part of Content-Type for outgoing response.

The value converted to lower-case on attribute assigning.

last_modified

Last-Modified header for outgoing response.

This property accepts raw str values, datetime.datetime objects, Unix timestamps specified as an int or a float object, and the value None to unset the header.

tcp_cork

TCP_CORK (linux) or TCP_NOPUSH (FreeBSD and MacOSX) is applied to underlying transport if the property is True.

Use set_tcp_cork() to assign new value to the property.

Default value is False.

set_tcp_cork(value)[source]

Set tcp_cork property to value.

Clear tcp_nodelay if value is True.

tcp_nodelay

TCP_NODELAY is applied to underlying transport if the property is True.

Use set_tcp_nodelay() to assign new value to the property.

Default value is True.

set_tcp_nodelay(value)[source]

Set tcp_nodelay property to value.

Clear tcp_cork if value is True.

coroutine prepare(request)[source]
Parameters:request (aiohttp.web.Request) – HTTP request object, that the response answers.

Send HTTP header. You should not change any header data after calling this method.

The coroutine calls on_response_prepare signal handlers.

New in version 0.18.

write(data)[source]

Send byte-ish data as the part of response BODY.

prepare() must be called before.

Raises TypeError if data is not bytes, bytearray or memoryview instance.

Raises RuntimeError if prepare() has not been called.

Raises RuntimeError if write_eof() has been called.

coroutine drain()[source]

A coroutine to let the write buffer of the underlying transport a chance to be flushed.

The intended use is to write:

resp.write(data)
await resp.drain()

Yielding from drain() gives the opportunity for the loop to schedule the write operation and flush the buffer. It should especially be used when a possibly large amount of data is written to the transport, and the coroutine does not yield-from between calls to write().

coroutine write_eof()[source]

A coroutine may be called as a mark of the HTTP response processing finish.

Internal machinery will call this method at the end of the request processing if needed.

After write_eof() call any manipulations with the response object are forbidden.

Response

class aiohttp.web.Response(*, status=200, headers=None, content_type=None, charset=None, body=None, text=None)[source]

The most usable response class, inherited from StreamResponse.

Accepts body argument for setting the HTTP response BODY.

The actual body sending happens in overridden write_eof().

Parameters:
  • body (bytes) – response’s BODY
  • status (int) – HTTP status code, 200 OK by default.
  • headers (collections.abc.Mapping) – HTTP headers that should be added to response’s ones.
  • text (str) – response’s BODY
  • content_type (str) – response’s content type. 'text/plain' if text is passed also, 'application/octet-stream' otherwise.
  • charset (str) – response’s charset. 'utf-8' if text is passed also, None otherwise.
body

Read-write attribute for storing response’s content aka BODY, bytes.

Setting body also recalculates content_length value.

Resetting body (assigning None) sets content_length to None too, dropping Content-Length HTTP header.

text

Read-write attribute for storing response’s content, represented as string, str.

Setting text also recalculates content_length value and body value

Resetting text (assigning None) sets content_length to None too, dropping Content-Length HTTP header.

WebSocketResponse

class aiohttp.web.WebSocketResponse(*, timeout=10.0, receive_timeout=None, autoclose=True, autoping=True, heartbeat=None, protocols=())[source]

Class for handling server-side websockets, inherited from StreamResponse.

After starting (by prepare() call) the response you cannot use write() method but should to communicate with websocket client by send_str(), receive() and others.

New in version 1.3.0.

To enable back-pressure from slow websocket clients treat methods ping(), pong(), send_str(), send_bytes(), send_json() as coroutines. By default write buffer size is set to 64k.

Parameters:autoping (bool) – Automatically send PONG on PING message from client, and handle PONG responses from client. Note that server does not send PING requests, you need to do this explicitly using ping() method.

New in version 1.3.0.

Parameters:
  • heartbeat (float) – Send ping message every heartbeat seconds and wait pong response, close connection if pong response is not received.
  • receive_timeout (float) – Timeout value for receive operations. Default value is None (no timeout for receive operation)

New in version 0.19: The class supports async for statement for iterating over incoming messages:

ws = web.WebSocketResponse()
await ws.prepare(request)

async for msg in ws:
    print(msg.data)
coroutine prepare(request)[source]

Starts websocket. After the call you can use websocket methods.

Parameters:request (aiohttp.web.Request) – HTTP request object, that the response answers.
Raises:HTTPException – if websocket handshake has failed.

New in version 0.18.

can_prepare(request)[source]

Performs checks for request data to figure out if websocket can be started on the request.

If can_prepare() call is success then prepare() will success too.

Parameters:request (aiohttp.web.Request) – HTTP request object, that the response answers.
Returns:WebSocketReady instance.

WebSocketReady.ok is True on success, WebSocketReady.protocol is websocket subprotocol which is passed by client and accepted by server (one of protocols sequence from WebSocketResponse ctor). WebSocketReady.protocol may be None if client and server subprotocols are not overlapping.

Note

The method never raises exception.

closed

Read-only property, True if connection has been closed or in process of closing. CLOSE message has been received from peer.

close_code

Read-only property, close code from peer. It is set to None on opened connection.

protocol

Websocket subprotocol chosen after start() call.

May be None if server and client protocols are not overlapping.

exception()[source]

Returns last occurred exception or None.

ping(message=b”)[source]

Send PING to peer.

Parameters:message – optional payload of ping message, str (converted to UTF-8 encoded bytes) or bytes.
Raises:RuntimeError – if connections is not started or closing.
pong(message=b”)[source]

Send unsolicited PONG to peer.

Parameters:message – optional payload of pong message, str (converted to UTF-8 encoded bytes) or bytes.
Raises:RuntimeError – if connections is not started or closing.
coroutine send_str(data)[source]

Send data to peer as TEXT message.

Parameters:

data (str) – data to send.

Raises:
coroutine send_bytes(data)[source]

Send data to peer as BINARY message.

Parameters:

data – data to send.

Raises:
coroutine send_json(data, *, dumps=json.loads)[source]

Send data to peer as JSON string.

Parameters:
Raises:
coroutine close(*, code=1000, message=b”)[source]

A coroutine that initiates closing handshake by sending CLOSE message.

It is save to call close() from different task.

Parameters:
  • code (int) – closing code
  • message – optional payload of pong message, str (converted to UTF-8 encoded bytes) or bytes.
Raises:

RuntimeError – if connection is not started

coroutine receive(timeout=None)[source]

A coroutine that waits upcoming data message from peer and returns it.

The coroutine implicitly handles PING, PONG and CLOSE without returning the message.

It process ping-pong game and performs closing handshake internally.

Note

Can only be called by the request handling task.

Parameters:timeout – timeout for receive operation. timeout value overrides response`s receive_timeout attribute.
Returns:WSMessage
Raises:RuntimeError – if connection is not started
coroutine receive_str(*, timeout=None)[source]

A coroutine that calls receive() but also asserts the message type is TEXT.

Note

Can only be called by the request handling task.

Parameters:timeout – timeout for receive operation. timeout value overrides response`s receive_timeout attribute.
Return str:peer’s message content.
Raises:TypeError – if message is BINARY.
coroutine receive_bytes(*, timeout=None)[source]

A coroutine that calls receive() but also asserts the message type is BINARY.

Note

Can only be called by the request handling task.

Parameters:timeout – timeout for receive operation. timeout value overrides response`s receive_timeout attribute.
Return bytes:peer’s message content.
Raises:TypeError – if message is TEXT.
coroutine receive_json(*, loads=json.loads, timeout=None)[source]

A coroutine that calls receive_str() and loads the JSON string to a Python dict.

Note

Can only be called by the request handling task.

Parameters:loads (callable) – any callable that accepts str and returns dict with parsed JSON (json.loads() by default).
Parameters:timeout
timeout for receive operation.
timeout value overrides response`s receive_timeout attribute.
return dict:loaded JSON content
raise TypeError:
 if message is BINARY.
raise ValueError:
 if message is not valid JSON.

New in version 0.22.

WebSocketReady

class aiohttp.web.WebSocketReady[source]

A named tuple for returning result from WebSocketResponse.can_prepare().

Has bool check implemented, e.g.:

if not await ws.can_prepare(...):
    cannot_start_websocket()
ok

True if websocket connection can be established, False otherwise.

protocol

str represented selected websocket sub-protocol.

json_response

aiohttp.web.json_response([data, ]*, text=None, body=None, status=200, reason=None, headers=None, content_type=’application/json’, dumps=json.dumps)[source]

Return Response with predefined 'application/json' content type and data encoded by dumps parameter (json.dumps() by default).

Application and Router

Application

Application is a synonym for web-server.

To get fully working example, you have to make application, register supported urls in router and create a server socket with Server as a protocol factory. Server could be constructed with Application.make_handler().

Application contains a router instance and a list of callbacks that will be called during application finishing.

Application is a dict-like object, so you can use it for sharing data globally by storing arbitrary properties for later access from a handler via the Request.app property:

app = Application()
app['database'] = await aiopg.create_engine(**db_config)

async def handler(request):
    with (await request.app['database']) as conn:
        conn.execute("DELETE * FROM table")

Although Application is a dict-like object, it can’t be duplicated like one using Application.copy().

class aiohttp.web.Application(*, router=None, logger=<default>, middlewares=(), debug=False, **kwargs)[source]

The class inherits dict.

Parameters:
  • routeraiohttp.abc.AbstractRouter instance, the system creates UrlDispatcher by default if router is None.
  • logger

    logging.Logger instance for storing application logs.

    By default the value is logging.getLogger("aiohttp.web")

  • middlewareslist of middleware factories, see Middlewares for details.
  • debug – Switches debug mode.
  • loop – loop parameter is deprecated. loop is get set during freeze stage.
router

Read-only property that returns router instance.

logger

logging.Logger instance for storing application logs.

loop

event loop used for processing HTTP requests.

debug

Boolean value indicating whether the debug mode is turned on or off.

on_response_prepare

A Signal that is fired at the beginning of StreamResponse.prepare() with parameters request and response. It can be used, for example, to add custom headers to each response before sending.

Signal handlers should have the following signature:

async def on_prepare(request, response):
    pass
on_startup

A Signal that is fired on application start-up.

Subscribers may use the signal to run background tasks in the event loop along with the application’s request handler just after the application start-up.

Signal handlers should have the following signature:

async def on_startup(app):
    pass

See also

Background tasks.

on_shutdown

A Signal that is fired on application shutdown.

Subscribers may use the signal for gracefully closing long running connections, e.g. websockets and data streaming.

Signal handlers should have the following signature:

async def on_shutdown(app):
    pass

It’s up to end user to figure out which web-handlers are still alive and how to finish them properly.

We suggest keeping a list of long running handlers in Application dictionary.

on_cleanup

A Signal that is fired on application cleanup.

Subscribers may use the signal for gracefully closing connections to database server etc.

Signal handlers should have the following signature:

async def on_cleanup(app):
    pass
make_handler(loop=None, **kwargs)[source]

Creates HTTP protocol factory for handling requests.

Parameters:
  • loop

    event loop used for processing HTTP requests.

    If param is None asyncio.get_event_loop() used for getting default event loop.

  • secure_proxy_ssl_header (tuple) –

    Default: None.

    Deprecated since version 2.1: See request.url.scheme for built-in resolution of the current scheme using the standard and de-facto standard headers.

  • tcp_keepalive (bool) – Enable TCP Keep-Alive. Default: True.
  • keepalive_timeout (int) – Number of seconds before closing Keep-Alive connection. Default: 75 seconds (NGINX’s default value).
  • slow_request_timeout – Slow request timeout. Default: 0.
  • logger – Custom logger object. Default: aiohttp.log.server_logger.
  • access_log – Custom logging object. Default: aiohttp.log.access_logger.
  • access_log_format (str) – Access log format string. Default: helpers.AccessLogger.LOG_FORMAT.
  • debug (bool) –

    Switches debug mode. Default: False.

    Deprecated since version 1.0: The usage of debug parameter in Application.make_handler() is deprecated in favor of Application.debug. The Application’s debug mode setting should be used as a single point to setup a debug mode.

  • max_line_size (int) – Optional maximum header line size. Default: 8190.
  • max_headers (int) – Optional maximum header size. Default: 32768.
  • max_field_size (int) – Optional maximum header field size. Default: 8190.
  • lingering_time (float) – maximum time during which the server reads and ignore additional data coming from the client when lingering close is on. Use 0 for disabling lingering on server channel closing.
  • lingering_timeout (float) – maximum waiting time for more client data to arrive when lingering close is in effect

You should pass result of the method as protocol_factory to create_server(), e.g.:

loop = asyncio.get_event_loop()

app = Application(loop=loop)

# setup route table
# app.router.add_route(...)

await loop.create_server(app.make_handler(),
                         '0.0.0.0', 8080)
coroutine startup()[source]

A coroutine that will be called along with the application’s request handler.

The purpose of the method is calling on_startup signal handlers.

coroutine shutdown()[source]

A coroutine that should be called on server stopping but before cleanup().

The purpose of the method is calling on_shutdown signal handlers.

coroutine cleanup()[source]

A coroutine that should be called on server stopping but after shutdown().

The purpose of the method is calling on_cleanup signal handlers.

Note

Application object has router attribute but has no add_route() method. The reason is: we want to support different router implementations (even maybe not url-matching based but traversal ones).

For sake of that fact we have very trivial ABC for AbstractRouter: it should have only AbstractRouter.resolve() coroutine.

No methods for adding routes or route reversing (getting URL by route name). All those are router implementation details (but, sure, you need to deal with that methods after choosing the router for your application).

Server

A protocol factory compatible with create_server().

class aiohttp.web.Server[source]

The class is responsible for creating HTTP protocol objects that can handle HTTP connections.

Server.connections

List of all currently opened connections.

aiohttp.web.requests_count

Amount of processed requests.

New in version 1.0.

coroutine Server.shutdown(timeout)[source]

A coroutine that should be called to close all opened connections.

coroutine Server.finish_connections(timeout)

Deprecated since version 1.2: A deprecated alias for shutdown().

Changed in version 1.2: Server was called RequestHandlerFactory before aiohttp==1.2.

The rename has no deprecation period but it’s safe: no user should instantiate the class by hands.

Router

For dispatching URLs to handlers aiohttp.web uses routers.

Router is any object that implements AbstractRouter interface.

aiohttp.web provides an implementation called UrlDispatcher.

Application uses UrlDispatcher as router() by default.

class aiohttp.web.UrlDispatcher[source]

Straightforward url-matching router, implements collections.abc.Mapping for access to named routes.

Before running Application you should fill route table first by calling add_route() and add_static().

Handler lookup is performed by iterating on added routes in FIFO order. The first matching route will be used to call corresponding handler.

If on route creation you specify name parameter the result is named route.

Named route can be retrieved by app.router[name] call, checked for existence by name in app.router etc.

See also

Route classes

add_resource(path, *, name=None)[source]

Append a resource to the end of route table.

path may be either constant string like '/a/b/c' or variable rule like '/a/{var}' (see handling variable paths)

Parameters:
  • path (str) – resource path spec.
  • name (str) – optional resource name.
Returns:

created resource instance (PlainResource or DynamicResource).

add_route(method, path, handler, *, name=None, expect_handler=None)[source]

Append handler to the end of route table.

path may be either constant string like '/a/b/c' or
variable rule like '/a/{var}' (see handling variable paths)

Pay attention please: handler is converted to coroutine internally when it is a regular function.

Parameters:
  • method (str) –

    HTTP method for route. Should be one of 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS' or '*' for any method.

    The parameter is case-insensitive, e.g. you can push 'get' as well as 'GET'.

  • path (str) – route path. Should be started with slash ('/').
  • handler (callable) – route handler.
  • name (str) – optional route name.
  • expect_handler (coroutine) – optional expect header handler.
Returns:

new PlainRoute or DynamicRoute instance.

add_get(path, *args, **kwargs)[source]

Shortcut for adding a GET handler. Calls the add_route() with method equals to 'GET'.

New in version 1.0.

add_post(path, *args, **kwargs)[source]

Shortcut for adding a POST handler. Calls the add_route() with

method equals to 'POST'.

New in version 1.0.

add_put(path, *args, **kwargs)[source]

Shortcut for adding a PUT handler. Calls the add_route() with method equals to 'PUT'.

New in version 1.0.

add_patch(path, *args, **kwargs)[source]

Shortcut for adding a PATCH handler. Calls the add_route() with method equals to 'PATCH'.

New in version 1.0.

add_delete(path, *args, **kwargs)[source]

Shortcut for adding a DELETE handler. Calls the add_route() with method equals to 'DELETE'.

New in version 1.0.

add_static(prefix, path, *, name=None, expect_handler=None, chunk_size=256*1024, response_factory=StreamResponse, show_index=False, follow_symlinks=False)[source]

Adds a router and a handler for returning static files.

Useful for serving static content like images, javascript and css files.

On platforms that support it, the handler will transfer files more efficiently using the sendfile system call.

In some situations it might be necessary to avoid using the sendfile system call even if the platform supports it. This can be accomplished by by setting environment variable AIOHTTP_NOSENDFILE=1.

If a gzip version of the static content exists at file path + .gz, it will be used for the response.

Warning

Use add_static() for development only. In production, static content should be processed by web servers like nginx or apache.

Changed in version 0.18.0: Transfer files using the sendfile system call on supported platforms.

Changed in version 0.19.0: Disable sendfile by setting environment variable AIOHTTP_NOSENDFILE=1

Changed in version 1.2.0: Send gzip version if file path + .gz exists.

Parameters:
  • prefix (str) – URL path prefix for handled static files
  • path – path to the folder in file system that contains handled static files, str or pathlib.Path.
  • name (str) – optional route name.
  • expect_handler (coroutine) – optional expect header handler.
  • chunk_size (int) –

    size of single chunk for file downloading, 256Kb by default.

    Increasing chunk_size parameter to, say, 1Mb may increase file downloading speed but consumes more memory.

    New in version 0.16.

  • response_factory (callable) –

    factory to use to generate a new response, defaults to StreamResponse and should expose a compatible API.

    New in version 0.17.

  • show_index (bool) – flag for allowing to show indexes of a directory, by default it’s not allowed and HTTP/403 will be returned on directory access.
  • follow_symlinks (bool) – flag for allowing to follow symlinks from a directory, by default it’s not allowed and HTTP/404 will be returned on access.
Returns:

new StaticRoute instance.

add_subapp(prefix, subapp)

Register nested sub-application under given path prefix.

In resolving process if request’s path starts with prefix then further resolving is passed to subapp.

Parameters:
  • prefix (str) – path’s prefix for the resource.
  • subapp (Application) – nested application attached under prefix.
Returns:

a PrefixedSubAppResource instance.

New in version 1.1.

coroutine resolve(request)[source]

A coroutine that returns AbstractMatchInfo for request.

The method never raises exception, but returns AbstractMatchInfo instance with:

  1. http_exception assigned to HTTPException instance.

  2. handler which raises HTTPNotFound or HTTPMethodNotAllowed on handler’s execution if there is no registered route for request.

    Middlewares can process that exceptions to render pretty-looking error page for example.

Used by internal machinery, end user unlikely need to call the method.

Note

The method uses Request.raw_path for pattern matching against registered routes.

resources()[source]

The method returns a view for all registered resources.

The view is an object that allows to:

  1. Get size of the router table:

    len(app.router.resources())
    
  2. Iterate over registered resources:

    for resource in app.router.resources():
        print(resource)
    
  3. Make a check if the resources is registered in the router table:

    route in app.router.resources()
    

New in version 0.21.1.

routes()[source]

The method returns a view for all registered routes.

New in version 0.18.

named_resources()[source]

Returns a dict-like types.MappingProxyType view over all named resources.

The view maps every named resource’s name to the BaseResource instance. It supports the usual dict-like operations, except for any mutable operations (i.e. it’s read-only):

len(app.router.named_resources())

for name, resource in app.router.named_resources().items():
    print(name, resource)

"name" in app.router.named_resources()

app.router.named_resources()["name"]

New in version 0.21.

named_routes()

An alias for named_resources() starting from aiohttp 0.21.

New in version 0.19.

Changed in version 0.21: The method is an alias for named_resources(), so it iterates over resources instead of routes.

Deprecated since version 0.21: Please use named resources instead of named routes.

Several routes which belongs to the same resource shares the resource name.

Resource

Default router UrlDispatcher operates with resources.

Resource is an item in routing table which has a path, an optional unique name and at least one route.

web-handler lookup is performed in the following way:

  1. Router iterates over resources one-by-one.
  2. If resource matches to requested URL the resource iterates over own routes.
  3. If route matches to requested HTTP method (or '*' wildcard) the route’s handler is used as found web-handler. The lookup is finished.
  4. Otherwise router tries next resource from the routing table.
  5. If the end of routing table is reached and no resource / route pair found the router returns special AbstractMatchInfo instance with AbstractMatchInfo.http_exception is not None but HTTPException with either HTTP 404 Not Found or HTTP 405 Method Not Allowed status code. Registered AbstractMatchInfo.handler raises this exception on call.

User should never instantiate resource classes but give it by UrlDispatcher.add_resource() call.

After that he may add a route by calling Resource.add_route().

UrlDispatcher.add_route() is just shortcut for:

router.add_resource(path).add_route(method, handler)

Resource with a name is called named resource. The main purpose of named resource is constructing URL by route name for passing it into template engine for example:

url = app.router['resource_name'].url_for().with_query({'a': 1, 'b': 2})

Resource classes hierarchy:

AbstractResource
  Resource
    PlainResource
    DynamicResource
    StaticResource
class aiohttp.web.AbstractResource[source]

A base class for all resources.

Inherited from collections.abc.Sized and collections.abc.Iterable.

len(resource) returns amount of routes belongs to the resource, for route in resource allows to iterate over these routes.

name

Read-only name of resource or None.

coroutine resolve(method, path)[source]

Resolve resource by finding appropriate web-handler for (method, path) combination.

Parameters:
  • method (str) – requested HTTP method.
  • path (str) – path part of request.
Returns:

(match_info, allowed_methods) pair.

allowed_methods is a set or HTTP methods accepted by resource.

match_info is either UrlMappingMatchInfo if request is resolved or None if no route is found.

get_info()[source]

A resource description, e.g. {'path': '/path/to'} or {'formatter': '/path/{to}', 'pattern': re.compile(r'^/path/(?P<to>[a-zA-Z][_a-zA-Z0-9]+)$

url_for(*args, **kwargs)[source]

Construct an URL for route with additional params.

args and kwargs depend on a parameters list accepted by inherited resource class.

Returns:URL – resulting URL instance.

New in version 1.1.

url(**kwargs)[source]

Construct an URL for route with additional params.

kwargs depends on a list accepted by inherited resource class parameters.

Returns:str – resulting URL string.

Deprecated since version 1.1: Use url_for() instead.

class aiohttp.web.Resource[source]

A base class for new-style resources, inherits AbstractResource.

add_route(method, handler, *, expect_handler=None)[source]

Add a web-handler to resource.

Parameters:
  • method (str) –

    HTTP method for route. Should be one of 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS' or '*' for any method.

    The parameter is case-insensitive, e.g. you can push 'get' as well as 'GET'.

    The method should be unique for resource.

  • handler (callable) – route handler.
  • expect_handler (coroutine) – optional expect header handler.
Returns:

new ResourceRoute instance.

class aiohttp.web.PlainResource[source]

A resource, inherited from Resource.

The class corresponds to resources with plain-text matching, '/path/to' for example.

url_for()[source]

Returns a URL for the resource.

New in version 1.1.

class aiohttp.web.DynamicResource[source]

A resource, inherited from Resource.

The class corresponds to resources with variable matching, e.g. '/path/{to}/{param}' etc.

url_for(**params)[source]

Returns a URL for the resource.

Parameters:params

– a variable substitutions for dynamic resource.

E.g. for '/path/{to}/{param}' pattern the method should be called as resource.url_for(to='val1', param='val2')

New in version 1.1.

class aiohttp.web.StaticResource[source]

A resource, inherited from Resource.

The class corresponds to resources for static file serving.

url_for(filename)[source]

Returns a URL for file path under resource prefix.

Parameters:filename

– a file name substitution for static file handler.

Accepts both str and pathlib.Path.

E.g. an URL for '/prefix/dir/file.txt' should be generated as resource.url_for(filename='dir/file.txt')

New in version 1.1.

class aiohttp.web.PrefixedSubAppResource[source]

A resource for serving nested applications. The class instance is returned by add_subapp call.

New in version 1.1.

url_for(**kwargs)[source]

The call is not allowed, it raises RuntimeError.

Route

Route has HTTP method (wildcard '*' is an option), web-handler and optional expect handler.

Every route belong to some resource.

Route classes hierarchy:

AbstractRoute
  ResourceRoute
  SystemRoute

ResourceRoute is the route used for resources, SystemRoute serves URL resolving errors like 404 Not Found and 405 Method Not Allowed.

class aiohttp.web.AbstractRoute[source]

Base class for routes served by UrlDispatcher.

method

HTTP method handled by the route, e.g. GET, POST etc.

handler

handler that processes the route.

name

Name of the route, always equals to name of resource which owns the route.

resource

Resource instance which holds the route, None for SystemRoute.

url_for(*args, **kwargs)[source]

Abstract method for constructing url handled by the route.

Actually it’s a shortcut for route.resource.url_for(...).

coroutine handle_expect_header(request)[source]

100-continue handler.

class aiohttp.web.ResourceRoute[source]

The route class for handling different HTTP methods for Resource.

class aiohttp.web.SystemRoute

The route class for handling URL resolution errors like like 404 Not Found and 405 Method Not Allowed.

status

HTTP status code

reason

HTTP status reason

MatchInfo

After route matching web application calls found handler if any.

Matching result can be accessible from handler as Request.match_info attribute.

In general the result may be any object derived from AbstractMatchInfo (UrlMappingMatchInfo for default UrlDispatcher router).

class aiohttp.web.UrlMappingMatchInfo[source]

Inherited from dict and AbstractMatchInfo. Dict items are filled by matching info and is resource-specific.

expect_handler

A coroutine for handling 100-continue.

handler

A coroutine for handling request.

route

Route instance for url matching.

View

class aiohttp.web.View(request)[source]

Inherited from AbstractView.

Base class for class based views. Implementations should derive from View and override methods for handling HTTP verbs like get() or post():

class MyView(View):

    async def get(self):
        resp = await get_response(self.request)
        return resp

    async def post(self):
        resp = await post_response(self.request)
        return resp

app.router.add_route('*', '/view', MyView)

The view raises 405 Method Not allowed (HTTPMethodNowAllowed) if requested web verb is not supported.

Parameters:request – instance of Request that has initiated a view processing.
request

Request sent to view’s constructor, read-only property.

Overridable coroutine methods: connect(), delete(), get(), head(), options(), patch(), post(), put(), trace().

Utilities

class aiohttp.web.FileField

A namedtuple instance that is returned as multidict value by Request.POST() if field is uploaded file.

name

Field name

filename

File name as specified by uploading (client) side.

file

An io.IOBase instance with content of uploaded file.

content_type

MIME type of uploaded file, 'text/plain' by default.

See also

File Uploads

aiohttp.web.run_app(app, *, host=None, port=None, path=None, loop=None, shutdown_timeout=60.0, ssl_context=None, print=print, backlog=128, access_log_format=None, access_log=aiohttp.log.access_logger)[source]

A utility function for running an application, serving it until keyboard interrupt and performing a Graceful shutdown.

Suitable as handy tool for scaffolding aiohttp based projects. Perhaps production config will use more sophisticated runner but it good enough at least at very beginning stage.

The function uses app.loop as event loop to run.

The server will listen on any host or Unix domain socket path you supply. If no hosts or paths are supplied, or only a port is supplied, a TCP server listening on 0.0.0.0 (all hosts) will be launched.

Distributing HTTP traffic to multiple hosts or paths on the same application process provides no performance benefit as the requests are handled on the same event loop. See aiohttp server deployment for ways of distributing work for increased performance.

Parameters:
  • appApplication instance to run
  • host (str) – TCP/IP host or a sequence of hosts for HTTP server. Default is '0.0.0.0' if port has been specified or if path is not supplied.
  • port (int) – TCP/IP port for HTTP server. Default is 8080 for plain text HTTP and 8443 for HTTP via SSL (when ssl_context parameter is specified).
  • path (str) – file system path for HTTP server Unix domain socket. A sequence of file system paths can be used to bind multiple domain sockets. Listening on Unix domain sockets is not supported by all operating systems.
  • sock (socket) – a preexisting socket object to accept connections on. A sequence of socket objects can be passed.
  • shutdown_timeout (int) –

    a delay to wait for graceful server shutdown before disconnecting all open client sockets hard way.

    A system with properly Graceful shutdown implemented never waits for this timeout but closes a server in a few milliseconds.

  • ssl_contextssl.SSLContext for HTTPS server, None for HTTP connection.
  • print – a callable compatible with print(). May be used to override STDOUT output or suppress it.
  • backlog (int) – the number of unaccepted connections that the system will allow before refusing new connections (128 by default).
  • access_loglogging.Logger instance used for saving access logs. Use None for disabling logs for sake of speedup.
  • access_log_format – access log format, see Format specification for details.
  • loop

    an event loop used for running the application (None by default).

    If the loop is not explicitly specified the function closes it by close() call but does nothing for non-default loop.

Constants

class aiohttp.web.ContentCoding[source]

An enum.Enum class of available Content Codings.

deflate

DEFLATE compression

gzip

GZIP compression

aiohttp.web.identity

no compression

Middlewares

Normalize path middleware

aiohttp.web.normalize_path_middleware(*, append_slash=True, merge_slashes=True)[source]

Middleware that normalizes the path of a request. By normalizing it means:

  • Add a trailing slash to the path.
  • Double slashes are replaced by one.

The middleware returns as soon as it finds a path that resolves correctly. The order if all enabled is 1) merge_slashes, 2) append_slash and 3) both merge_slashes and append_slash. If the path resolves with at least one of those conditions, it will redirect to the new path.

If append_slash is True append slash when needed. If a resource is defined with trailing slash and the request comes without it, it will append it automatically.

If merge_slashes is True, merge multiple consecutive slashes in the path into one.

blog comments powered by Disqus