HTTP Server Reference

Changed in version 0.12: The module was deeply refactored in backward incompatible manner.

Request

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

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

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

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.

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.

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.

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(*, loader=json.loads)[source]

Read request body decoded as json.

The method is just a boilerplate coroutine implemented as:

@asyncio.coroutine
def json(self, *, loader=json.loads):
    body = yield from 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()[source]

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

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

Once you call start() 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..
started

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

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.

New in version 0.14.

enable_compression(force=False)[source]

Enable compression.

When force is False (default) compression is used only when deflate is in Accept-Encoding request’s header.

Accept-Encoding is not checked if force is True.

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

New in version 0.14.

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.

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

write(data)[source]

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

start() must be called before.

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

Raises RuntimeError if start() 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)
yield from 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()[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, 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
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.

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

start(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.
can_start(request)[source]

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

If can_start() call is success then start() 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 newer raises exception.

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()[source]

Returns last occured exception or None.

ping(message=b'')[source]

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'')[source]

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)[source]

Send data to peer as MSG_TEXT message.

Parameters:

data (str) – data to send.

Raises:
send_bytes(data)[source]

Send data to peer as MSG_BINARY message.

Parameters:

data – data to send.

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

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()[source]

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()[source]

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()[source]

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.

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, so you can use it as registry for arbitrary properties for later access from handler via Request.app property:

app = Application(loop=loop)
app['database'] = yield from aiopg.create_engine(**db_config)

@asyncio.coroutine
def handler(request):
    with (yield from request.app['database']) as conn:
        conn.execute("DELETE * FROM table")
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

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

make_handler(**kwargs)[source]

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

yield from loop.create_server(app.make_handler(),
                              '0.0.0.0', 8080)
coroutine finish()[source]

A coroutine that should be called after server stopping.

This method executes functions registered by register_on_finish() in LIFO order.

If callback raises an exception, the error will be stored by call_exception_handler() with keys: message, exception, application.

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 (yield from) the later.

Note

Application object has route attribute but has no add_router method. The reason is: we want to support different route 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 oppened 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_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 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
  • 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)[source]

Adds router for returning static files.

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

Warning

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

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

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

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

    New in version 0.16.

Returns:new StaticRoute instance.
coroutine resolve(requst)[source]

A coroutine that returns AbstractMatchInfo for request.

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

  1. route asigned to SystemRoute 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.

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

Route

Default router UrlDispatcher operates with routes.

User should not instantiate route classes by hand but can give named route instance by router[name] if he have added route by UrlDispatcher.add_route() or UrlDispatcher.add_static() calls with non-empty name parameter.

The main usage of named routes is constructing URL by route name for passing it into template engine for example:

url = app.router['route_name'].url(query={'a': 1, 'b': 2})

There are three concrete route classes:* DynamicRoute for urls with variable pathes spec.

class aiohttp.web.Route[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.

match(path)[source]

Abstract method, accepts URL path and returns dict with parsed path parts for UrlMappingMatchInfo or None if the route cannot handle given path.

The method exists for internal usage, end user unlikely need to call it.

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.

class aiohttp.web.PlainRoute[source]

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

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

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)[source]

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)[source]

Construct url for given filename:

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

The route class for internal purposes.

Now it has used for handling 404: Not Found and 405: Method Not Allowed.

url()

Always raises RuntimeError, SystemRoute should not be used in url construction expressions.

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 given from Route.match() call return value.

route

Route instance for url matching.

Utilities

class aiohttp.web.FileField

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