Changed in version 0.12: The module was deeply refactored in backward incompatible manner.
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.
HTTP method, Read-only property.
The value is upper-cased str like "GET", "POST", "PUT" etc.
HTTP version of request, Read-only property.
Returns aiohttp.protocol.HttpVersion instance.
HOST header of request, Read-only property.
Returns str or None if HTTP request has no HOST header.
The URL including PATH_INFO and the query string. e.g, /app/blog?id=10
Read-only str property.
The URL including PATH INFO without the host or scheme. e.g., /app/blog
Read-only str property.
A multidict with all the variables in the query string.
Read-only MultiDictProxy lazy property.
A multidict with all the variables in the POST parameters. POST property available only after Request.post() coroutine call.
Read-only MultiDictProxy.
Raises RuntimeError: | |
---|---|
if Request.post() was not called before accessing the property. |
A case-insensitive multidict with all headers.
Read-only CIMultiDictProxy lazy property.
True if keep-alive connection enabled by HTTP client and protocol version supports it, otherwise False.
Read-only bool property.
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.
An Application instance used to call request handler, Read-only property.
An transport used to process request, Read-only property.
The property can be used, for example, for getting IP address of client’s peer:
peername = request.transport.get_extra_info('peername')
if peername is not None:
host, port = peername
A multidict of all request’s cookies.
Read-only MultiDictProxy lazy property.
A FlowControlStreamReader instance, input stream for reading request’s BODY.
Read-only property.
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
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.
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 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''.
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 ''.
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.
A coroutine that reads POST parameters from request body.
Returns MultiDictProxy instance filled with parsed data.
If method is not POST, PUT or PATCH or content_type is not empty or application/x-www-form-urlencoded or multipart/form-data returns empty multidict.
Warning
The method does store read data internally, subsequent post() call will return the same value.
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.
For now, aiohttp.web has two classes for the HTTP response: StreamResponse and Response.
Usually you need to use the second one. StreamResponse is intended for streaming data, while Response contains HTTP BODY as an attribute and sends own content as single piece with the correct Content-Length HTTP header.
For sake of design decisions Response is derived from StreamResponse parent class.
The response supports keep-alive handling out-of-the-box if request supports it.
You can disable keep-alive by force_close() though.
The common case for sending an answer from web-handler is returning a Response instance:
def handler(request):
return Response("All right!")
The base class for the HTTP response handling.
Contains methods for setting HTTP response headers, cookies, response status code, writing HTTP response BODY and so on.
The most important thing you should know about response — it is Finite State Machine.
That means you can do any manipulations with headers, cookies and status code only before start() called.
Once you call start() any change of the HTTP header part will raise RuntimeError exception.
Any write() call after write_eof() is also forbidden.
Parameters: |
---|
Read-only property, copy of Request.keep_alive by default.
Can be switched to False by force_close() call.
Disable keep_alive for connection. There are no ways to enable it back.
Read-only property, incicates if chunked encoding is on.
Can be enabled by enable_chunked_encoding() call.
Enables chunked enacoding for response. There are no ways to disable it back. With enabled chunked encoding each write() operation encoded in separate chunk.
CIMultiDict instance for outgoing HTTP headers.
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: |
|
---|
Deletes cookie.
Parameters: |
---|
Charset aka encoding part of Content-Type for outgoing response.
The value converted to lower-case on attribute assigning.
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.
Send byte-ish data as the part of response BODY.
start() must be called before.
Raises TypeError if data is not bytes, bytearray or memoryview instance.
Raises RuntimeError if start() has not been called.
Raises RuntimeError if write_eof() has been called.
A coroutine to let the write buffer of the underlying transport a chance to be flushed.
The intended use is to write:
resp.write(data)
yield from resp.drain()
Yielding from drain() gives the opportunity for the loop to schedule the write operation and flush the buffer. It should especially be used when a possibly large amount of data is written to the transport, and the coroutine does not yield-from between calls to write().
New in version 0.14.
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.
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: |
|
---|
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.
Read-write attribute for storing response’s content, represented as str, str.
Setting str also recalculates content_length value and body value
Resetting body (assigning None) sets content_length to None too, dropping Content-Length HTTP header.
Class for handling server-side websockets.
After starting (by start() call) the response you cannot use write() method but should to communicate with websocket client by send_str(), receive() and others.
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. |
Performs checks for request data to figure out if websocket can be started on the request.
If can_start() call is success then start() will success too.
Parameters: | request (aiohttp.web.Request) – HTTP request object, that the response answers. |
---|---|
Returns: | (ok, protocol) pair, ok is True on success, protocol is websocket subprotocol which is passed by client and accepted by server (one of protocols sequence from WebSocketResponse ctor). protocol may be None if client and server subprotocols are nit overlapping. |
Note
The method newer raises exception.
Read-only property, True if close() has been called of MSG_CLOSE message has been received from peer.
Websocket subprotocol choosen after start() call.
May be None if server and client protocols are not overlapping.
Send MSG_PING to peer.
Parameters: | message – optional payload of ping messasge, str (coverted to UTF-8 encdoded bytes) or bytes. |
---|---|
Raises RuntimeError: | |
if connections is not started or closing. |
Send unsolicited MSG_PONG to peer.
Parameters: | message – optional payload of pong messasge, str (coverted to UTF-8 encdoded bytes) or bytes. |
---|---|
Raises RuntimeError: | |
if connections is not started or closing. |
Send data to peer as MSG_TEXT message.
Parameters: | data (str) – data to send. |
---|---|
Raises: |
|
Send data to peer as MSG_BINARY message.
Parameters: | data – data to send. |
---|---|
Raises: |
|
Initiate closing handshake by sending MSG_CLOSE message.
The handshake is finished by next yield from ws.receive_*() or yield from ws.wait_closed() call.
Use wait_closed() if you call the method from write-only task and one of receive_str(), receive_bytes() or receive_msg() otherwise.
Parameters: | |
---|---|
Raises RuntimeError: | |
if connection is not started or closing |
A coroutine that waits for socket handshake finish and raises WebSocketDisconnectedError at the end.
Use the method only from write-only tasks, please call one of receive_str(), receive_bytes() or receive_msg() otherwise.
Raises RuntimeError: | |
---|---|
if connection is not started |
A coroutine that waits upcomming data message from peer and returns it.
The coroutine implicitly handles MSG_PING, MSG_PONG and MSG_CLOSE without returning the message.
It process ping-pong game and performs closing handshake internally.
After websocket closing raises WebSocketDisconnectedError with connection closing data.
Returns: | Message |
---|---|
Raises RuntimeError: | |
if connection is not started | |
Raise: | WebSocketDisconnectedError on closing. |
New in version 0.14.
See also
Application is a synonym for web-server.
To get fully working example, you have to make application, register supported urls in router and create a server socket with aiohttp.RequestHandlerFactory as a protocol factory. RequestHandlerFactory could be constructed with make_handler().
Application contains a router instance and a list of callbacks that will be called during application finishing.
Application is a dict, so you can use it as registry for arbitrary properties for later access from handler via Request.app property:
app = Application(loop=loop)
app['database'] = yield from aiopg.create_engine(**db_config)
@asyncio.coroutine
def handler(request):
with (yield from request.app['database']) as conn:
conn.execute("DELETE * FROM table")
The class inherits dict.
Parameters: |
|
---|
Read-only property that returns router instance.
logging.Logger instance for storing application logs.
Creates HTTP protocol factory for handling requests.
Parameters: | kwargs – additional parameters for RequestHandlerFactory constructor. |
---|
You should pass result of the method as protocol_factory to create_server(), e.g.:
loop = asyncio.get_event_loop()
app = Application(loop=loop)
# setup route table
# app.router.add_route(...)
yield from loop.create_server(app.make_handler(),
'0.0.0.0', 8080)
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 func as a function to be executed at termination. Any optional arguments that are to be passed to func must be passed as arguments to register_on_finish(). It is possible to register the same function and arguments more than once.
During the call of finish() all functions registered are called in last in, first out order.
func may be either regular function or coroutine, finish() will un-yield (yield from) the later.
Note
Application object has route attribute but has no add_router method. The reason is: we want to support different route implementations (even maybe not url-matching based but traversal ones).
For sake of that fact we have very trivial ABC for AbstractRouter: it should have only AbstractRouter.resolve() coroutine.
No methods for adding routes or route reversing (getting URL by route name). All those are router implementation details (but, sure, you need to deal with that methods after choosing the router for your application).
RequestHandlerFactory is responsible for creating HTTP protocol objects that can handle http connections.
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.
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
Append handler to the end of route table.
Pay attention please: handler is converted to coroutine internally when it is a regular function.
Parameters: | |
---|---|
Returns: | new PlainRoute or DynamicRoute instance. |
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: | |
---|---|
Returns: | new StaticRoute instance. |
A coroutine that returns AbstractMatchInfo for request.
The method never raises exception, but returns AbstractMatchInfo instance with None route and handler which raises HTTPNotFound or HTTPMethodNotAllowed on handler’s execution if there is no registered route for request.
Middlewares can process that exceptions to render pretty-looking error page for example.
Used by internal machinery, end user unlikely need to call the method.
Changed in version 0.14: The method don’t raise HTTPNotFound and HTTPMethodNotAllowed anymore.
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.
Base class for routes served by UrlDispatcher.
HTTP method handled by the route, e.g. GET, POST etc.
handler that processes the route.
Name of the route.
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.
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.
The route class for handling plain URL path, e.g. "/a/b/c"
Construct url, doesn’t accepts extra parameters:
>>> route.url(query={'d': 1, 'e': 2})
'/a/b/c/?d=1&e=2'``
The route class for handling variable path, e.g. "/a/{name1}/{name2}"
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'
The route class for handling static files, created by UrlDispatcher.add_static() call.
Construct url for given filename:
>>> route.url(filename='img/logo.png', query={'param': 1})
'/path/to/static/img/logo.png?param=1'
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).
A namedtuple() that is returned as multidict value by Request.POST() if field is uploaded file.
Field name
File name as specified by uploading (client) side.
MIME type of uploaded file, 'text/plain' by default.
See also