HTTP Server Reference

Request

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

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

A Request is a dict-like object, allowing it to be used for sharing data among Middlewares and Signals handlers.

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

Note

You should never create the Request instance manually – aiohttp.web does it for you.

class aiohttp.web.Request[source]
scheme

A string representing the scheme of the request.

The scheme is 'https' if transport for request handling is SSL or secure_proxy_ssl_header is matching.

'http' otherwise.

Read-only str property.

method

HTTP method, read-only property.

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

version

HTTP version of request, Read-only property.

Returns aiohttp.protocol.HttpVersion instance.

host

HOST header of request, Read-only property.

Returns str or None if HTTP request has no HOST header.

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_string

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

Read-only str property.

GET

A multidict with all the variables in the query string.

Read-only MultiDictProxy lazy property.

Changed in version 0.17: A multidict contains empty items for query string like ?arg=.

POST

A multidict with all the variables in the POST parameters. POST property available only after Request.post() coroutine call.

Read-only MultiDictProxy.

Raises:RuntimeError – if Request.post() was not called before accessing the 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.

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.

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 FlowControlStreamReader instance, input stream for reading request’s BODY.

Read-only property.

New in version 0.15.

has_body

Return True if request has HTTP BODY, False otherwise.

Read-only bool property.

New in version 0.16.

payload

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

Read-only property.

Deprecated since version 0.15: Use content instead.

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.

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.

coroutine read()

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()

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)

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 loader(body)
Parameters:loader (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 post()

A coroutine that reads POST parameters from request body.

Returns MultiDictProxy instance filled with parsed data.

If method is not POST, PUT or PATCH 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()

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.

Response classes

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

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.

started

Deprecated alias for prepared.

Deprecated since version 0.18.

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)

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()

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.

New in version 0.14.

enable_compression(force=None)

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.

New in version 0.14.

See also

compression

chunked

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

Can be enabled by enable_chunked_encoding() call.

New in version 0.14.

enable_chunked_encoding()

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

New in version 0.14.

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

CIMultiDict 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)

Changed in version 0.14.3: Default value for path changed from None to '/'.

Deletes cookie.

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

Changed in version 0.14.3: Default value for path changed from None to '/'.

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)

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)

Set tcp_nodelay property to value.

Clear tcp_cork if value is True.

start(request)
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.

Deprecated since version 0.18: Use prepare() instead.

Warning

The method doesn’t call web.Application.on_response_prepare signal, use prepare() instead.

coroutine prepare(request)
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 web.Application.on_response_prepare signal handlers.

New in version 0.18.

write(data)

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()

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().

New in version 0.14.

coroutine write_eof()

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 str, str.

Setting str also recalculates content_length value and body value

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

WebSocketResponse

class aiohttp.web.WebSocketResponse(*, timeout=10.0, autoclose=True, autoping=True, 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 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)

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.

start(request)

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.

Deprecated since version 0.18: Use prepare() instead.

can_prepare(request)

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:(ok, protocol) pair, ok is True on success, protocol is websocket subprotocol which is passed by client and accepted by server (one of protocols sequence from WebSocketResponse ctor). protocol may be None if client and server subprotocols are nit overlapping.

Note

The method never raises exception.

can_start(request)

Deprecated alias for can_prepare()

Deprecated since version 0.18.

closed

Read-only property, True if connection has been closed or in process of closing. MSG_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()

Returns last occurred exception or None.

ping(message=b'')

Send MSG_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'')

Send unsolicited MSG_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.
send_str(data)

Send data to peer as MSG_TEXT message.

Parameters:

data (str) – data to send.

Raises:
send_bytes(data)

Send data to peer as MSG_BINARY message.

Parameters:

data – data to send.

Raises:
coroutine close(*, code=1000, message=b'')

A coroutine that initiates closing handshake by sending MSG_CLOSE message.

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 or closing

coroutine receive()

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

The coroutine implicitly handles MSG_PING, MSG_PONG and MSG_CLOSE without returning the message.

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

After websocket closing raises WSClientDisconnectedError with connection closing data.

Returns:Message
Raises:RuntimeError – if connection is not started
Raise:WSClientDisconnectedError on closing.
coroutine receive_str()

A coroutine that calls receive_mgs() but also asserts the message type is MSG_TEXT.

Return str:peer’s message content.
Raises:TypeError – if message is MSG_BINARY.
coroutine receive_bytes()

A coroutine that calls receive_mgs() but also asserts the message type is MSG_BINARY.

Return bytes:peer’s message content.
Raises:TypeError – if message is MSG_TEXT.

New in version 0.14.

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 aiohttp.RequestHandlerFactory as a protocol factory. RequestHandlerFactory could be constructed with 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(loop=loop)
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(*, loop=None, router=None, logger=<default>, middlewares=(), **kwargs)[source]

The class inherits dict.

