HTTP Server Reference¶
Changed in version 0.12: The module was deeply refactored in backward incompatible manner.
Request¶
The Request object contains all the information about an incoming HTTP request.
Every handler accepts a request instance as the first positional parameter.
Note
You should never create the Request instance manually –
aiohttp.web does it for you.
-
class
aiohttp.web.Request[source]¶ -
scheme¶ A string representing the scheme of the request.
The scheme is
'https'if transport for request handling is SSL 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.
-
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.
-
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()[source]¶ 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()[source]¶ 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(*, loader=json.loads)[source]¶ Read request body decoded as json.
The method is just a boilerplate coroutine implemented as:
@asyncio.coroutine def json(self, *, loader=json.loads): body = yield from self.text() return loader(body)
Parameters: loader (callable) – any callable that accepts 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()[source]¶ 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()[source]¶ 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)[source]¶ The base class for the HTTP response handling.
Contains methods for setting HTTP response headers, cookies, response status code, writing HTTP response BODY and so on.
The most important thing you should know about response — it is Finite State Machine.
That means you can do any manipulations with headers, cookies and status code only before
start()called.Once you call
start()any change of the HTTP header part will raiseRuntimeErrorexception.Any
write()call afterwrite_eof()is also forbidden.Parameters: -
keep_alive¶ Read-only property, copy of
Request.keep_aliveby default.Can be switched to
Falsebyforce_close()call.
-
force_close()[source]¶ 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)[source]¶ 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()[source]¶ 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.
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.
-
start(request)[source]¶ Parameters: request (aiohttp.web.Request) – HTTP request object, that the response answers. Send HTTP header. You should not change any header data after calling this method.
-
write(data)[source]¶ Send byte-ish data as the part of response BODY.
start()must be called before.Raises
TypeErrorif data is notbytes,bytearrayormemoryviewinstance.Raises
RuntimeErrorifstart()has not been called.Raises
RuntimeErrorifwrite_eof()has been called.
-
coroutine
drain()[source]¶ A coroutine to let the write buffer of the underlying transport a chance to be flushed.
The intended use is to write:
resp.write(data) yield from resp.drain()
Yielding from
drain()gives the opportunity for the loop to schedule the write operation and flush the buffer. It should especially be used when a possibly large amount of data is written to the transport, and the coroutine does not yield-from between calls towrite().New in version 0.14.
-
coroutine
write_eof()[source]¶ A coroutine may be called as a mark of the HTTP response processing finish.
Internal machinery will call this method at the end of the request processing if needed.
After
write_eof()call any manipulations with the response object are forbidden.
-
Response¶
-
class
aiohttp.web.Response(*, status=200, headers=None, content_type=None, body=None, text=None)[source]¶ The most usable response class, inherited from
StreamResponse.Accepts body argument for setting the HTTP response BODY.
The actual
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
-
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=())[source]¶ Class for handling server-side websockets.
After starting (by
start()call) the response you cannot usewrite()method but should to communicate with websocket client bysend_str(),receive()and others.-
start(request)[source]¶ Starts websocket. After the call you can use websocket methods.
Parameters: request (aiohttp.web.Request) – HTTP request object, that the response answers. Raises HTTPException: if websocket handshake has failed.
-
can_start(request)[source]¶ Performs checks for request data to figure out if websocket can be started on the request.
If
can_start()call is success thenstart()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 newer raises exception.
-
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.
-
ping(message=b'')[source]¶ 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'')[source]¶ 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)[source]¶ 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)[source]¶ 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'')[source]¶ A coroutine that initiates closing handshake by sending
MSG_CLOSEmessage.Parameters: Raises RuntimeError: if connection is not started or closing
-
coroutine
receive()[source]¶ A coroutine that waits upcoming data message from peer and returns it.
The coroutine implicitly handles
MSG_PING,MSG_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.
-
New in version 0.14.
See also
Application and Router¶
Application¶
Application is a synonym for web-server.
To get fully working example, you have to make application, register
supported urls in router and create a server socket with
aiohttp.RequestHandlerFactory as a protocol
factory. RequestHandlerFactory could be constructed with
make_handler().
Application contains a router instance and a list of callbacks that will be called during application finishing.
Application is a dict, so you can use it as registry for
arbitrary properties for later access from
handler via Request.app property:
app = Application(loop=loop)
app['database'] = yield from aiopg.create_engine(**db_config)
@asyncio.coroutine
def handler(request):
with (yield from request.app['database']) as conn:
conn.execute("DELETE * FROM table")
-
class
aiohttp.web.Application(*, loop=None, router=None, logger=<default>, middlewares=(), **kwargs)[source]¶ The class inherits
dict.Parameters: - loop –
event loop used for processing HTTP requests.
If param is
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.
-
make_handler(**kwargs)[source]¶ 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(...) yield from loop.create_server(app.make_handler(), '0.0.0.0', 8080)
-
coroutine
finish()[source]¶ A coroutine that should be called after server stopping.
This method executes functions registered by
register_on_finish()in LIFO order.If callback raises an exception, the error will be stored by
call_exception_handler()with keys: message, exception, application.
-
register_on_finish(self, func, *args, **kwargs): Register func as a function to be executed at termination. Any optional arguments that are to be passed to func must be passed as arguments to
register_on_finish(). It is possible to register the same function and arguments more than once.During the call of
finish()all functions registered are called in last in, first out order.func may be either regular function or coroutine,
finish()will un-yield (yield from) the later.
Note
Application object has
routeattribute but has noadd_route()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 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[source]¶ 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_route(method, path, handler, *, name=None, expect_handler=None)[source]¶ Append handler to the end of route table.
- path may be either constant string like
'/a/b/c'or - variable rule like
'/a/{var}'(see handling variable pathes)
Pay attention please: handler is converted to coroutine internally when it is a regular function.
Parameters: - method (str) –
HTTP method for route. Should be one of
'GET','POST','PUT','DELETE','PATCH','HEAD','OPTIONS'or'*'for any method.The parameter is case-insensitive, e.g. you can push
'get'as well as'GET'. - path (str) – route path. 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)[source]¶ Adds router for returning static files.
Useful for handling static content like images, javascript and css files.
Warning
Use
add_static()for development only. In production, static content should be processed by web servers like nginx or apache.Parameters: - prefix (str) – URL path prefix for handled static files
- path (str) – path to the folder in file system that contains handled static files.
- name (str) – optional route name.
- expect_handler (coroutine) – optional expect header handler.
- chunk_size (int) –
size of single chunk for file downloading, 64Kb by default.
Increasing chunk_size parameter to, say, 1Mb may increase file downloading speed but consumes more memory.
New in version 0.16.
Returns: new StaticRouteinstance.-
coroutine
resolve(requst)[source]¶ A coroutine that returns
AbstractMatchInfofor request.The method never raises exception, but returns
AbstractMatchInfoinstance with:routeasigned toSystemRouteinstancehandlerwhich 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.
-
Route¶
Default router UrlDispatcher operates with routes.
User should not instantiate route classes by hand but can give named
route instance by router[name] if he have added route by
UrlDispatcher.add_route() or UrlDispatcher.add_static()
calls with non-empty name parameter.
The main usage of named routes is constructing URL by route name for passing it into template engine for example:
url = app.router['route_name'].url(query={'a': 1, 'b': 2})
There are three concrete route classes:* DynamicRoute for
urls with variable pathes spec.
PlainRoutefor urls without variable pathesDynamicRoutefor urls with variable pathes spec.StaticRoutefor static file handlers.
-
class
aiohttp.web.Route[source]¶ Base class for routes served by
UrlDispatcher.-
method¶
HTTP method handled by the route, e.g. GET, POST etc.
-
handler¶
handler that processes the route.
-
name¶
Name of the route.
Abstract method, accepts URL path and returns
dictwith parsed path parts forUrlMappingMatchInfoorNoneif 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.
-
-
class
aiohttp.web.PlainRoute[source]¶ 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'``
-
class
aiohttp.web.DynamicRoute[source]¶ 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'
-
class
aiohttp.web.StaticRoute[source]¶ 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'
-
class
aiohttp.web.SystemRoute¶ The route class for internal purposes.
Now it has used for handling 404: Not Found and 405: Method Not Allowed.
-
url()¶
Always raises
RuntimeError,SystemRouteshould not be used in url construction expressions.-
MatchInfo¶
After route matching web application calls found handler if any.
Matching result can be accessible from handler as
Request.match_info attribute.
In general the result may be any object derived from
AbstractMatchInfo (UrlMappingMatchInfo for default
UrlDispatcher router).
Utilities¶
-
class
aiohttp.web.FileField¶ A
namedtuple()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
-