# 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). `Request` has an `Request.app` and `Request.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
  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, `'http'` otherwise.

    The value could be overridden by `clone()`.

    Read-only `str` property.

    Changed in version 2.3: Forwarded and X-Forwarded-Proto are not used anymore.

    Call `.clone(scheme=new_scheme)` for setting up the value explicitly.

    See also

    Deploying behind a Proxy

  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, resolved in this order:

    - Overridden value by `clone()` call.

    - Host HTTP header

    - `socket.getfqdn()`

    Read-only `str` property.

    Changed in version 2.3: Forwarded and X-Forwarded-Host are not used anymore.

    Call `.clone(host=new_host)` for setting up the value explicitly.

    See also

    Deploying behind a Proxy

  remote

    Originating IP address of a client initiated HTTP request.

    The IP is resolved through the following headers, in this order:

    - Overridden value by `clone()` call.

    - Peer name of opened socket.

    Read-only `str` property.

    Call `.clone(remote=new_remote)` for setting up the value explicitly.

    Added in version 2.3.

    See also

    Deploying behind a Proxy

  client_max_size

    The maximum size of the request body.

    The value could be overridden by `clone()`.

    Read-only `int` property.

  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-decoded. 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 URL-encoded and may contain invalid URL characters, e.g. `/my%2Fpath%7Cwith%21some%25strange%24characters`.

    For URL-decoded 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

    A 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

  loop

    An event loop instance used by HTTP request handling.

    Read-only `asyncio.AbstractEventLoop` property.

    Deprecated since version 3.5.

  cookies

    A read-only dictionary-like object containing the request’s cookies.

    Read-only `MappingProxyType` property.

  content

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

    Read-only property.

  body_exists

    Return `True` if request has HTTP BODY, `False` otherwise.

    Read-only `bool` property.

    Added in version 2.3.

  can_read_body

    Return `True` if request’s HTTP BODY can be read, `False` otherwise.

    Read-only `bool` property.

    Added in version 2.3.

  has_body

    Return `True` if request’s HTTP BODY can be read, `False` otherwise.

    Read-only `bool` property.

    Deprecated since version 2.3: Use `can_read_body()` 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.

  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]

  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.

  if_unmodified_since

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

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

    Added in version 3.1.

  if_match

    Read-only property that returns `ETag` objects specified in the If-Match header.

    Returns `tuple` of `ETag` or `None` if If-Match header is absent.

    Added in version 3.8.

  if_none_match

    Read-only property that returns `ETag` objects specified If-None-Match header.

    Returns `tuple` of `ETag` or `None` if If-None-Match header is absent.

    Added in version 3.8.

  if_range

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

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

    Added in version 3.1.

  clone(*, method=..., rel_url=..., headers=...)

    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`

      - headers – `CIMultiDict` or compatible headers container.

    Returns:

      a cloned `Request` instance.

  get_extra_info(name, default=None)

    Reads extra information from the protocol’s transport. If no value associated with `name` is found, `default` is returned.

    See `asyncio.BaseTransport.get_extra_info()`

    Parameters:

      - name (str) – The key to look up in the transport extra information.

      - default – Default value to be used when no value for `name` is found (default is `None`).

    Added in version 3.7.

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

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

  async 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 loads(body)

    Parameters:

      loads (collections.abc.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.

  async multipart()

    Returns `aiohttp.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.

    See also

    Working with Multipart

    Changed in version 3.4: Dropped reader parameter.

  async post()

    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.

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

class aiohttp.web.Request

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

  config_dict

    A `aiohttp.ChainMapProxy` instance for mapping all properties from the current application returned by `app` property and all its parents.

    See also

    Application’s config

    Added in version 3.2.

  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:

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

Response classes are `dict` like objects, allowing them to be used for sharing data among Middlewares and Signals handlers:

    resp['key'] = value

Added in version 3.0: Dict-like interface support.

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

  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.

  task

    A task that serves HTTP request handling.

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

  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 `aiohttp.web.BaseRequest.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.

    See also

    `enable_compression()`

  enable_compression(force=None, strategy=zlib.Z_DEFAULT_STRATEGY)

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

    strategy accepts a `zlib` compression strategy. See `zlib.compressobj()` for possible values.

    See also

    `compression`

  chunked

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

    Can be enabled by `enable_chunked_encoding()` call.

    See also

    `enable_chunked_encoding`

  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.

    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.

  set_cookie(name, value, *, path='/', expires=None, domain=None, max_age=None, secure=None, httponly=None, version=None, samesite=None)

    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)

      - samesite (str) –

        Asserts that a cookie must not be sent with cross-origin requests, providing some protection against cross-site request forgery attacks. Generally the value should be one of: `None`, `Lax` or `Strict`. (optional)

        > Added in version 3.7.

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

  del_cookie(name, *, path='/', domain=None)

    Deletes cookie.

    Parameters:

      - name (str) – cookie name

      - domain (str) – optional cookie domain

      - path (str) – optional cookie path, `'/'` by default

  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.

  etag

    ETag header for outgoing response.

    This property accepts raw `str` values, `ETag` objects and the value `None` to unset the header.

    In case of `str` input, etag is considered as strong by default.

    Do not use double quotes `"` in the etag value, they will be added automatically.

    Added in version 3.8.

  async 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 `on_response_prepare` signal handlers after default headers have been computed and directly before headers are sent.

  async write(data)

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

        await resp.write(data)

    `prepare()` must be invoked before the call.

    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.

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