Parameters:
  • loop

    event loop used for processing HTTP requests.

    If param is None asyncio.get_event_loop() used for getting default event loop, but we strongly recommend to use explicit loops everywhere.

  • 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")

  • middlewares

    list of middleware factories, see Middlewares for details.

    New in version 0.13.

router

Read-only property that returns router instance.

logger

logging.Logger instance for storing application logs.

loop

event loop used for processing HTTP requests.

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_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(**kwargs)

Creates HTTP protocol factory for handling requests.

Parameters:kwargs – additional parameters for RequestHandlerFactory constructor.

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 shutdown()

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

The purpose of the method is calling on_shutdown signal handlers.

coroutine cleanup()

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

The purpose of the method is calling on_cleanup signal handlers.

coroutine finish()

A deprecated alias for cleanup().

Deprecated since version 0.21.

register_on_finish(self, func, *args, **kwargs):

Register func as a function to be executed at termination. Any optional arguments that are to be passed to func must be passed as arguments to register_on_finish(). It is possible to register the same function and arguments more than once.

During the call of finish() all functions registered are called in last in, first out order.

func may be either regular function or coroutine, finish() will un-yield (await) the later.

Deprecated since version 0.21: Use on_cleanup instead: app.on_cleanup.append(handler).

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).

RequestHandlerFactory

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

aiohttp.web.connections

List of all currently opened connections.

aiohttp.web.finish_connections(timeout)

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

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)

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 pathes)

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)

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 pathes)

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_static(prefix, path, *, name=None, expect_handler=None, chunk_size=256*1024, response_factory=StreamResponse)

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.

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

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.

Returns:new StaticRoute instance.
coroutine resolve(requst)

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.

Changed in version 0.14: The method don’t raise HTTPNotFound and HTTPMethodNotAllowed anymore.

resources()

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()

The method returns a view for all registered routes.

New in version 0.18.

named_resources()

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

The view maps every named resources’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(query={'a': 1, 'b': 2})

Resource classes hierarchy:

AbstractResource
  Resource
    PlainResource
    DynamicResource
  ResourceAdapter
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)

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

Parameters:method (str) – requested HTTP method.
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.

url(**kwargs)

Construct an URL for route with additional params.

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

Returns:str – resulting URL.
class aiohttp.web.Resource[source]

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

add_route(method, handler, *, expect_handler=None)

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.

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

new ResourceRoute instance.

class aiohttp.web.PlainResource[source]

A new-style resource, inherited from Resource.

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

class aiohttp.web.DynamicResource[source]

A new-style resource, inherited from Resource.

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

class aiohttp.web.ResourceAdapter[source]

An adapter for old-style routes.

The adapter is used by router.register_route() call, the method is deprecated and will be removed eventually.

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
  Route
    PlainRoute
    DynamicRoute
    StaticRoute

ResourceRoute is the route used for new-style resources, PlainRoute and DynamicRoute serves old-style routes kept for backward compatibility only.

StaticRoute is used for static file serving (UrlDispatcher.add_static()). Don’t rely on the route implementation too hard, static file handling most likely will be rewritten eventually.

So the only non-deprecated and not internal route is ResourceRoute only.

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.

url(*, query=None, **kwargs)[source]

Abstract method for constructing url handled by the route.

query is a mapping or list of (name, value) pairs for specifying query part of url (parameter is processed by urlencode()).

Other available parameters depends on concrete route class and described in descendant classes.

Note

The method is kept for sake of backward compatibility, usually you should use Resource.url() instead.

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.PlainRoute[source]

The route class for handling plain URL path, e.g. "/a/b/c"

url(*, parts, query=None)

Construct url, doesn’t accepts extra parameters:

>>> route.url(query={'d': 1, 'e': 2})
'/a/b/c/?d=1&e=2'
class aiohttp.web.DynamicRoute[source]

The route class for handling variable path, e.g. "/a/{name1}/{name2}"

url(*, parts, query=None)

Construct url with given dynamic parts:

>>> route.url(parts={'name1': 'b', 'name2': 'c'},
              query={'d': 1, 'e': 2})
'/a/b/c/?d=1&e=2'
class aiohttp.web.StaticRoute[source]

The route class for handling static files, created by UrlDispatcher.add_static() call.

url(*, filename, query=None)

Construct url for given filename:

>>> route.url(filename='img/logo.png', query={'param': 1})
'/path/to/static/img/logo.png?param=1'

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='0.0.0.0', port=None, loop=None, shutdown_timeout=60.0, ssl_context=None, print=print)[source]

An 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.

Parameters:
  • appApplication instance to run
  • host (str) – host for HTTP server, '0.0.0.0' by default
  • port (int) – port for HTTP server. By default is 8080 for plain text HTTP and 8443 for HTTP via SSL (when ssl_context parameter is specified).
  • 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.

Constants

class aiohttp.web.ContentCoding[source]

An enum.Enum class of available Content Codings.

deflate

DEFLATE compression

gzip

GZIP comression

identity

no comression

blog comments powered by Disqus