High-level HTTP Server

New in version 0.10.

Run a simple web server

For implementing a web server, first create a request handler.

Handler is a coroutine or a regular function that accepts only request parameter of type Request and returns Response instance:

import asyncio
from aiohttp import web

@asyncio.coroutine
def hello(request):
    return web.Response(request, b"Hello, world")

Next, you have to create a Application instance and register handler in the application’s router pointing HTTP method, path and handler:

app = web.Application()
app.router.add_route('GET', '/', hello)

After that, create a server and run the asyncio loop as usual:

loop = asyncio.get_event_loop()
f = loop.create_server(app.make_handler, '0.0.0.0', 8080)
srv = loop.run_until_complete(f)
print('serving on', srv.sockets[0].getsockname())
try:
    loop.run_forever()
except KeyboardInterrupt:
    pass

That’s it.

Handler

Handler is an any callable that accepts a single Request argument and returns a StreamResponse derived (e.g. Response) instance.

Handler can be a coroutine, aiohttp.web will unyield returned result by applying yield from to the handler.

Handlers are connected to the Application via routes:

handler = Handler()
app.router.add_route('GET', '/', handler)

You can also use variable routes. If route contains string like '/a/{name}/c' that means the route matches to the path like '/a/b/c' or '/a/1/c'.

Parsed path part will be available in the request handler as request.match_info['name']:

@asyncio.coroutine
def variable_handler(request):
    return web.Response(
        request,
        "Hello, {}".format(request.match_info['name']).encode('utf8'))

app.router.add_route('GET', '/{name}', variable_handler)

Handlers can be first-class functions, e.g.:

@asyncio.coroutine
def hello(request):
    return web.Response(request, b"Hello, world")

app.router.add_route('GET', '/', hello)

Sometimes you would like to group logically coupled handlers into a python class.

aiohttp.web doesn’t dictate any implementation details, so application developer can use classes if he wants:

class Handler:

    def __init__(self):
        pass

    def handle_intro(self, request):
        return web.Response(request, b"Hello, world")

    @asyncio.coroutine
    def handle_greeting(self, request):
        name = request.match_info.get('name')
        txt = "Hello, {}".format(name)
        return web.Response(request, txt.encode('utf-8')

handler = Handler()
app.router.add_route('GET', '/intro', handler.handle_intro)
app.router.add_route('GET', '/greet/{name}', handler.handle_greeting)

File Uploads

There are two steps necessary for handling file uploads. The first is to make sure that you have a form that has been setup correctly to accept files. This means adding enctype attribute to your form element with the value of multipart/form-data. A very simple example would be a form that accepts a mp3 file. Notice, we have set up the form as previously explained and also added the input element of the file type:

<form action="/store_mp3" method="post" accept-charset="utf-8"
      enctype="multipart/form-data">

    <label for="mp3">Mp3</label>
    <input id="mp3" name="mp3" type="file" value="" />

    <input type="submit" value="submit" />
</form>

The second step is handling the file upload in your request handler (here assumed to answer on /store_mp3). The uploaded file is added to the request object as a FileField object accessible through the Request.POST() coroutine. The two properties we are interested in are file and filename and we will use those to read a file’s name and a content:

import os
import uuid
from aiohttp.web import Response

def store_mp3_view(request):

    data = yield from request.POST()

    # ``filename`` contains the name of the file in string format.
    filename = data['mp3'].filename

    # ``input_file`` contains the actual file data which needs to be
    # stored somewhere.

    input_file = data['mp3'].file

    content = input_file.read()

    return Response(request, content,
        headers=MultiDict([('CONTENT-DISPOSITION', input-file)])

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

HTTP method, Read-only property.

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

version[source]

HTTP version of request, Read-only property.

Returns aiohttp.protocol.HttpVersion instance.

host[source]

HOST header of request, Read-only property.

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

path_qs[source]

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

Read-only str property.

path[source]

The URL including PATH INFO without the host or scheme. e.g., /app/blog

Read-only str property.

query_string[source]

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

Read-only str property.

GET[source]

A multidict with all the variables in the query string.

Read-only MultiDict lazy property.

headers[source]

A case-insensitive multidict with all headers.

Read-only CaseInsensitiveMultiDict lazy property.

keep_alive[source]

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

Read-only bool property.

match_info[source]

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

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

transport[source]

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('peername')
if peername is not None:
    host, port = peername
cookies[source]

A multidict of all request’s cookies.

Read-only MultiDict lazy property.

payload[source]

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

Read-only property.

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.

read()[source]

Read request body, returns bytes object with body content.

The method is a coroutine.

Warning

The method doesn’t store read data internally, subsequent read() call will return empty bytes b''.

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.

The method is a coroutine.

Warning

The method doesn’t store read data internally, subsequent text() call will return empty string ''.

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

Warning

The method doesn’t store read data internally, subsequent json() call will raise an exception.

POST()[source]

A coroutine that reads POST parameters from request body.

Returns MultiDict 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.

Warning

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

release()[source]

Release request.

Eat unread part of HTTP BODY if present.

The method is a coroutine.

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(request, "All right!")

StreamResponse

class aiohttp.web.StreamResponse(request, *, 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 send_headers() called.

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

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

Parameters:
  • request (aiohttp.web.Request) – HTTP request object, that the response answers.
  • 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..
request[source]

Read-only property for Request object used for creating this response.

status[source]

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

200 (OK) by default.

reason[source]

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

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.

headers[source]

CaseInsensitiveMultiDict instance for outgoing HTTP headers.

cookies[source]

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).
  • expries – 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)
  • 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)