class aiohttp.web.Response(*, body=None, status=200, reason=None, text=None, headers=None, content_type=None, charset=None, zlib_executor_size=sentinel, zlib_executor=None)

  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.

    - zlib_executor_size (int) –

      length in bytes which will trigger zlib compression

        of body to happen in an executor

      Added in version 3.5.

    - zlib_executor (int) –

      executor to use for zlib compression

      Added in version 3.5.

  body

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

    Assigning `str` to `body` will make the `body` type of `aiohttp.payload.StringPayload`, which tries to encode the given data based on Content-Type HTTP header, while defaulting to `UTF-8`.

  text

    Read-write attribute for storing response’s `body`, represented as `str`.

class aiohttp.web.FileResponse(*, path, chunk_size=256 * 1024, status=200, reason=None, headers=None)

  The response class used to send files, inherited from `StreamResponse`.

  Supports the `Content-Range` and `If-Range` HTTP Headers in requests.

  The actual `body` sending happens in overridden `prepare()`.

  Parameters:

    - path – Path to file. Accepts both `str` and `pathlib.Path`.

    - chunk_size (int) – Chunk size in bytes which will be passed into `io.RawIOBase.read()` in the event that the `sendfile` system call is not supported.

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

    - headers (collections.abc.Mapping) – HTTP headers that should be added to response’s ones. The `Content-Type` response header will be overridden if provided.

