HTTP Server Reference¶
Request¶
The Request object contains all the information about an incoming HTTP request.
Every handler accepts a request instance as the first positional parameter.
A Request is a dict-like object, allowing it to be used for
sharing data among
Middlewares and Signals handlers.
Although Request is dict-like object, it can’t be duplicated
like one using Request.copy().
Note
You should never create the Request instance manually –
aiohttp.web does it for you.
-
class
aiohttp.web.Request¶ -
scheme¶ A string representing the scheme of the request.
The scheme is
'https'if transport for request handling is SSL orsecure_proxy_ssl_headeris matching.'http'otherwise.Read-only
strproperty.
-
method¶ HTTP method, read-only property.
The value is upper-cased
strlike"GET","POST","PUT"etc.
-
version¶ HTTP version of request, Read-only property.
Returns
aiohttp.protocol.HttpVersioninstance.
-
host¶ HOST header of request, Read-only property.
Returns
strorNoneif HTTP request has no HOST header.
-
path_qs¶ The URL including PATH_INFO and the query string. e.g,
/app/blog?id=10Read-only
strproperty.
-
path¶ The URL including PATH INFO without the host or scheme. e.g.,
/app/blog. The path is URL-unquoted. For raw path info seeraw_path.Read-only
strproperty.
-
raw_path¶ The URL including raw PATH INFO without the host or scheme. Warning, the path may be quoted and may contains non valid URL characters, e.g.
/my%2Fpath%7Cwith%21some%25strange%24characters.For unquoted version please take a look on
path.Read-only
strproperty.
-
GET¶ A multidict with all the variables in the query string.
Read-only
MultiDictProxylazy property.Changed in version 0.17: A multidict contains empty items for query string like
?arg=.
-
POST¶ A multidict with all the variables in the POST parameters. POST property available only after
Request.post()coroutine call.Read-only
MultiDictProxy.Raises: RuntimeError – if Request.post()was not called before accessing the property.
-
headers¶ A case-insensitive multidict proxy with all headers.
Read-only
CIMultiDictProxyproperty.
-
raw_headers¶ HTTP headers of response as unconverted bytes, a sequence of
(key, value)pairs.
-
keep_alive¶ Trueif keep-alive connection enabled by HTTP client and protocol version supports it, otherwiseFalse.Read-only
boolproperty.
-
match_info¶ Read-only property with
AbstractMatchInfoinstance for result of route resolving.Note
Exact type of property depends on used router. If
app.routerisUrlDispatcherthe property containsUrlMappingMatchInfoinstance.
-
app¶ An
Applicationinstance used to call request handler, Read-only property.
-
transport¶ An transport used to process request, Read-only property.
The property can be used, for example, for getting IP address of client’s peer:
peername = request.transport.get_extra_info('peername') if peername is not None: host, port = peername
A multidict of all request’s cookies.
Read-only
MultiDictProxylazy property.
-
content¶ A
FlowControlStreamReaderinstance, input stream for reading request’s BODY.Read-only property.
New in version 0.15.
-
has_body¶ Return
Trueif request has HTTP BODY,Falseotherwise.Read-only
boolproperty.New in version 0.16.
-
payload¶ A
FlowControlStreamReaderinstance, input stream for reading request’s BODY.Read-only property.
Deprecated since version 0.15: Use
contentinstead.
-
content_type¶ Read-only property with content part of Content-Type header.
Returns
strlike'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
strlike'utf-8'orNoneif 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
intorNoneif Content-Length is absent.
-
if_modified_since¶ Read-only property that returns the date specified in the If-Modified-Since header.
Returns
datetime.datetimeorNoneif If-Modified-Since header is absent or is not a valid HTTP date.
-
coroutine
read()¶ Read request body, returns
bytesobject with body content.Note
The method does store read data internally, subsequent
read()call will return the same value.
-
coroutine
text()¶ Read request body, decode it using
charsetencoding orUTF-8if no encoding was specified in MIME-type.Returns
strwith body content.Note
The method does store read data internally, subsequent
text()call will return the same value.
-
coroutine
json(*, loads=json.loads)¶ Read request body decoded as json.
The method is just a boilerplate coroutine implemented as:
async def json(self, *, loads=json.loads): body = await self.text() return loader(body)
Parameters: loader (callable) – any callable that accepts strand returnsdictwith parsed JSON (json.loads()by default).Note
The method does store read data internally, subsequent
json()call will return the same value.
-
coroutine
post()¶ A coroutine that reads POST parameters from request body.
Returns
MultiDictProxyinstance filled with parsed data.If
methodis not POST, PUT or PATCH orcontent_typeis not empty or application/x-www-form-urlencoded or multipart/form-data returns empty multidict.Note
The method does store read data internally, subsequent
post()call will return the same value.
-
coroutine
release()¶ Release request.
Eat unread part of HTTP BODY if present.
Note
User code may never call
release(), all required work will be processed byaiohttp.webinternal machinery.
-
Response classes¶
For now, aiohttp.web has two classes for the HTTP response:
StreamResponse and Response.
Usually you need to use the second one. StreamResponse is
intended for streaming data, while Response contains HTTP
BODY as an attribute and sends own content as single piece with the
correct Content-Length HTTP header.
For sake of design decisions Response is derived from
StreamResponse parent class.
The response supports keep-alive handling out-of-the-box if request supports it.
You can disable keep-alive by force_close() though.
The common case for sending an answer from
web-handler is returning a
Response instance:
def handler(request):
return Response("All right!")
StreamResponse¶
-
class
aiohttp.web.StreamResponse(*, status=200, reason=None)¶ 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 raiseRuntimeErrorexception.Any
write()call afterwrite_eof()is also forbidden.Parameters: -
prepared¶ Read-only
boolproperty,Trueifprepare()has been called,Falseotherwise.New in version 0.18.
-
set_status(status, reason=None)¶ -
reason value is auto calculated if not specified (
None).
-
keep_alive¶ Read-only property, copy of
Request.keep_aliveby default.Can be switched to
Falsebyforce_close()call.
-
force_close()¶ Disable
keep_alivefor connection. There are no ways to enable it back.
-
compression¶ Read-only
boolproperty,Trueif compression is enabled.Falseby default.New in version 0.14.
See also
-
enable_compression(force=None)¶ Enable compression.
When force is unset compression encoding is selected based on the request’s Accept-Encoding header.
Accept-Encoding is not checked if force is set to a
ContentCoding.New in version 0.14.
See also
-
chunked¶ Read-only property, indicates if chunked encoding is on.
Can be enabled by
enable_chunked_encoding()call.New in version 0.14.
See also
-
enable_chunked_encoding()¶ Enables
chunkedencoding for response. There are no ways to disable it back. With enabledchunkedencoding each write() operation encoded in separate chunk.New in version 0.14.
Warning
chunked encoding can be enabled for
HTTP/1.1only.Setting up both
content_lengthand chunked encoding is mutually exclusive.See also
-
headers¶ CIMultiDictinstance for outgoing HTTP headers.
An instance of
http.cookies.SimpleCookiefor outgoing cookies.Warning
Direct setting up Set-Cookie header may be overwritten by explicit calls to cookie manipulation.
We are encourage using of
cookiesandset_cookie(),del_cookie()for cookie manipulations.
Convenient way for setting
cookies, allows to specify some additional properties like max_age in a single call.Parameters: - name (str) – cookie name
- value (str) – cookie value (will be converted to
strif 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) –
Trueif the cookie HTTP only (optional) - version (int) – a decimal integer, identifies to which version of the state management specification the cookie conforms. (Optional, version=1 by default)
Changed in version 0.14.3: Default value for path changed from
Noneto'/'.
Deletes cookie.
Parameters: Changed in version 0.14.3: Default value for path changed from
Noneto'/'.
-
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
strvalues,datetime.datetimeobjects, Unix timestamps specified as anintor afloatobject, and the valueNoneto unset the header.
-
tcp_cork¶ TCP_CORK(linux) orTCP_NOPUSH(FreeBSD and MacOSX) is applied to underlying transport if the property isTrue.Use
set_tcp_cork()to assign new value to the property.Default value is
False.
-
set_tcp_cork(value)¶ Set
tcp_corkproperty to value.Clear
tcp_nodelayif value isTrue.
-
tcp_nodelay¶ TCP_NODELAYis applied to underlying transport if the property isTrue.Use
set_tcp_nodelay()to assign new value to the property.Default value is
True.
-
set_tcp_nodelay(value)¶ Set
tcp_nodelayproperty to value.Clear
tcp_corkif value isTrue.
-
start(request)¶ Parameters: request (aiohttp.web.Request) – HTTP request object, that the response answers. Send HTTP header. You should not change any header data after calling this method.
Deprecated since version 0.18: Use
prepare()instead.Warning
The method doesn’t call
web.Application.on_response_preparesignal, useprepare()instead.
-
coroutine
prepare(request)¶ Parameters: request (aiohttp.web.Request) – HTTP request object, that the response answers. Send HTTP header. You should not change any header data after calling this method.
The coroutine calls
web.Application.on_response_preparesignal handlers.New in version 0.18.
-
write(data)¶ Send byte-ish data as the part of response BODY.
prepare()must be called before.Raises
TypeErrorif data is notbytes,bytearrayormemoryviewinstance.Raises
RuntimeErrorifprepare()has not been called.Raises
RuntimeErrorifwrite_eof()has been called.
-
coroutine
drain()¶ A coroutine to let the write buffer of the underlying transport a chance to be flushed.
The intended use is to write:
resp.write(data) await resp.drain()
Yielding from
drain()gives the opportunity for the loop to schedule the write operation and flush the buffer. It should especially be used when a possibly large amount of data is written to the transport, and the coroutine does not yield-from between calls towrite().New in version 0.14.
-
coroutine
write_eof()¶ A coroutine may be called as a mark of the HTTP response processing finish.
Internal machinery will call this method at the end of the request processing if needed.
After
write_eof()call any manipulations with the response object are forbidden.
-
Response¶
-
class
aiohttp.web.Response(*, status=200, headers=None, content_type=None, charset=None, body=None, text=None)¶ The most usable response class, inherited from
StreamResponse.Accepts body argument for setting the HTTP response BODY.
The actual
bodysending happens in overriddenwrite_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,Noneotherwise.
-
body¶ Read-write attribute for storing response’s content aka BODY,
bytes.Setting
bodyalso recalculatescontent_lengthvalue.Resetting
body(assigningNone) setscontent_lengthtoNonetoo, dropping Content-Length HTTP header.
-
text¶ Read-write attribute for storing response’s content, represented as str,
str.Setting
stralso recalculatescontent_lengthvalue andbodyvalueResetting
body(assigningNone) setscontent_lengthtoNonetoo, dropping Content-Length HTTP header.
WebSocketResponse¶
-
class
aiohttp.web.WebSocketResponse(*, timeout=10.0, autoclose=True, autoping=True, protocols=())¶ Class for handling server-side websockets, inherited from
StreamResponse.After starting (by
prepare()call) the response you cannot usewrite()method but should to communicate with websocket client bysend_str(),receive()and others.New in version 0.19: The class supports
async forstatement for iterating over incoming messages:ws = web.WebSocketResponse() await ws.prepare(request) async for msg in ws: print(msg.data)
-
coroutine
prepare(request)¶ Starts websocket. After the call you can use websocket methods.
Parameters: request (aiohttp.web.Request) – HTTP request object, that the response answers. Raises: HTTPException – if websocket handshake has failed. New in version 0.18.
-
start(request)¶ Starts websocket. After the call you can use websocket methods.
Parameters: request (aiohttp.web.Request) – HTTP request object, that the response answers. Raises: HTTPException – if websocket handshake has failed. Deprecated since version 0.18: Use
prepare()instead.
-
can_prepare(request)¶ Performs checks for request data to figure out if websocket can be started on the request.
If
can_prepare()call is success thenprepare()will success too.Parameters: request (aiohttp.web.Request) – HTTP request object, that the response answers. Returns: (ok, protocol)pair, ok isTrueon success, protocol is websocket subprotocol which is passed by client and accepted by server (one of protocols sequence fromWebSocketResponsector). protocol may beNoneif client and server subprotocols are nit overlapping.Note
The method never raises exception.
-
can_start(request)¶ Deprecated alias for
can_prepare()Deprecated since version 0.18.
-
closed¶ Read-only property,
Trueif connection has been closed or in process of closing.MSG_CLOSEmessage has been received from peer.
-
close_code¶ Read-only property, close code from peer. It is set to
Noneon opened connection.
-
protocol¶ Websocket subprotocol chosen after
start()call.May be
Noneif server and client protocols are not overlapping.
-
exception()¶ Returns last occurred exception or None.
-
ping(message=b'')¶ Send
MSG_PINGto peer.Parameters: message – optional payload of ping message, str(converted to UTF-8 encoded bytes) orbytes.Raises: RuntimeError – if connections is not started or closing.
-
pong(message=b'')¶ Send unsolicited
MSG_PONGto peer.Parameters: message – optional payload of pong message, str(converted to UTF-8 encoded bytes) orbytes.Raises: RuntimeError – if connections is not started or closing.
-
send_str(data)¶ Send data to peer as
MSG_TEXTmessage.Parameters: data (str) – data to send.
Raises: - RuntimeError – if connection is not started or closing
- TypeError – if data is not
str
-
send_bytes(data)¶ Send data to peer as
MSG_BINARYmessage.Parameters: data – data to send.
Raises: - RuntimeError – if connection is not started or closing
- TypeError – if data is not
bytes,bytearrayormemoryview.
-
coroutine
close(*, code=1000, message=b'')¶ A coroutine that initiates closing handshake by sending
MSG_CLOSEmessage.Parameters: Raises: RuntimeError – if connection is not started or closing
-
coroutine
receive()¶ A coroutine that waits upcoming data message from peer and returns it.
The coroutine implicitly handles
MSG_PING,MSG_PONGandMSG_CLOSEwithout returning the message.It process ping-pong game and performs closing handshake internally.
After websocket closing raises
WSClientDisconnectedErrorwith connection closing data.Returns: MessageRaises: RuntimeError – if connection is not started Raise: WSClientDisconnectedErroron closing.
-
coroutine
New in version 0.14.
See also
json_response¶
-
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).
Application and Router¶
Application¶
Application is a synonym for web-server.
To get fully working example, you have to make application, register
supported urls in router and create a server socket with
aiohttp.RequestHandlerFactory as a protocol
factory. RequestHandlerFactory could be constructed with
make_handler().
Application contains a router instance and a list of callbacks that will be called during application finishing.
Application is a dict-like object, so you can use it for
sharing data globally by storing arbitrary
properties for later access from a handler via the
Request.app property:
app = Application(loop=loop)
app['database'] = await aiopg.create_engine(**db_config)
async def handler(request):
with (await request.app['database']) as conn:
conn.execute("DELETE * FROM table")
Although Application is a dict-like object, it can’t be
duplicated like one using Application.copy().
-
class
aiohttp.web.Application(*, loop=None, router=None, logger=<default>, middlewares=(), **kwargs)¶ The class inherits
dict.Parameters: - loop –
event loop used for processing HTTP requests.
If param is
Noneasyncio.get_event_loop()used for getting default event loop, but we strongly recommend to use explicit loops everywhere. - router –
aiohttp.abc.AbstractRouterinstance, the system createsUrlDispatcherby default if router isNone. - logger –
logging.Loggerinstance for storing application logs.By default the value is
logging.getLogger("aiohttp.web") - middlewares –
listof middleware factories, see Middlewares for details.New in version 0.13.
-
router¶ Read-only property that returns router instance.
-
logger¶ logging.Loggerinstance for storing application logs.
-
loop¶ event loop used for processing HTTP requests.
-
on_response_prepare¶ A
Signalthat is fired at the beginning ofStreamResponse.prepare()with parameters request and response. It can be used, for example, to add custom headers to each response before sending.Signal handlers should have the following signature:
async def on_prepare(request, response): pass
-
on_shutdown¶ A
Signalthat 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
Applicationdictionary.See also
-
on_cleanup¶ A
Signalthat 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
-
make_handler(**kwargs)¶ Creates HTTP protocol factory for handling requests.
Parameters: kwargs – additional parameters for RequestHandlerFactoryconstructor.You should pass result of the method as protocol_factory to
create_server(), e.g.:loop = asyncio.get_event_loop() app = Application(loop=loop) # setup route table # app.router.add_route(...) await loop.create_server(app.make_handler(), '0.0.0.0', 8080)
-
coroutine
shutdown()¶ A coroutine that should be called on server stopping but before
finish().The purpose of the method is calling
on_shutdownsignal handlers.
-
coroutine
cleanup()¶ A coroutine that should be called on server stopping but after
shutdown().The purpose of the method is calling
on_cleanupsignal handlers.
-
register_on_finish(self, func, *args, **kwargs): Register func as a function to be executed at termination. Any optional arguments that are to be passed to func must be passed as arguments to
register_on_finish(). It is possible to register the same function and arguments more than once.During the call of
finish()all functions registered are called in last in, first out order.func may be either regular function or coroutine,
finish()will un-yield (await) the later.Deprecated since version 0.21: Use
on_cleanupinstead:app.on_cleanup.append(handler).
Note
Application object has
routerattribute but has noadd_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 onlyAbstractRouter.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).
- loop –
RequestHandlerFactory¶
RequestHandlerFactory is responsible for creating HTTP protocol objects that can handle HTTP connections.
Router¶
For dispatching URLs to handlers
aiohttp.web uses routers.
Router is any object that implements AbstractRouter interface.
aiohttp.web provides an implementation called UrlDispatcher.
Application uses UrlDispatcher as router() by default.
-
class
aiohttp.web.UrlDispatcher¶ Straightforward url-matching router, implements
collections.abc.Mappingfor access to named routes.Before running
Applicationyou should fill route table first by callingadd_route()andadd_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 byname in app.routeretc.See also
-
add_resource(path, *, name=None)¶ Append a resource to the end of route table.
path may be either constant string like
'/a/b/c'or variable rule like'/a/{var}'(see handling variable pathes)Parameters: Returns: created resource instance (
PlainResourceorDynamicResource).
-
add_route(method, path, handler, *, name=None, expect_handler=None)¶ Append handler to the end of route table.
- path may be either constant string like
'/a/b/c'or - variable rule like
'/a/{var}'(see handling variable pathes)
Pay attention please: handler is converted to coroutine internally when it is a regular function.
Parameters: - method (str) –
HTTP method for route. Should be one of
'GET','POST','PUT','DELETE','PATCH','HEAD','OPTIONS'or'*'for any method.The parameter is case-insensitive, e.g. you can push
'get'as well as'GET'. - path (str) – route path. Should be started with slash (
'/'). - handler (callable) – route handler.
- name (str) – optional route name.
- expect_handler (coroutine) – optional expect header handler.
Returns: new
PlainRouteorDynamicRouteinstance.- path may be either constant string like
-
add_static(prefix, path, *, name=None, expect_handler=None, chunk_size=256*1024, response_factory=StreamResponse)¶ Adds a router and a handler for returning static files.
Useful for serving static content like images, javascript and css files.
On platforms that support it, the handler will transfer files more efficiently using the
sendfilesystem call.In some situations it might be necessary to avoid using the
sendfilesystem call even if the platform supports it. This can be accomplished by by setting environment variableAIOHTTP_NOSENDFILE=1.Warning
Use
add_static()for development only. In production, static content should be processed by web servers like nginx or apache.Changed in version 0.18.0: Transfer files using the
sendfilesystem call on supported platforms.Changed in version 0.19.0: Disable
sendfileby setting environment variableAIOHTTP_NOSENDFILE=1Parameters: - prefix (str) – URL path prefix for handled static files
- path – path to the folder in file system that contains
handled static files,
strorpathlib.Path. - name (str) – optional route name.
- expect_handler (coroutine) – optional expect header handler.
- chunk_size (int) –
size of single chunk for file downloading, 256Kb by default.
Increasing chunk_size parameter to, say, 1Mb may increase file downloading speed but consumes more memory.
New in version 0.16.
- response_factory (callable) –
factory to use to generate a new response, defaults to
StreamResponseand should expose a compatible API.New in version 0.17.
Returns: new StaticRouteinstance.-
coroutine
resolve(requst)¶ A coroutine that returns
AbstractMatchInfofor request.The method never raises exception, but returns
AbstractMatchInfoinstance with:http_exceptionassigned toHTTPExceptioninstance.handlerwhich raisesHTTPNotFoundorHTTPMethodNotAllowedon handler’s execution if there is no registered route for request.Middlewares can process that exceptions to render pretty-looking error page for example.
Used by internal machinery, end user unlikely need to call the method.
Note
The method uses
Request.raw_pathfor pattern matching against registered routes.Changed in version 0.14: The method don’t raise
HTTPNotFoundandHTTPMethodNotAllowedanymore.
-
resources()¶ The method returns a view for all registered resources.
The view is an object that allows to:
Get size of the router table:
len(app.router.resources())
Iterate over registered resources:
for resource in app.router.resources(): print(resource)
Make a check if the resources is registered in the router table:
route in app.router.resources()
New in version 0.21.1.
-
routes()¶ The method returns a view for all registered routes.
New in version 0.18.
-
named_resources()¶ Returns a
dict-liketypes.MappingProxyTypeview over all named resources.The view maps every named resources’s name to the
BaseResourceinstance. It supports the usualdict-like operations, except for any mutable operations (i.e. it’s read-only):len(app.router.named_resources()) for name, resource in app.router.named_resources().items(): print(name, resource) "name" in app.router.named_resources() app.router.named_resources()["name"]
New in version 0.21.
-
named_routes()¶ An alias for
named_resources()starting from aiohttp 0.21.New in version 0.19.
Changed in version 0.21: The method is an alias for
named_resources(), so it iterates over resources instead of routes.Deprecated since version 0.21: Please use named resources instead of named routes.
Several routes which belongs to the same resource shares the resource name.
-
Resource¶
Default router UrlDispatcher operates with resources.
Resource is an item in routing table which has a path, an optional unique name and at least one route.
web-handler lookup is performed in the following way:
- Router iterates over resources one-by-one.
- If resource matches to requested URL the resource iterates over own routes.
- If route matches to requested HTTP method (or
'*'wildcard) the route’s handler is used as found web-handler. The lookup is finished. - Otherwise router tries next resource from the routing table.
- If the end of routing table is reached and no resource /
route pair found the router returns special
AbstractMatchInfoinstance withAbstractMatchInfo.http_exceptionis notNonebutHTTPExceptionwith either HTTP 404 Not Found or HTTP 405 Method Not Allowed status code. RegisteredAbstractMatchInfo.handlerraises this exception on call.
User should never instantiate resource classes but give it by
UrlDispatcher.add_resource() call.
After that he may add a route by calling Resource.add_route().
UrlDispatcher.add_route() is just shortcut for:
router.add_resource(path).add_route(method, handler)
Resource with a name is called named resource. The main purpose of named resource is constructing URL by route name for passing it into template engine for example:
url = app.router['resource_name'].url(query={'a': 1, 'b': 2})
Resource classes hierarchy:
AbstractResource
Resource
PlainResource
DynamicResource
ResourceAdapter
-
class
aiohttp.web.AbstractResource¶ A base class for all resources.
Inherited from
collections.abc.Sizedandcollections.abc.Iterable.len(resource)returns amount of routes belongs to the resource,for route in resourceallows to iterate over these routes.-
name¶ Read-only name of resource or
None.
-
coroutine
resolve(method, path)¶ Resolve resource by finding appropriate web-handler for
(method, path)combination.Parameters: method (str) – requested HTTP method. Returns: (match_info, allowed_methods) pair. allowed_methods is a
setor HTTP methods accepted by resource.match_info is either
UrlMappingMatchInfoif request is resolved orNoneif no route is found.
-
-
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.
- path (str) – route path. Should be started with slash (
'/'). - handler (callable) – route handler.
- expect_handler (coroutine) – optional expect header handler.
Returns: new
ResourceRouteinstance.- method (str) –
-
-
class
aiohttp.web.PlainResource¶ A new-style resource, inherited from
Resource.The class corresponds to resources with plain-text matching,
'/path/to'for example.
-
class
aiohttp.web.DynamicResource¶ A new-style resource, inherited from
Resource.The class corresponds to resources with variable matching, e.g.
'/path/{to}/{param}'etc.
-
class
aiohttp.web.ResourceAdapter¶ An adapter for old-style routes.
The adapter is used by
router.register_route()call, the method is deprecated and will be removed eventually.
Route¶
Route has HTTP method (wildcard '*' is an option),
web-handler and optional expect handler.
Every route belong to some resource.
Route classes hierarchy:
AbstractRoute
ResourceRoute
Route
PlainRoute
DynamicRoute
StaticRoute
ResourceRoute is the route used for new-style resources,
PlainRoute and DynamicRoute serves old-style
routes kept for backward compatibility only.
StaticRoute is used for static file serving
(UrlDispatcher.add_static()). Don’t rely on the route
implementation too hard, static file handling most likely will be
rewritten eventually.
So the only non-deprecated and not internal route is
ResourceRoute only.
-
class
aiohttp.web.AbstractRoute¶ Base class for routes served by
UrlDispatcher.-
method¶ HTTP method handled by the route, e.g. GET, POST etc.
-
name¶ Name of the route, always equals to name of resource which owns the route.
-
resource¶ Resource instance which holds the route.
-
url(*, query=None, **kwargs)¶ Abstract method for constructing url handled by the route.
query is a mapping or list of (name, value) pairs for specifying query part of url (parameter is processed by
urlencode()).Other available parameters depends on concrete route class and described in descendant classes.
Note
The method is kept for sake of backward compatibility, usually you should use
Resource.url()instead.
-
coroutine
handle_expect_header(request)¶ 100-continuehandler.
-
-
class
aiohttp.web.PlainRoute¶ The route class for handling plain URL path, e.g.
"/a/b/c"-
url(*, parts, query=None)¶ Construct url, doesn’t accepts extra parameters:
>>> route.url(query={'d': 1, 'e': 2}) '/a/b/c/?d=1&e=2'
-
-
class
aiohttp.web.DynamicRoute¶ The route class for handling variable path, e.g.
"/a/{name1}/{name2}"-
url(*, parts, query=None)¶ Construct url with given dynamic parts:
>>> route.url(parts={'name1': 'b', 'name2': 'c'}, query={'d': 1, 'e': 2}) '/a/b/c/?d=1&e=2'
-
-
class
aiohttp.web.StaticRoute¶ The route class for handling static files, created by
UrlDispatcher.add_static()call.-
url(*, filename, query=None)¶ Construct url for given filename:
>>> route.url(filename='img/logo.png', query={'param': 1}) '/path/to/static/img/logo.png?param=1'
-
MatchInfo¶
After route matching web application calls found handler if any.
Matching result can be accessible from handler as
Request.match_info attribute.
In general the result may be any object derived from
AbstractMatchInfo (UrlMappingMatchInfo for default
UrlDispatcher router).
View¶
-
class
aiohttp.web.View(request)¶ Inherited from
AbstractView.Base class for class based views. Implementations should derive from
Viewand override methods for handling HTTP verbs likeget()orpost():class MyView(View): async def get(self): resp = await get_response(self.request) return resp async def post(self): resp = await post_response(self.request) return resp app.router.add_route('*', '/view', MyView)
The view raises 405 Method Not allowed (
HTTPMethodNowAllowed) if requested web verb is not supported.Parameters: request – instance of Requestthat 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
Utilities¶
-
class
aiohttp.web.FileField¶ A
namedtupleinstance that is returned as multidict value byRequest.POST()if field is uploaded file.-
name¶ Field name
-
filename¶ File name as specified by uploading (client) side.
-
content_type¶ MIME type of uploaded file,
'text/plain'by default.
See also
-
-
aiohttp.web.run_app(app, *, host='0.0.0.0', port=None, loop=None, shutdown_timeout=60.0, ssl_context=None, print=print)¶ An utility function for running an application, serving it until keyboard interrupt and performing a Graceful shutdown.
Suitable as handy tool for scaffolding aiohttp based projects. Perhaps production config will use more sophisticated runner but it good enough at least at very beginning stage.
The function uses app.loop as event loop to run.
Parameters: - app –
Applicationinstance to run - host (str) – host for HTTP server,
'0.0.0.0'by default - port (int) – port for HTTP server. By default is
8080for plain text HTTP and8443for HTTP via SSL (when ssl_context parameter is specified). - shutdown_timeout (int) –
a delay to wait for graceful server shutdown before disconnecting all open client sockets hard way.
A system with properly Graceful shutdown implemented never waits for this timeout but closes a server in a few milliseconds.
- ssl_context –
ssl.SSLContextfor HTTPS server,Nonefor HTTP connection. - print – a callable compatible with
print(). May be used to override STDOUT output or suppress it.
- app –