Deletes cookie.

Parameters:
  • name (str) – cookie name
  • domain (str) – optional cookie domain
  • path (str) – optional cookie path
content_length[source]

Content-Length for outgoing response.

content_type[source]

Content part of Content-Type for outgoing response.

charset[source]

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

send_headers()[source]

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.

Calls send_headers() if it has not been called before.

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

Raises RuntimeError if write_eof() has been called.

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(request, body=None, *, status=200, headers=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:
  • request (Request) – HTTP request object used for this response creation.
  • 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.
body[source]

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.

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 make_handler() as a protocol factory.

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

The class inherits dict.

Parameters:
router[source]

Read-only property that returns router instance.

loop[source]

Read-only property that returns event loop.

make_handler()[source]

Creates HTTP protocol for handling requests.

You should never call this method manually, but pass it to create_server() as protocol_factory parameter instead, like:

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

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-mathing 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)[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)
Parameters:
  • path (str) – route path
  • handler (callable) – route handler
  • name (str) – optional route name.
add_static(prefix, path, *, name=None)[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.
resolve(requst)[source]

A coroutine that returns AbstractMatchInfo for request or raises http exception like HTTPNotFound if there is no registered route for request.

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

Route

New in version 0.11.

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 conctrete route classes:* DynamicRoute for urls with variable pathes spec.

class aiohttp.web.Route[source]

Base class for routes served by UrlDispatcher.

method[source]

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

handler[source]

handler that processes the route.

name[source]

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'

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

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

Exceptions

aiohttp.web defines exceptions for list of HTTP status codes.

Each class relates to a single HTTP status code. Each class is a subclass of the HTTPException.

Those exceptions are derived from Response too, so you can either return exception object from Handler or raise it.

The following snippets are equal:

@asyncio.coroutine
def handler(request):
    return aiohttp.web.HTTPFound(request, '/redirect')

and:

@asyncio.coroutine
def handler(request):
    raise aiohttp.web.HTTPFound(request, '/redirect')

Each exception class has a status code according to RFC 2068: codes with 100-300 are not really errors; 400s are client errors, and 500s are server errors.

Http Exception hierarchy chart:

Exception
  HTTPException
    HTTPSuccessful
      * 200 - HTTPOk
      * 201 - HTTPCreated
      * 202 - HTTPAccepted
      * 203 - HTTPNonAuthoritativeInformation
      * 204 - HTTPNoContent
      * 205 - HTTPResetContent
      * 206 - HTTPPartialContent
    HTTPRedirection
      * 300 - HTTPMultipleChoices
      * 301 - HTTPMovedPermanently
      * 302 - HTTPFound
      * 303 - HTTPSeeOther
      * 304 - HTTPNotModified
      * 305 - HTTPUseProxy
      * 307 - HTTPTemporaryRedirect
    HTTPError
      HTTPClientError
        * 400 - HTTPBadRequest
        * 401 - HTTPUnauthorized
        * 402 - HTTPPaymentRequired
        * 403 - HTTPForbidden
        * 404 - HTTPNotFound
        * 405 - HTTPMethodNotAllowed
        * 406 - HTTPNotAcceptable
        * 407 - HTTPProxyAuthenticationRequired
        * 408 - HTTPRequestTimeout
        * 409 - HTTPConflict
        * 410 - HTTPGone
        * 411 - HTTPLengthRequired
        * 412 - HTTPPreconditionFailed
        * 413 - HTTPRequestEntityTooLarge
        * 414 - HTTPRequestURITooLong
        * 415 - HTTPUnsupportedMediaType
        * 416 - HTTPRequestRangeNotSatisfiable
        * 417 - HTTPExpectationFailed
      HTTPServerError
        * 500 - HTTPInternalServerError
        * 501 - HTTPNotImplemented
        * 502 - HTTPBadGateway
        * 503 - HTTPServiceUnavailable
        * 504 - HTTPGatewayTimeout
        * 505 - HTTPVersionNotSupported

All http exceptions have the same constructor:

HTTPNotFound(request, *, headers=None, reason=None)

if other not directly specified. headers will be added to default response headers.

Classes HTTPMultipleChoices, HTTPMovedPermanently, HTTPFound, HTTPSeeOther, HTTPUseProxy, HTTPTemporaryRedirect has constructor signature like:

HTTPFound(request, location, *, headers=None, reason=None)

where location is value for Location HTTP header.

HTTPMethodNotAllowed constructed with pointing trial method and list of allowed methods:

HTTPMethodNotAllowed(request, method, allowed_methods, *, headers=None, reason=None)