class aiohttp.web.WebSocketResponse(*, timeout=10.0, receive_timeout=None, autoclose=True, autoping=True, heartbeat=None, protocols=(), compress=True, max_msg_size=4194304, writer_limit=65536)

  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.

  To enable back-pressure from slow websocket clients treat methods `ping()`, `pong()`, `send_str()`, `send_bytes()`, `send_json()`, `send_frame()` 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.

    - heartbeat (float) – Send ping message every heartbeat seconds and wait pong response, close connection if pong response is not received. The timer is reset on any data reception.

    - timeout (float) – Timeout value for the `close` operation. After sending the close websocket message, `close` waits for `timeout` seconds for a response. Default value is `10.0` (10 seconds for `close` operation)

    - receive_timeout (float) – Timeout value for receive operations. Default value is `None` (no timeout for receive operation)

    - compress (bool) – Enable per-message deflate extension support. `False` for disabled, default value is `True`.

    - max_msg_size (int) –

      maximum size of read websocket message, 4

        MB by default. To disable the size limit use `0`.

      Added in version 3.3.

    - autoclose (bool) – Close connection when the client sends a `CLOSE` message, `True` by default. If set to `False`, the connection is not closed and the caller is responsible for calling `request.transport.close()` to avoid leaking resources.

    - writer_limit (int) –

      maximum size of write buffer, 64 KB by default.

        Once the buffer is full, the websocket will pause to drain the buffer.

      Added in version 3.11.

  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)

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

  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:

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

  ws_protocol

    Websocket subprotocol chosen after `start()` call.

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

  get_extra_info(name, default=None)

    Reads optional extra information from the writer’s transport. If no value associated with `name` is found, `default` is returned.

    See `asyncio.BaseTransport.get_extra_info()`

    Parameters:

      - name (str) – The key to look up in the transport extra information.

      - default – Default value to be used when no value for `name` is found (default is `None`).

  exception()

    Returns last occurred exception or None.

  async ping(message=b'')

    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.

    Changed in version 3.0: The method is converted into coroutine

  async pong(message=b'')

    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.

    Changed in version 3.0: The method is converted into coroutine

  async send_str(data, compress=None)

    Send data to peer as `TEXT` message.

    Parameters:

      - data (str) – data to send.

      - compress (int) – sets specific level of compression for single message, `None` for not overriding per-socket setting.

    Raises:

      - RuntimeError – if connection is not started or closing

      - TypeError – if data is not `str`

    Changed in version 3.0: The method is converted into coroutine, compress parameter added.

  async send_bytes(data, compress=None)

    Send data to peer as `BINARY` message.

    Parameters:

      - data – data to send.

      - compress (int) – sets specific level of compression for single message, `None` for not overriding per-socket setting.

    Raises:

      - RuntimeError – if connection is not started or closing

      - TypeError – if data is not `bytes`, `bytearray` or `memoryview`.

    Changed in version 3.0: The method is converted into coroutine, compress parameter added.

  async send_json(data, compress=None, *, dumps=json.dumps)

    Send data to peer as JSON string.

    Parameters:

      - data – data to send.

      - compress (int) – sets specific level of compression for single message, `None` for not overriding per-socket setting.

      - dumps (collections.abc.Callable) – any callable that accepts an object and returns a JSON string (`json.dumps()` by default).

    Raises:

      - RuntimeError – if connection is not started or closing

      - ValueError – if data is not serializable object

      - TypeError – if value returned by `dumps` param is not `str`

    Changed in version 3.0: The method is converted into coroutine, compress parameter added.

  async send_frame(message, opcode, compress=None)

    Send a `WSMsgType` message message to peer.

    This method is low-level and should be used with caution as it only accepts bytes which must conform to the correct message type for message.

    It is recommended to use the `send_str()`, `send_bytes()` or `send_json()` methods instead of this method.

    The primary use case for this method is to send bytes that are have already been encoded without having to decode and re-encode them.

    Parameters:

      - message (bytes) – message to send.

      - opcode (WSMsgType) – opcode of the message.

      - compress (int) – sets specific level of compression for single message, `None` for not overriding per-socket setting.

    Added in version 3.11.

  async close(*, code=WSCloseCode.OK, message=b'', drain=True)

    A coroutine that initiates closing handshake by sending `CLOSE` message.

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

    Parameters:

      - code (int) – closing code. See also `WSCloseCode`.

      - message – optional payload of close message, `str` (converted to UTF-8 encoded bytes) or `bytes`.

      - drain (bool) – drain outgoing buffer before closing connection.

    Raises:

      RuntimeError – if connection is not started

  async receive(timeout=None)

    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

  async receive_str(*, timeout=None)

    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:

      aiohttp.WSMessageTypeError – if message is not `TEXT`.

  async receive_bytes(*, timeout=None)

    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:

      aiohttp.WSMessageTypeError – if message is not `BINARY`.

  async receive_json(*, loads=json.loads, timeout=None)

    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 (collections.abc.Callable) – any callable that accepts `str` and returns `dict` with parsed JSON (`json.loads()` by default).

      - timeout –

        timeout for receive operation.

        timeout value overrides response`s receive_timeout attribute.

    Return dict:

      loaded JSON content

    Raises:

      - TypeError – if message is `BINARY`.

      - ValueError – if message is not valid JSON.

See also

WebSockets handling

class aiohttp.web.WebSocketReady

  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.

  See also

  `WebSocketResponse.can_prepare()`

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

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

### HTTP Exceptions

Errors can also be returned by raising a HTTP exception instance from within the handler.

class aiohttp.web.HTTPException(*, headers=None, reason=None, text=None, content_type=None)

  Low-level HTTP failure.

  Parameters:

    - headers (dict or multidict.CIMultiDict) – headers for the response

    - reason (str) – reason included in the response

    - text (str) – response’s body

    - content_type (str) – response’s content type. This is passed through to the `Response` initializer.

  Sub-classes of `HTTPException` exist for the standard HTTP response codes as described in Exceptions and the expected usage is to simply raise the appropriate exception type to respond with a specific HTTP response code.

  Since `HTTPException` is a sub-class of `Response`, it contains the methods and properties that allow you to directly manipulate details of the response.

  status_code

    HTTP status code for this exception class. This attribute is usually defined at the class level. `self.status_code` is passed to the `Response` initializer.

## Application and Router

class aiohttp.web.Application(*, logger=<default>, router=None, middlewares=(), handler_args=None, client_max_size=1024**2, loop=None, debug=...)

  Application is a synonym for web-server.

  To get a fully working example, you have to make an application, register supported urls in the router and pass it to `aiohttp.web.run_app()` or `aiohttp.web.AppRunner`.

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

  This class 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()
      database = AppKey("database", AsyncEngine)
      app[database] = await create_async_engine(db_url)

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

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

  The class inherits `dict`.

  Parameters:

    - logger –

      `logging.Logger` instance for storing application logs.

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

    - router –

      `aiohttp.abc.AbstractRouter` instance, the system

        creates `UrlDispatcher` by default if router is `None`.

      Deprecated since version 3.3: The custom routers support is deprecated, the parameter will be removed in 4.0.

    - middlewares – `list` of middleware factories, see Middlewares for details.

    - handler_args – dict-like object that overrides keyword arguments of `Application.make_handler()`

    - client_max_size – client’s maximum size in a request, in bytes. If a POST request exceeds this value, it raises an HTTPRequestEntityTooLarge exception.

    - loop –

      event loop

      Deprecated since version 2.0: The parameter is deprecated. Loop is get set during freeze stage.

    - debug –

      Switches debug mode.

      Deprecated since version 3.5: Use asyncio Debug Mode instead.

  router

    Read-only property that returns router instance.

  logger

    `logging.Logger` instance for storing application logs.

  loop

    event loop used for processing HTTP requests.

    Deprecated since version 3.5.

  debug

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

    Deprecated since version 3.5: Use asyncio Debug Mode instead.

  on_response_prepare

    A `Signal` that is fired near the end of `StreamResponse.prepare()` with parameters request and response. It can be used, for example, to add custom headers to each response, or to modify the default headers computed by the application, directly before sending the headers to the client.

    Signal handlers should have the following signature:

        async def on_prepare(request, response):
            pass

    Note

    The headers are written immediately after these callbacks are run. Therefore, if you modify the content of the response, you may need to adjust the Content-Length header or similar to match. Aiohttp will not make any updates to the headers from this point.

  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

    Signals.

  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.

    See also

    Graceful shutdown and `on_cleanup`.

  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

    See also

    Signals and `on_shutdown`.

  cleanup_ctx

    A list of context generators for startup/cleanup handling.

    Signal handlers should have the following signature:

        async def context(app):
            # do startup stuff
            yield
            # do cleanup

    Added in version 3.1.

    See also

    Cleanup Context.

  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.

  add_domain(domain, subapp)

    Register nested sub-application that serves the domain name or domain name mask.

    In resolving process if request.headers[‘host’] matches the pattern domain then further resolving is passed to subapp.

    Parameters:

      - domain (str) – domain or mask of domain for the resource.

      - subapp (Application) – nested application.

    Returns:

      a `MatchedSubAppResource` instance.

  add_routes(routes_table)

    Register route definitions from routes_table.

    The table is a `list` of `RouteDef` items or `RouteTableDef`.

    Returns:

      `list` of registered `AbstractRoute` instances.

    The method is a shortcut for `app.router.add_routes(routes_table)`, see also `UrlDispatcher.add_routes()`.

    Added in version 3.1.

    Changed in version 3.7: Return value updated from `None` to `list` of `AbstractRoute` instances.

  make_handler(loop=None, **kwargs)

    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.

        Deprecated since version 2.0.

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

      - logger – Custom logger object. Default: `aiohttp.log.server_logger`.

      - access_log – Custom logging object. Default: `aiohttp.log.access_logger`.

      - access_log_class – Class for access_logger. Default: `aiohttp.helpers.AccessLogger`. Must to be a subclass of `aiohttp.abc.AbstractAccessLogger`.

      - access_log_format (str) – Access log format string. Default: `helpers.AccessLogger.LOG_FORMAT`.

      - 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 ignores additional data coming from the client when lingering close is on. Use `0` to disable lingering on server channel closing.

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

        loop = asyncio.get_event_loop()

        app = Application()

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

        await loop.create_server(app.make_handler(),
                                 '0.0.0.0', 8080)

    Deprecated since version 3.2: The method is deprecated and will be removed in future aiohttp versions. Please use Application runners instead.

  async startup()

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

    The purpose of the method is calling `on_startup` signal handlers.

  async shutdown()

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

    The purpose of the method is calling `on_shutdown` signal handlers.

  async cleanup()

    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 `aiohttp.abc.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).

class aiohttp.web.AppKey(name, t)

  This class should be used for the keys in `Application`. They provide a type-safe alternative to str keys when checking your code with a type checker (e.g. mypy). They also avoid name clashes with keys from different libraries etc.

  Parameters:

    - name – A name to help with debugging. This should be the same as the variable name (much like how `typing.TypeVar` is used).

    - t – The type that should be used for the value in the dict (e.g. str, Iterator[int] etc.)

class aiohttp.web.Server

  A protocol factory compatible with `create_server()`.

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

  connections

    List of all currently opened connections.

  requests_count

    Amount of processed requests.

  async shutdown(timeout)

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

class aiohttp.web.UrlDispatcher

  For dispatching URLs to handlers `aiohttp.web` uses routers, which is any object that implements `AbstractRouter` interface.

  This class is a straightforward url-matching router, implementing `collections.abc.Mapping` for access to named routes.

  `Application` uses this class as `router()` by default.

  Before running an `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 the corresponding handler.

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

  A named route can be retrieved by a `app.router[name]` call, checking for existence can be done with `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 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)

    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 (collections.abc.Callable) – route handler.

      - name (str) – optional route name.

      - expect_handler (collections.abc.Coroutine) – optional expect header handler.

    Returns:

      new `AbstractRoute` instance.

  add_routes(routes_table)

    Register route definitions from routes_table.

    The table is a `list` of `RouteDef` items or `RouteTableDef`.

    Returns:

      `list` of registered `AbstractRoute` instances.

    Added in version 2.3.

    Changed in version 3.7: Return value updated from `None` to `list` of `AbstractRoute` instances.

  add_get(path, handler, *, name=None, allow_head=True, **kwargs)

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

    If allow_head is `True` (default) the route for method HEAD is added with the same handler as for GET.

    If name is provided the name for HEAD route is suffixed with `'-head'`. For example `router.add_get(path, handler, name='route')` call adds two routes: first for GET with name `'route'` and second for HEAD with name `'route-head'`.

  add_post(path, handler, **kwargs)

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

    `method` equals to `'POST'`.

  add_head(path, handler, **kwargs)

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

  add_put(path, handler, **kwargs)

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

  add_patch(path, handler, **kwargs)

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

  add_delete(path, handler, **kwargs)

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

  add_view(path, handler, **kwargs)

    Shortcut for adding a class-based view handler. Calls the `add_route()` with `method` equals to `'*'`.

    Added in version 3.0.

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

    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 Brotli or gzip compressed version of the static content exists at the requested path with the `.br` or `.gz` extension, it will be used for the response. Brotli will be preferred over gzip if both files exist.

    Warning

    Use `add_static()` for development only. In production, static content should be processed by web servers like nginx or apache. Such web servers will be able to provide significantly better performance and security for static assets. Several past security vulnerabilities in aiohttp only affected applications using `add_static()`.

    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 (collections.abc.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.

      - 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 that lead outside the static root directory, by default it’s not allowed and HTTP/404 will be returned on access. Enabling `follow_symlinks` can be a security risk, and may lead to a directory transversal attack. You do NOT need this option to follow symlinks which point to somewhere else within the static directory, this option is only used to break out of the security sandbox. Enabling this option is highly discouraged, and only expected to be used for edge cases in a local development setting where remote users do not have access to the server.

      - append_version (bool) – flag for adding file version (hash) to the url query string, this value will be used as default when you call to `url()` and `url_for()` methods.

    Returns:

      new `AbstractRoute` instance.

  async resolve(request)

    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 `aiohttp.web.BaseRequest.raw_path` for pattern matching against registered routes.

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

  routes()

    The method returns a view for all registered routes.

  named_resources()

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

    The view maps every named resource’s name to the `AbstractResource` 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"]

### 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. The router splits the URL and checks the index from longest to shortest. For example, ‘/one/two/three’ will first check the index for ‘/one/two/three’, then ‘/one/two’ and finally ‘/’.

2. If the URL part is found in the index, the list of routes for that URL part is iterated over. If a route matches to requested HTTP method (or `'*'` wildcard) the route’s handler is used as the chosen web-handler. The lookup is finished.

3. If the route is not found in the index, the router tries to find the route in the list of `MatchedSubAppResource`, (current only created from `add_domain()`), and will iterate over the list of `MatchedSubAppResource` in a linear fashion until a match is found.

4. If no resource / route pair was found, the router returns the special `AbstractMatchInfo` instance with `aiohttp.abc.AbstractMatchInfo.http_exception` is not `None` but `HTTPException` with either HTTP 404 Not Found or HTTP 405 Method Not Allowed status code. Registered `handler()` raises this exception on call.

Fixed paths are preferred over variable paths. For example, if you have two routes `/a/b` and `/a/{name}`, then the first route will always be preferred over the second one.

If there are multiple dynamic paths with the same fixed prefix, they will be resolved in order of registration.

For example, if you have two dynamic routes that are prefixed with the fixed `/users` path such as `/users/{x}/{y}/z` and `/users/{x}/y/z`, the first one will be preferred over the second one.

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
      PrefixResource
        StaticResource
        PrefixedSubAppResource
           MatchedSubAppResource

class aiohttp.web.AbstractResource

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

  canonical

    Read-only canonical path associate with the resource. For example `/path/to` or `/path/{to}`

    Added in version 3.3.

  async resolve(request)

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

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

    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)

    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.

class aiohttp.web.Resource

  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.

      - handler (collections.abc.Callable) – route handler.

      - expect_handler (collections.abc.Coroutine) – optional expect header handler.

    Returns:

      new `ResourceRoute` instance.

class aiohttp.web.PlainResource

  A resource, inherited from `Resource`.

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

  canonical

    Read-only canonical path associate with the resource. Returns the path used to create the PlainResource. For example `/path/to`

    Added in version 3.3.

  url_for()

    Returns a `URL` for the resource.

class aiohttp.web.DynamicResource

  A resource, inherited from `Resource`.

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

  canonical

    Read-only canonical path associate with the resource. Returns the formatter obtained from the path used to create the DynamicResource. For example, from a path `/get/{num:^\d+}`, it returns `/get/{num}`

    Added in version 3.3.

  url_for(**params)

    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')`

class aiohttp.web.StaticResource

  A resource, inherited from `Resource`.

  The class corresponds to resources for static file serving.

  canonical

    Read-only canonical path associate with the resource. Returns the prefix used to create the StaticResource. For example `/prefix`

    Added in version 3.3.

  url_for(filename, append_version=None)

    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')`

      - append_version (bool) –

        – a flag for adding file version

          (hash) to the url query string for cache boosting

        By default has value from a constructor (`False` by default) When set to `True` - `v=FILE_HASH` query string param will be added When set to `False` has no impact

        if file not found has no impact

class aiohttp.web.PrefixedSubAppResource

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

  canonical

    Read-only canonical path associate with the resource. Returns the prefix used to create the PrefixedSubAppResource. For example `/prefix`

    Added in version 3.3.

  url_for(**kwargs)

    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

  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)

    Abstract method for constructing url handled by the route.

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

  async handle_expect_header(request)

    `100-continue` handler.

class aiohttp.web.ResourceRoute

  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

### RouteDef and StaticDef

Route definition, a description for not registered yet route.

Could be used for filing route table by providing a list of route definitions (Django style).

The definition is created by functions like `get()` or `post()`, list of definitions could be added to router by `UrlDispatcher.add_routes()` call:

    from aiohttp import web

    async def handle_get(request):
        ...

    async def handle_post(request):
        ...

    app.router.add_routes([web.get('/get', handle_get),
                           web.post('/post', handle_post),

class aiohttp.web.AbstractRouteDef

  A base class for route definitions.

  Inherited from `abc.ABC`.

  Added in version 3.1.

  register(router)

    Register itself into `UrlDispatcher`.

    Abstract method, should be overridden by subclasses.

    Returns:

      `list` of registered `AbstractRoute` objects.

    Changed in version 3.7: Return value updated from `None` to `list` of `AbstractRoute` instances.

class aiohttp.web.RouteDef

  A definition of not registered yet route.

  Implements `AbstractRouteDef`.

  Added in version 2.3.

  Changed in version 3.1: The class implements `AbstractRouteDef` interface.

  method

    HTTP method (`GET`, `POST` etc.) (`str`).

  path

    Path to resource, e.g. `/path/to`. Could contain `{}` brackets for variable resources (`str`).

  handler

    An async function to handle HTTP request.

  kwargs

    A `dict` of additional arguments.

class aiohttp.web.StaticDef

  A definition of static file resource.

  Implements `AbstractRouteDef`.

  Added in version 3.1.

  prefix

    A prefix used for static file handling, e.g. `/static`.

  path

    File system directory to serve, `str` or `pathlib.Path` (e.g. `'/home/web-service/path/to/static'`.

  kwargs

    A `dict` of additional arguments, see `UrlDispatcher.add_static()` for a list of supported options.

aiohttp.web.get(path, handler, *, name=None, allow_head=True, expect_handler=None)

  Return `RouteDef` for processing `GET` requests. See `UrlDispatcher.add_get()` for information about parameters.

  Added in version 2.3.

aiohttp.web.post(path, handler, *, name=None, expect_handler=None)

  Return `RouteDef` for processing `POST` requests. See `UrlDispatcher.add_post()` for information about parameters.

  Added in version 2.3.

aiohttp.web.head(path, handler, *, name=None, expect_handler=None)

  Return `RouteDef` for processing `HEAD` requests. See `UrlDispatcher.add_head()` for information about parameters.

  Added in version 2.3.

aiohttp.web.put(path, handler, *, name=None, expect_handler=None)

  Return `RouteDef` for processing `PUT` requests. See `UrlDispatcher.add_put()` for information about parameters.

  Added in version 2.3.

aiohttp.web.patch(path, handler, *, name=None, expect_handler=None)

  Return `RouteDef` for processing `PATCH` requests. See `UrlDispatcher.add_patch()` for information about parameters.

  Added in version 2.3.

aiohttp.web.delete(path, handler, *, name=None, expect_handler=None)

  Return `RouteDef` for processing `DELETE` requests. See `UrlDispatcher.add_delete()` for information about parameters.

  Added in version 2.3.

aiohttp.web.view(path, handler, *, name=None, expect_handler=None)

  Return `RouteDef` for processing `ANY` requests. See `UrlDispatcher.add_view()` for information about parameters.

  Added in version 3.0.

aiohttp.web.static(prefix, path, *, name=None, expect_handler=None, chunk_size=256 * 1024, show_index=False, follow_symlinks=False, append_version=False)

  Return `StaticDef` for processing static files.

  See `UrlDispatcher.add_static()` for information about supported parameters.

  Added in version 3.1.

aiohttp.web.route(method, path, handler, *, name=None, expect_handler=None)

  Return `RouteDef` for processing requests that decided by `method`. See `UrlDispatcher.add_route()` for information about parameters.

  Added in version 2.3.

### RouteTableDef

A routes table definition used for describing routes by decorators (Flask style):

    from aiohttp import web

    routes = web.RouteTableDef()

    @routes.get('/get')
    async def handle_get(request):
        ...

    @routes.post('/post')
    async def handle_post(request):
        ...

    app.router.add_routes(routes)

    @routes.view("/view")
    class MyView(web.View):
        async def get(self):
            ...

        async def post(self):
            ...

class aiohttp.web.RouteTableDef

  A sequence of `RouteDef` instances (implements `collections.abc.Sequence` protocol).

  In addition to all standard `list` methods the class provides also methods like `get()` and `post()` for adding new route definition.

  Added in version 2.3.

  @get(path, *, allow_head=True, name=None, expect_handler=None)

    Add a new `RouteDef` item for registering `GET` web-handler.

    See `UrlDispatcher.add_get()` for information about parameters.

  @post(path, *, name=None, expect_handler=None)

    Add a new `RouteDef` item for registering `POST` web-handler.

    See `UrlDispatcher.add_post()` for information about parameters.

  @head(path, *, name=None, expect_handler=None)

    Add a new `RouteDef` item for registering `HEAD` web-handler.

    See `UrlDispatcher.add_head()` for information about parameters.

  @put(path, *, name=None, expect_handler=None)

    Add a new `RouteDef` item for registering `PUT` web-handler.

    See `UrlDispatcher.add_put()` for information about parameters.

  @patch(path, *, name=None, expect_handler=None)

    Add a new `RouteDef` item for registering `PATCH` web-handler.

    See `UrlDispatcher.add_patch()` for information about parameters.

  @delete(path, *, name=None, expect_handler=None)

    Add a new `RouteDef` item for registering `DELETE` web-handler.

    See `UrlDispatcher.add_delete()` for information about parameters.

  @view(path, *, name=None, expect_handler=None)

    Add a new `RouteDef` item for registering `ANY` methods against a class-based view.

    See `UrlDispatcher.add_view()` for information about parameters.

    Added in version 3.0.

  static(prefix, path, *, name=None, expect_handler=None, chunk_size=256 * 1024, show_index=False, follow_symlinks=False, append_version=False)

    Add a new `StaticDef` item for registering static files processor.

    See `UrlDispatcher.add_static()` for information about supported parameters.

    Added in version 3.1.

  @route(method, path, *, name=None, expect_handler=None)

    Add a new `RouteDef` item for registering a web-handler for arbitrary HTTP method.

    See `UrlDispatcher.add_route()` for information about parameters.

### 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

  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

    `AbstractRoute` instance for url matching.

### View

class aiohttp.web.View(request)

  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_view('/view', MyView)

  The view raises 405 Method Not allowed (`HTTPMethodNotAllowed`) 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()`.

See also

Class Based Views

## Running Applications

To start web application there is `AppRunner` and site classes.

Runner is a storage for running application, sites are for running application on specific TCP or Unix socket, e.g.:

    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, 'localhost', 8080)
    await site.start()
    # wait for finish signal
    await runner.cleanup()

Added in version 3.0: `AppRunner` / `ServerRunner` and `TCPSite` / `UnixSite` / `SockSite` are added in aiohttp 3.0

class aiohttp.web.BaseRunner

  A base class for runners. Use `AppRunner` for serving `Application`, `ServerRunner` for low-level `Server`.

  server

    Low-level web `Server` for handling HTTP requests, read-only attribute.

  addresses

    A `list` of served sockets addresses.

    See `socket.getsockname()` for items type.

    Added in version 3.3.

  sites

    A read-only `set` of served sites (`TCPSite` / `UnixSite` / `NamedPipeSite` / `SockSite` instances).

  async setup()

    Initialize the server. Should be called before adding sites.

  async cleanup()

    Stop handling all registered sites and cleanup used resources.

class aiohttp.web.AppRunner(app, *, handle_signals=False, **kwargs)

  A runner for `Application`. Used with conjunction with sites to serve on specific port.

  Inherited from `BaseRunner`.

  Parameters:

    - app (Application) – web application instance to serve.

    - handle_signals (bool) – add signal handlers for `signal.SIGINT` and `signal.SIGTERM` (`False` by default). These handlers will raise `GracefulExit`.

    - kwargs – named parameters to pass into web protocol.

  Supported kwargs:

  Parameters:

    - tcp_keepalive (bool) – Enable TCP Keep-Alive. Default: `True`.

    - keepalive_timeout (int) – Number of seconds before closing Keep-Alive connection. Default: `3630` seconds (when deployed behind a reverse proxy it’s important for this value to be higher than the proxy’s timeout. To avoid race conditions we always want the proxy to close the connection).

    - logger – Custom logger object. Default: `aiohttp.log.server_logger`.

    - access_log – Custom logging object. Default: `aiohttp.log.access_logger`.

    - access_log_class – Class for access_logger. Default: `aiohttp.helpers.AccessLogger`. Must to be a subclass of `aiohttp.abc.AbstractAccessLogger`.

    - access_log_format (str) – Access log format string. Default: `helpers.AccessLogger.LOG_FORMAT`.

    - 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 ignores additional data coming from the client when lingering close is on. Use `0` to disable lingering on server channel closing.

    - read_bufsize (int) –

      Size of the read buffer (`BaseRequest.content`).

        `None` by default, it means that the session global value is used.

      Added in version 3.7.

    - auto_decompress (bool) –

      Automatically decompress request body, `True` by default.

      Added in version 3.8.

  app

    Read-only attribute for accessing to `Application` served instance.

  async setup()

    Initialize application. Should be called before adding sites.

    The method calls `Application.on_startup` registered signals.

  async cleanup()

    Stop handling all registered sites and cleanup used resources.

    `Application.on_shutdown` and `Application.on_cleanup` signals are called internally.

class aiohttp.web.ServerRunner(web_server, *, handle_signals=False, **kwargs)

  A runner for low-level `Server`. Used with conjunction with sites to serve on specific port.

  Inherited from `BaseRunner`.

  Parameters:

    - web_server (Server) – low-level web server instance to serve.

    - handle_signals (bool) – add signal handlers for `signal.SIGINT` and `signal.SIGTERM` (`False` by default). These handlers will raise `GracefulExit`.

    - kwargs – named parameters to pass into web protocol.

  See also

  Low Level Server demonstrates low-level server usage

class aiohttp.web.BaseSite

  An abstract class for handled sites.

  name

    An identifier for site, read-only `str` property. Could be a handled URL or UNIX socket path.

  async start()

    Start handling a site.

  async stop()

    Stop handling a site.

class aiohttp.web.TCPSite(runner, host=None, port=None, *, shutdown_timeout=60.0, ssl_context=None, backlog=128, reuse_address=None, reuse_port=None)

  Serve a runner on TCP socket.

  Parameters:

    - runner – a runner to serve.

    - host (str) – HOST to listen on, all interfaces if `None` (default).

    - port (int) – PORT to listed on, `8080` if `None` (default).

    - shutdown_timeout (float) – a timeout used for both waiting on pending tasks before application shutdown and for closing opened connections on `BaseSite.stop()` call.

    - ssl_context – a `ssl.SSLContext` instance for serving SSL/TLS secure server, `None` for plain HTTP server (default).

    - backlog (int) –

      a number of unaccepted connections that the system will allow before refusing new connections, see `socket.socket.listen()` for details.

      `128` by default.

    - reuse_address (bool) – tells the kernel to reuse a local socket in TIME_WAIT state, without waiting for its natural timeout to expire. If not specified will automatically be set to True on UNIX.

    - reuse_port (bool) – tells the kernel to allow this endpoint to be bound to the same port as other existing endpoints are bound to, so long as they all set this flag when being created. This option is not supported on Windows.

class aiohttp.web.UnixSite(runner, path, *, shutdown_timeout=60.0, ssl_context=None, backlog=128)

  Serve a runner on UNIX socket.

  Parameters:

    - runner – a runner to serve.

    - path (str) – PATH to UNIX socket to listen.

    - shutdown_timeout (float) – a timeout used for both waiting on pending tasks before application shutdown and for closing opened connections on `BaseSite.stop()` call.

    - ssl_context – a `ssl.SSLContext` instance for serving SSL/TLS secure server, `None` for plain HTTP server (default).

    - backlog (int) –

      a number of unaccepted connections that the system will allow before refusing new connections, see `socket.socket.listen()` for details.

      `128` by default.

class aiohttp.web.NamedPipeSite(runner, path, *, shutdown_timeout=60.0)

  Serve a runner on Named Pipe in Windows.

  Parameters:

    - runner – a runner to serve.

    - path (str) – PATH of named pipe to listen.

    - shutdown_timeout (float) – a timeout used for both waiting on pending tasks before application shutdown and for closing opened connections on `BaseSite.stop()` call.

class aiohttp.web.SockSite(runner, sock, *, shutdown_timeout=60.0, ssl_context=None, backlog=128)

  Serve a runner on UNIX socket.

  Parameters:

    - runner – a runner to serve.

    - sock – A socket instance to listen to.

    - shutdown_timeout (float) – a timeout used for both waiting on pending tasks before application shutdown and for closing opened connections on `BaseSite.stop()` call.

    - ssl_context – a `ssl.SSLContext` instance for serving SSL/TLS secure server, `None` for plain HTTP server (default).

    - backlog (int) –

      a number of unaccepted connections that the system will allow before refusing new connections, see `socket.socket.listen()` for details.

      `128` by default.

exception aiohttp.web.GracefulExit

  Raised by signal handlers for `signal.SIGINT` and `signal.SIGTERM` defined in `AppRunner` and `ServerRunner` when `handle_signals` is set to `True`.

  Inherited from `SystemExit`, which exits with error code `1` if not handled.

## Utilities

class aiohttp.web.FileField

  A `dataclass` instance that is returned as multidict value by `aiohttp.web.BaseRequest.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, sock=None, shutdown_timeout=60.0, keepalive_timeout=3630, ssl_context=None, print=print, backlog=128, access_log_class=aiohttp.helpers.AccessLogger, access_log_format=aiohttp.helpers.AccessLogger.LOG_FORMAT, access_log=aiohttp.log.access_logger, handle_signals=True, reuse_address=None, reuse_port=None, handler_cancellation=False)

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

  This is a high-level function very similar to `asyncio.run()` and should be used as the main entry point for an application. The `Application` object essentially becomes our main() function. If additional tasks need to be run in parallel, see Complex Applications.

  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 Server Deployment for ways of distributing work for increased performance.

  Parameters:

    - app – `Application` instance to run or a coroutine that returns an application.

    - 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 – 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, `str`, `pathlib.Path` or an iterable of these.

    - sock (socket.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.

      This is used as a delay to wait for pending tasks to complete and then again to close any pending connections.

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

    - keepalive_timeout (float) –

      a delay before a TCP connection is

        closed after a HTTP request. The delay allows for reuse of a TCP connection.

        When deployed behind a reverse proxy it’s important for this value to be higher than the proxy’s timeout. To avoid race conditions, we always want the proxy to handle connection closing.

      Added in version 3.8.

    - ssl_context – `ssl.SSLContext` for HTTPS server, `None` for HTTP connection.

    - print – a callable compatible with `print()`. May be used to override STDOUT output or suppress it. Passing None disables output.

    - backlog (int) – the number of unaccepted connections that the system will allow before refusing new connections (`128` by default).

    - access_log_class – class for access_logger. Default: `aiohttp.helpers.AccessLogger`. Must to be a subclass of `aiohttp.abc.AbstractAccessLogger`.

    - access_log – `logging.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.

    - handle_signals (bool) – override signal TERM handling to gracefully exit the application.

    - reuse_address (bool) – tells the kernel to reuse a local socket in TIME_WAIT state, without waiting for its natural timeout to expire. If not specified will automatically be set to True on UNIX.

    - reuse_port (bool) – tells the kernel to allow this endpoint to be bound to the same port as other existing endpoints are bound to, so long as they all set this flag when being created. This option is not supported on Windows.

    - handler_cancellation (bool) – cancels the web handler task if the client drops the connection. This is recommended if familiar with asyncio behavior or scalability is a concern. Peer disconnection

  Added in version 3.0: Support access_log_class parameter.

  Support reuse_address, reuse_port parameter.

  Added in version 3.1: Accept a coroutine as app parameter.

  Added in version 3.9: Support handler_cancellation parameter (this was the default behavior in aiohttp <3.7).

## Constants

class aiohttp.web.ContentCoding

  An `enum.Enum` class of available Content Codings.

  deflate

    DEFLATE compression

  gzip

    GZIP compression

  identity

    no compression

## Middlewares

aiohttp.web.normalize_path_middleware(*, append_slash=True, remove_slash=False, merge_slashes=True, redirect_class=HTTPPermanentRedirect)

  Middleware factory which produces a middleware that normalizes the path of a request. By normalizing it means:

  > - Add or remove 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 both merge and append/remove are enabled is:

  > 1. merge_slashes

  > 2. append_slash or remove_slash

  > 3. both merge_slashes and append_slash or remove_slash

  If the path resolves with at least one of those conditions, it will redirect to the new path.

  Only one of append_slash and remove_slash can be enabled. If both are `True` the factory will raise an `AssertionError`

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

  If remove_slash is `True`, append_slash must be `False`. When enabled the middleware will remove trailing slashes and redirect if the resource is defined.

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

  Added in version 3.4: Support for remove_slash