Developer guide · source aligned

aiohttp_ws.py

A compact HTTP and WebSocket framework built on aiohttp, with flexible route returns, lifecycle hooks, cookie tracking, event-based WebSocket messages, multi-domain dispatch, and a requests-like async client.

Python async HTTP routing WebSockets Cookie sessions v1.1.5

Quick start

The server uses aiohttp and imports the local pmblue_update updater, which also requires requests. Make both modules available before importing, then construct a server, decorate routes, and choose a run mode.

from aiohttp_ws import Server, responses

server = Server(host="127.0.0.1", port=8080, default_max_age=3600)

@server.route("/", method="GET")
async def home(request):
    return "<h1>Hello</h1>"

@server.route("/api/users/{user_id}", method="GET")
async def user(request):
    return {"user_id": request.match_info["user_id"]}

@server.route("/old", method="GET")
def old(request):
    return responses.redirect("/")

server.run()
Import side effect: importing aiohttp_ws calls pmblue_update.self_update(). If pmblue_update is missing, the module attempts to download it over HTTP and write pmblue_update.py. Plan for that behavior in offline, test, and restricted environments.

Mental model

Incoming request
Route match
Hooks + handler
Normalized response

HTTP

Server finds a registered Route/ARoute, runs request hooks, calls the handler, normalizes its return value, applies cookies and cache headers, and sends an aiohttp response.

WebSocket

WSEndpoint upgrades a matching request when the decorated handler returns None. Each peer becomes a WSConnection that dispatches named events and correlates request/response messages.

The custom dispatcher checks method-specific route groups before the wildcard group. Each group retains its registration order; it checks an exact match and then a parameter match for each route, so an earlier parameter route can shadow a later literal route. Brace parameters use the bundled TxtParser and appear in request.match_info. get_app() instead registers routes with aiohttp's native router.

Server configuration

Server(host=None, port=None, loop=None, max_size=None, default_max_age=None)
Argument / attributeMeaning
host, portBind address and TCP port used by the run helpers.
loopOptional asyncio event loop. When omitted, the startup helper gets the current loop or creates one.
max_sizeAccepted for compatibility. The current constructor does not apply this value.
default_max_ageDefault lifetime in seconds for values set through Cookies.
default_statusStatus used when route output omits one; initialized to 200.
max_msg_sizeMaximum HTTP/WebSocket message size; defaults to 4 MiB.
ssl_contextAssign an ssl.SSLContext before starting to enable TLS in supported run modes.
routesRoutes registry holding all HTTP and WebSocket route wrappers.
ws_endpoints / connectionsRegistered WebSocket endpoints and a flattened read-only connection list.
runner, appPopulated during startup with the active aiohttp runner/site objects.

Routing and return values

server.route(path, method="*", cache_time=None, server_cache_time=None, pass_cookies=False, **kwargs)

route() accepts sync or async handlers. Since 1.1.5, method accepts one string or an iterable such as ("GET", "POST"). Methods are normalized to uppercase, duplicate values are removed, and each method receives its own route object and response cache.

@server.route("/settings", method=("get", "POST", "GET"))
async def settings(request):
    if request.method == "POST":
        values = await request.json()
        return {"saved": values}
    return {"theme": "dark"}

Empty collections, empty or malformed method tokens, non-string elements, and "*" mixed with explicit methods are rejected. Duplicate path/method registrations raise ValueError before any requested method is registered. The decorator returns the first route wrapper; its method represents only that registration. Existing single-string calls keep their behavior.

This iterable support applies to Server.route(), Server.quick_route(), and PreRoute.route(). WSEndpoint.route() and PmSocket.route() still need one uppercase method string or "*". Extra route keywords are stored in request.route.kwargs; flags such as auth=True have no built-in authentication behavior.

@server.route("/orders/{order_id}", method="GET", cache_time=60)
async def order(request):
    order_id = request.match_info["order_id"]
    if not order_id.isdigit():
        return {"error": "invalid order id"}, 400
    return {"id": int(order_id), "state": "open"}
Handler returnResponse behavior
dict or listJSON response with application/json.
str or intText response with text/html.
bytesRaw response body.
NoneEmpty response with status 204.
aiohttp.web.ResponseReturned unchanged.
(value, status)Normalizes value using the rules above and uses the integer status.
Other objectPassed through unchanged; it must be acceptable to aiohttp.

Cache controls

  • cache_time adds Cache-Control: max-age=<seconds>, public unless the response already has that header.
  • server_cache_time caches the generated response text and status in the route wrapper. Headers are not retained.
  • Both values must be non-negative integers or None.

quick_route()

quick_route(path, method="*", cache_time=None) registers the function directly. It skips the normal handler wrapper, so it does not provide flexible return conversion, lifecycle hooks, or managed cookies. The function must return an aiohttp-compatible response. It accepts the same string/iterable method contract and duplicate-registration checks as route().

Request lifecycle hooks

HookSignatureBehavior
before_requestsasync (request)Runs before the route. A non-None return short-circuits the route but still flows through the after hook.
during_requestsasync (request)Started with asyncio.create_task; it is not awaited before the response.
after_requestsasync (request, response)Runs after normalization. Return None to keep the response or return a replacement value/tuple.
internal_error_decasync (request, exception)Handles uncaught exceptions and is normalized with status 500.
@server.before_requests_dec
async def attach_context(request):
    # Available before this hook as of 1.1.4:
    assert request._aiohttp_ws_server is server

@server.after_requests_dec
async def add_header(request, response):
    response.headers["X-App"] = "salus"

@server.internal_error_dec
async def internal_error(request, error):
    return {"error": "internal server error"}
Decorator naming: the *_dec methods register handlers but do not return the original function. The server retains the callback, but the decorated module-level name becomes None. Assign the property directly if you need to call the function elsewhere.

Cookies

Set pass_cookies=True to receive a Cookies object as the route's second argument. The same object is also assigned to request.session.

from datetime import timedelta
from aiohttp_ws import CookieValue

@server.route("/preferences", method="POST", pass_cookies=True)
async def preferences(request, cookies):
    cookies["theme"] = "dark"                         # server default max age
    cookies["flash"] = ("saved", timedelta(minutes=5))
    cookies["region"] = CookieValue(
        "us-east", max_age=86400, domain="example.com", samesite="Lax"
    )
    return {"theme": cookies.get("theme")}
OperationEffect
cookies[key]Returns the raw cookie value, not the CookieValue wrapper.
cookies[key] = valueSchedules a response cookie using default_max_age when set.
(value, max_age)Accepts seconds, an expiry datetime, or a timedelta.
(value, max_age, domain)Sets value, lifetime, and domain. The implementation also accepts domain and max age in the opposite order when types make it unambiguous.
del cookies[key]Schedules deletion on the outgoing response.
get, pop, clearDictionary-like convenience operations. clear() schedules all original keys for deletion.

A separately constructed Cookies(request) inherits the server's default max age when the request has _aiohttp_ws_server, which is attached before the before-request hook in current versions.

Response helpers

responses.redirect(url)

Returns a status-302 aiohttp response with a Location header.

responses.send_file(...)

Builds an aiohttp response from a path, file object, or bytes and can mark it as an attachment.

responses.send_file(filename_or_fp, mimetype=None, as_attachment=False, attachment_filename=None, max_age=None)

MIME inference recognizes HTML, PNG, JPG/JPEG, GIF, SVG, and JSON, then falls back to application/<extension>. max_age sets a basic Cache-Control header.

Memory behavior: send_file() reads the complete file into memory. Prefer aiohttp's streaming/file response facilities for large files.

Error handling

@server.error_handler(status)

status can be an integer, tuple, list, or range. The async handler must accept (request, exception) and may return the same values as a route.

@server.error_handler(404)
async def not_found(request, error):
    return {"error": "not found", "path": request.path}, 404

@server.error_handler(range(400, 500))
async def client_error(request, error):
    return {"error": error.reason}, error.status

If no custom 404 handler matches, the server returns plain text 404: Not Found. Set an internal error handler separately with internal_error_dec().

Running and embedding

MethodUse
run(coro=None)Creates/uses an event loop, schedules startup and an optional coroutine, then calls run_forever().
start_site()Async start that returns after the TCP site starts; useful inside an existing loop.
run_site()Async start followed by an infinite sleep loop.
to_thread()Starts a new thread and runs the server loop there.
get_app()Returns an aiohttp.web.Application populated with registered routes and middleware.
create_loop(coro)Low-level loop setup used by run().
import_module(name)Imports/reloads a module; when it exposes the name aiohttp_ws, loads entries in that module's global PreRoute.routes registry.
import asyncio

async def main():
    await server.start_site()
    try:
        await asyncio.Event().wait()
    finally:
        if server.runner is not None:
            await server.runner.cleanup()

asyncio.run(main())

Multiple domains on one listener

MultiServer(host=None, port=None)

MultiServer dispatches by the request's Host header. Register domain names without ports. Unregistered hosts go to an internal fallback server.

from aiohttp_ws import MultiServer, Server

public = Server()
admin = Server()

@public.route("/")
async def public_home(request):
    return "Public site"

@admin.route("/")
async def admin_home(request):
    return "Admin site"

multi = MultiServer(host="0.0.0.0", port=8080)
multi.add_server("www.example.com", public)
multi.add_server("admin.example.com", admin)
multi.run()

The first added server with an SSL context supplies MultiServer.ssl_context. Available run methods mirror the main server: create_loop, run, start_site, and run_site.

Event-based WebSockets

Create an endpoint

chat = server.create_ws_endpoint()

@chat.route("/ws", method="GET")
async def websocket_route(request):
    # Returning None tells WSEndpoint to perform the upgrade.
    return None

@chat.on_connect_func
async def connected(connection):
    await connection.send_msg({"ready": True}, "WELCOME")

@chat.event()
async def CHAT(message):
    print(message.data)

@chat.r_event()
async def LOOKUP(message):
    return {"id": message.data, "name": "Example"}

The route handler and event handlers must be async functions. Server-level @server.event() and @server.r_event() callbacks are copied when an endpoint is created; registering through the endpoint also updates its current connections. Incoming server messages are dispatched as separate tasks, so applications must coordinate concurrent state changes. The matching Python client is documented in the client guide.

event() handlers receive fire-and-forget messages. r_event() handlers receive a message carrying a response ID; their return value is sent back as a RESPONSE. Handler names become event names and are case-sensitive.

Wire format

{
  "event": "CHAT",
  "type": "json",
  "data": {"text": "hello"},
  "response_id": "12345",
  "construct_id": "optional-chunk-group",
  "construct_index": 0,
  "construct_final": true
}
FieldMeaning
eventDispatch key. RESPONSE is reserved for correlated replies; PING is registered automatically as a response event.
typestring, bytes (base64 on the wire), or json.
dataDecoded payload exposed as WSMessage.data.
response_idCorrelation ID generated by send_req().
construct_*Chunk metadata used to rebuild a larger logical message.

WSConnection

MethodBehavior
send_msg(data, event, msg_dict=None)Sends bytes, string, number, dict, or list as the module's JSON envelope.
send_req(data, event, check_interval=10, timeout=2000)Sends a correlated request and polls for a reply. Timing arguments are treated as milliseconds.
check(raw_msg)Parses, reconstructs, correlates, and dispatches an incoming aiohttp WebSocket message.
ping(msg_size=0, trial_count=1, send_as_bytes=False, timeout=1000, interval=.5)Measures average round-trip time in milliseconds using the built-in PING response event.
close()Closes the underlying socket once and marks the connection closed.

Useful attributes include original_request, server, ws_endpoint, created, closed, events, and r_events.

PmSocket compatibility adapter

PmSocket(server) implements the simpler text protocol used by resources/pm_socket.js. Its route upgrades when the decorated function returns None, sends ::connect::, answers ::ping:: with ::pong::, and closes on ::disconnect::.

import aiohttp
from aiohttp_ws import PmSocket

socket = PmSocket(server)

@socket.route("/pm-socket", method="GET")
async def socket_route(request):
    return None

@socket.handler
async def on_message(ws, message):
    if message.type == aiohttp.WSMsgType.TEXT and not message.data.startswith("::"):
        await ws.send_str("echo: " + message.data)

@socket.on_disconnect
async def disconnected(ws):
    print("client left")

See the focused PmSocket server guide and browser client guide for the complete compatibility protocol.

PreRoute and modular routes

PreRoute.route() registers route metadata globally without requiring a server at import time. The decorated name becomes a PreRoute instance: call feature.load(server) to load that registration. It accepts the same method strings or iterables as Server.route(). For server.import_module(), the feature module must expose the name aiohttp_ws, as shown below.

# feature_routes.py
import aiohttp_ws

@aiohttp_ws.PreRoute.route("/feature", method=("GET", "POST"))
async def feature(request):
    return {"enabled": True}

# application startup
server.import_module("feature_routes")
Global registry: PreRoute.routes is process-wide and persists for the life of the interpreter. server.import_module() loads the global registry, not just the newly imported module's entries. Repeated calls or reloads can re-register paths and raise duplicate-route errors. Load specific registrations with their instance load(server) method when controlling registration explicitly.

Requests-like async HTTP client

AiohttpResponse reads the entire response before returning and exposes a familiar response interface.

import aiohttp
from aiohttp_ws import AiohttpResponse

response = await AiohttpResponse.get(
    "https://api.example.com/items",
    params={"limit": 20},
    timeout=aiohttp.ClientTimeout(total=10),
)
response.raise_for_status()
print(response.status_code, response.elapsed, response.json())
MemberMeaning
get, post, deleteAsync helpers forwarding arguments to aiohttp.request.
pingOpens a GET request and closes it without loading the response body; returns None.
content, text, json()Raw bytes, decoded text, and JSON-decoded content.
status, status_code, ok, reasonStatus metadata.
headers, cookies, links, historyResponse metadata copied from aiohttp.
url, request, raw, elapsedFinal URL, request info, underlying response, and measured duration.
encoding, apparent_encoding, charset, content_typeDecoding and content-type metadata.
Resource model: each convenience method creates its own aiohttp request context. For high-volume workloads, use a shared aiohttp.ClientSession directly.

Public API reference

Top-level functions

ts(dt=None)

Returns a POSIX timestamp; defaults to a timezone-aware current UTC datetime.

from_ts(t)

Creates a datetime from a POSIX timestamp using the host's local timezone rules.

toggle_badstatusline()

Toggles the aiohttp server log filter and returns its new enabled state.

Classes and namespaces

ClassRolePublic surface
RoutesMethod/path registry.add_route, get_handler, values, mapping/iteration operations.
responsesResponse helper namespace.base, redirect, send_file.
CookieValueCookie value and options.value, max_age, domain, samesite, value comparisons.
CookiesTracked incoming/outgoing cookies.Mapping operations, get, pop, clear.
ServerMain HTTP/WebSocket server.Routing, hooks, errors, events, startup, embedding, dynamic route modules.
MultiServerHost-header dispatcher.add_server, master_handler, startup methods.
ErrorHandlerAsync error callback plus status selector.Callable with (request, exception); supports membership testing by status.
ARouteAsync route wrapper.method, path, function, cache settings, async call.
RouteSync route wrapper.method, path, function, cache settings, call.
PreRouteDeferred global route registration.route, load, class-level routes.
WSEndpointWebSocket route and event registry.route, event, r_event, on_connect_func, connections.
WSConnectionConnected WebSocket peer.send_msg, send_req, check, ping, close.
WSMessageDecoded event envelope.from_msg, from_msg_dict, construct_msg, payload/correlation fields.
PmSocketLegacy/simple browser socket adapter.route, handler, on_disconnect, handle_msg.
TxtParserInternal-facing route-pattern parser.Construct with a pattern, then call it with text to receive named captures.
AiohttpResponseBuffered async client response.get, post, delete, ping, response metadata.

Names beginning with an underscore are implementation details and are intentionally excluded.

Working with the server objects

Create one Server for a routing context. It owns a Routes registry, lifecycle callbacks, and WSEndpoint instances. Each incoming HTTP request receives a selected route in request.route; each accepted event socket becomes a WSConnection. Application messages arrive as the framework's WSMessage, while the separate PmSocket adapter passes aiohttp's native message objects.

Object and constructionUseful stateHow its functions behave
Server(host=None, port=None, loop=None, max_size=None, default_max_age=None)routes, ws_endpoints, runner; connections builds a flattened list of current endpoint connections.route() registers normalized HTTP handlers; quick_route() registers raw handlers. Both return a decorator, whose result is a route object. start_site() is awaited and returns after startup; run() blocks on the event loop. get_app() returns an aiohttp application without starting it.
Routes() (normally server.routes)routes contains method-to-path dictionaries.get_handler(path, method) returns a route or None. Use the exact stored uppercase method; a missing explicit method does not fall back to *. values() returns a list; supplying a method prioritizes that group but still includes other groups. Iteration yields (path, route) pairs.
Route(method, path, f, **kwargs) / ARoute(...)function, method, path, kwargs, is_async, cache settings; parser for brace paths.The decorators construct these wrappers. Calling Route invokes its synchronous function; calling ARoute returns a coroutine to await. Normal Server.route() uses an async outer wrapper even for a synchronous user handler. Cache state belongs to each wrapper.
Cookies(request, default_max_age=None)request, default_max_age; shared tracked cookie state when constructed more than once for a request.get(key, default) and indexing return raw values. Assignment queues a response cookie; pop(key, default) returns/removes a value and queues deletion. clear() queues deletion of tracked keys but does not empty the in-memory mapping. These operations are synchronous.
CookieValue(value, max_age=None, domain=None, samesite=None)The four constructor values are readable/mutable attributes.Assign the object to cookies[key] to apply its options. Missing max_age is filled from the cookie manager default. Equality between two wrappers compares both value and options; ordering compares their values. Use seconds for the object's max_age; datetime/timedelta conversion belongs to tuple assignment.
WSEndpoint(server) via server.create_ws_endpoint()server, connections, events, r_events, route_obj.route(path, method) decorates an async handshake handler and returns that original function. event()/r_event() register by function name and return the function. on_connect_func(callback) returns the callback; on_connect may also be assigned directly.
WSConnection (created on acceptance)ws, original_request, server, ws_endpoint, created, closed.Await send_msg(data, event) to send without waiting for an application reply. Await send_req(data, event, check_interval=10, timeout=2000) for a WSMessage or None; timing is milliseconds. Await close() to clear ws and set closed=True. Remote close removes the connection from the endpoint but does not necessarily update this flag.
WSMessage() and class helpersevent, type, data, response_id; optional chunk metadata.Call WSMessage.from_msg(native_message) or WSMessage.from_msg_dict(envelope) on the class. They return a new decoded message; no network I/O occurs. For ordinary non-chunk messages, strings remain strings, JSON values remain structured, and bytes decode from base64.
PreRoute(func, path, ...) via @PreRoute.route(...)func, args, kwargs, route; shared PreRoute.routes.The decorator replaces the function name with the registration object. registration.load(server) registers it on that server and returns None; calling it again can raise a duplicate-route error.
ErrorHandler(func, status) via @server.error_handler(status)func and the accepted status collection.Membership checks such as 404 in handler inspect the selector. Awaiting handler(request, error) awaits the callback and returns its value. Let the server create and call these objects.
MultiServer(host=None, port=None)servers, host, port, ssl_context.add_server(domain, server) updates the domain map and returns None. master_handler(request) is async and forwards by the Host header without its port. Constructed child servers retain their own routes and cookies.
TxtParser(format_txt, var_chars=["<", ">"], handle_not_found=False, possible_chars=["[", "]"])format_txt, delimiters, compiled regex_format; class switch use_regex.Calling the parser with text returns a dictionary of captured strings or None on no match. Regex matching is case insensitive and normally uses a full match. With handle_not_found=True, unmatched fields can map to None; use a format containing placeholders.
AiohttpResponse via await AiohttpResponse.get/post/delete(...)content bytes, text property, status_code, headers, elapsed timedelta.The async factory reads the body and returns a wrapper. json() and raise_for_status() are synchronous. It is not a reusable session, and its factories should be called on the class.

responses is a helper namespace: call responses.redirect(url), responses.send_file(...), or responses.base(...) on the class. The first two return aiohttp responses synchronously; base aliases aiohttp.web.Response.

Practical object workflows

1. Save a preference and delete it later

Both routes receive the same kind of cookie manager. Assignment is reflected in the response; it does not write server storage. The DELETE route returns the removed raw value.

from aiohttp_ws import Server, CookieValue

server = Server(host="127.0.0.1", port=8080, default_max_age=3600)

@server.route("/theme", method="POST", pass_cookies=True)
async def save_theme(request, cookies):
    body = await request.json()
    theme = body.get("theme")
    if theme not in ("light", "dark"):
        return {"error": "choose light or dark"}, 400
    cookies["theme"] = CookieValue(theme, samesite="Lax")
    return {"theme": cookies.get("theme")}

@server.route("/theme", method="DELETE", pass_cookies=True)
async def remove_theme(request, cookies):
    previous = cookies.pop("theme", None)
    return {"previous": previous}

server.run()

2. Broadcast to current event connections

Add this fragment before server.run(). The endpoint owns the connection list; copy it before awaiting sends so a disconnect cannot change the iterable mid-send. The demonstration HTTP route is public and should receive application authentication before use in a deployed service.

import asyncio

updates = server.create_ws_endpoint()

@updates.route("/events", method="GET")
async def open_events(request):
    return None

@server.route("/broadcast", method="POST")
async def broadcast(request):
    payload = await request.json()
    peers = list(updates.connections)
    results = await asyncio.gather(
        *(peer.send_msg(payload, "UPDATE") for peer in peers),
        return_exceptions=True,
    )
    return {"attempted": len(peers),
            "failed": sum(isinstance(result, Exception) for result in results)}

3. Load one deferred route and inspect registrations

This uses a specific PreRoute object, so unrelated entries in the global registry are not loaded. The decorator returns the object holding the original function.

from aiohttp_ws import Server, PreRoute

@PreRoute.route("/health", method=("GET", "HEAD"))
async def health(request):
    return {"status": "ok"}

server = Server(host="127.0.0.1", port=8080)
health.load(server)
for path, registered in server.routes:
    print(registered.method, path, registered.is_async)

get_route = server.routes.get_handler("/health", "GET")
assert get_route is not None
print(get_route.kwargs)
server.run()

Operational notes and gotchas

  • Import performs work: the updater runs at import, and toggle_badstatusline() installs a global filter on the aiohttp.server logger.
  • Async error handlers: ErrorHandler.__call__ always awaits the callback; register an async function.
  • Hook callbacks: route lifecycle hooks are awaited, except during_requests, which is scheduled in the background.
  • WebSocket lifecycle: WSEndpoint uses its own route wrapper. It does not set request._aiohttp_ws_server before hooks, and a successful upgrade skips the normal after-request response hook. HTTP wrapper behavior should not be assumed for this path.
  • Cookie security options: CookieValue directly models only max_age, domain, and samesite. Use a custom aiohttp response when you need other flags such as secure or httponly.
  • Buffered bodies: both responses.send_file and AiohttpResponse load complete bodies into memory.
  • Timeouts: pass explicit aiohttp timeouts for outbound requests. The wrapper does not add an application-specific default.
  • Route paths: brace parameters use the bundled permissive text parser, not aiohttp router resource semantics.
  • Graceful shutdown: startup methods expose runner; application code is responsible for calling await runner.cleanup() when appropriate.

Complete source API

Generated from modules/aiohttp_ws.py; version 1.1.5. Includes public functions, classes, directly declared methods, properties, and Python protocol methods. Conditional APIs may require optional dependencies. Inherited members and dynamically assigned attributes are explained in the guide where relevant.

Signatures and docstrings are extracted without importing or running the module. A property or AsyncProperty decorator changes how a member is accessed; see its decorators and the guide.

Classes and objects

Module functions

ts(dt=None)

Source line 107

ParameterPassing conventionDefault / required
dtpositional or keywordNone
from_ts(t)

Source line 111

ParameterPassing conventionDefault / required
tpositional or keywordrequired
class Routes

Source line 157

Construct: Routes()

Fields assigned by the constructor: routes. Some assignments may be conditional; see the object guide for meaning and lifecycle.

Declared functions, properties, and nested objects:

Routes.__init__(self)

Source line 158

No caller-supplied parameters are declared.

Routes.add_route(self, path, handler, method='*')

Source line 163

ParameterPassing conventionDefault / required
pathpositional or keywordrequired
handlerpositional or keywordrequired
methodpositional or keyword'*'
Routes.get_handler(self, path, method='*')

Source line 168

ParameterPassing conventionDefault / required
pathpositional or keywordrequired
methodpositional or keyword'*'
Routes.values(self, method='*')

Source line 176

ParameterPassing conventionDefault / required
methodpositional or keyword'*'
Routes.__getitem__(self, key)

Source line 189

ParameterPassing conventionDefault / required
keypositional or keywordrequired
Routes.__setitem__(self, key, value)

Source line 195

ParameterPassing conventionDefault / required
keypositional or keywordrequired
valuepositional or keywordrequired
Routes.__contains__(self, key)

Source line 200

ParameterPassing conventionDefault / required
keypositional or keywordrequired
Routes.__iter__(self)

Source line 205

No caller-supplied parameters are declared.

Routes.__getattr__(self, key)

Source line 213

ParameterPassing conventionDefault / required
keypositional or keywordrequired
class responses

Source line 216

No constructor is declared here. Some utility classes group functions for direct class access; use the call style shown in the guide.

Declared functions, properties, and nested objects:

responses.redirect(url)

Source line 219

Redirect response to given url.
ParameterPassing conventionDefault / required
urlpositional or keywordrequired
responses.send_file(filename_or_fp, mimetype=None, as_attachment=False, attachment_filename=None, max_age=None)

Source line 223

File response containing given file.

filename_or_fp - files name or path, or buffer.

mimetype - What to put in content type header. By default, will be `application/<file extention>`.

as_attachment - Whether or not to have the file get downloaded.

attachment_filename - File name to set for attachment rather than the actual file name.
ParameterPassing conventionDefault / required
filename_or_fppositional or keywordrequired
mimetypepositional or keywordNone
as_attachmentpositional or keywordFalse
attachment_filenamepositional or keywordNone
max_agepositional or keywordNone
class CookieValue

Source line 280

Construct: CookieValue(value, max_age=None, domain=None, samesite=None, _cookies=None)

Fields assigned by the constructor: domain, max_age, samesite, value. Some assignments may be conditional; see the object guide for meaning and lifecycle.

Declared functions, properties, and nested objects:

CookieValue.__init__(self, value, max_age=None, domain=None, samesite=None, _cookies=None)

Source line 281

ParameterPassing conventionDefault / required
valuepositional or keywordrequired
max_agepositional or keywordNone
domainpositional or keywordNone
samesitepositional or keywordNone
_cookiespositional or keywordNone
CookieValue.__eq__(self, other)

Source line 296

ParameterPassing conventionDefault / required
otherpositional or keywordrequired
CookieValue.__repr__(self)

Source line 300

No caller-supplied parameters are declared.

CookieValue.__gt__(self, other)

Source line 302

ParameterPassing conventionDefault / required
otherpositional or keywordrequired
CookieValue.__lt__(self, other)

Source line 306

ParameterPassing conventionDefault / required
otherpositional or keywordrequired
CookieValue.__le__(self, other)

Source line 310

ParameterPassing conventionDefault / required
otherpositional or keywordrequired
CookieValue.__ge__(self, other)

Source line 314

ParameterPassing conventionDefault / required
otherpositional or keywordrequired
class Cookies

Source line 321

Construct: Cookies(request, default_max_age=None)

Fields assigned by the constructor: default_max_age, request. Some assignments may be conditional; see the object guide for meaning and lifecycle.

Declared functions, properties, and nested objects:

Cookies.__init__(self, request, default_max_age=None)

Source line 322

ParameterPassing conventionDefault / required
requestpositional or keywordrequired
default_max_agepositional or keywordNone
Cookies.__delitem__(self, key)

Source line 342

ParameterPassing conventionDefault / required
keypositional or keywordrequired
Cookies.__getitem__(self, key)

Source line 346

ParameterPassing conventionDefault / required
keypositional or keywordrequired
Cookies.__setitem__(self, key, value)

Source line 348

ParameterPassing conventionDefault / required
keypositional or keywordrequired
valuepositional or keywordrequired
Cookies.__contains__(self, i)

Source line 387

ParameterPassing conventionDefault / required
ipositional or keywordrequired
Cookies.get(self, key, default=None)

Source line 396

ParameterPassing conventionDefault / required
keypositional or keywordrequired
defaultpositional or keywordNone
Cookies.pop(self, key, value=None)

Source line 401

ParameterPassing conventionDefault / required
keypositional or keywordrequired
valuepositional or keywordNone
Cookies.clear(self)

Source line 408

No caller-supplied parameters are declared.

class Server

Source line 413

Construct: Server(host=None, port=None, loop=None, max_size=None, default_max_age=None)

Fields assigned by the constructor: app, default_max_age, default_status, error_handlers, events, host, loop, max_msg_size, port, r_events, routes, runner, ssl_context, ws_endpoints. Some assignments may be conditional; see the object guide for meaning and lifecycle.

Declared functions, properties, and nested objects:

Server.__init__(self, host=None, port=None, loop=None, max_size=None, default_max_age=None)

Source line 414

Represents the Server.

host - specify host for the server (str)

port - specify port for the server (port as int)

loop - specify asyncio event loop to run the server on

default_max_age - specify default max age for cookies (int)
ParameterPassing conventionDefault / required
hostpositional or keywordNone
portpositional or keywordNone
looppositional or keywordNone
max_sizepositional or keywordNone
default_max_agepositional or keywordNone
async Server.master_handler(self, request)

Source line 501

ParameterPassing conventionDefault / required
requestpositional or keywordrequired

Declared with async def. Normal calls return an awaitable, or an async generator if the body yields. Decorated properties may be accessed differently; follow the object guide.

Server.create_ws_endpoint(self, f=None)

Source line 532

Create a websocket endpoint
ParameterPassing conventionDefault / required
fpositional or keywordNone
Server.connections(self)

Source line 538

Decorators: @property

List of all websocket connections as `WSConnection` objects.

No caller-supplied parameters are declared.

Server.before_requests(self)

Source line 546

Decorators: @property

No caller-supplied parameters are declared.

Server.before_requests(self, value)

Source line 549

Decorators: @before_requests.setter

ParameterPassing conventionDefault / required
valuepositional or keywordrequired
Server.during_requests(self)

Source line 555

Decorators: @property

No caller-supplied parameters are declared.

Server.during_requests(self, value)

Source line 558

Decorators: @before_requests.setter

ParameterPassing conventionDefault / required
valuepositional or keywordrequired
Server.after_requests(self)

Source line 563

Decorators: @property

No caller-supplied parameters are declared.

Server.after_requests(self, value)

Source line 566

Decorators: @before_requests.setter

ParameterPassing conventionDefault / required
valuepositional or keywordrequired
Server.before_requests_dec(self, value)

Source line 570

Decorator for function to be run before a request is processed by endpoint.

value - calllable taking 1 arg, a request.

If returns anything that isnt `NoneType`, it should be a response. Will process through
after_requests function (if set), then will return the response, instead of processing
through route function.
ParameterPassing conventionDefault / required
valuepositional or keywordrequired
Server.during_requests_dec(self, value)

Source line 580

Decorator for function to be run as a task while the request is being processed by endpoint.

value - calllable taking 1 arg, a request.
ParameterPassing conventionDefault / required
valuepositional or keywordrequired
Server.after_requests_dec(self, value)

Source line 586

Decorator for function to be run before a request is processed by endpoint.

value - callable taking 2 args, to take a request and a response.

If returns anything that isnt `NoneType`, it should be a response. Returning None
results in original response being sent, otherwise it will parse and return the new/modified
response.
ParameterPassing conventionDefault / required
valuepositional or keywordrequired
Server.internal_error_dec(self, value)

Source line 596

Decorator for function to be run if a request errors.

value - callable taking 2 args, to take a request and a error.
ParameterPassing conventionDefault / required
valuepositional or keywordrequired
Server.r_event(self)

Source line 624

No caller-supplied parameters are declared.

Server.event(self)

Source line 632

No caller-supplied parameters are declared.

Server.route(self, route, method='*', cache_time=None, server_cache_time=None, pass_cookies=False, **kwargs)

Source line 730

Decorator to set a function for a request to be processed through.
Route can return 1 arg, or 2 args. The first arg is the content to return,
and the seconds would be the status code as an integer. If not specified, it will
use the default status.

method - One HTTP method string or an iterable of strings, e.g. ("GET", "POST"). Defaults to "*" (all methods).

cache_time - `int` representing amount of seconds to tell the user browser to cache for, if cache-control header isnt specified already.

server_cache_time - `int` representing amount of seconds the server caches any response content generated. Note that headers from cached response will be gone.

You may return any of the following as the first arg:

- An `aiohttp.web_response.Response` object

- `str` - Returns `text/html` mimetype

- `NoneType` - Returns No Content response

- `bytes` -  Returns `bytes` as body

- `dict` - Return dict in JSON format, with mimetype `application/json`
ParameterPassing conventionDefault / required
routepositional or keywordrequired
methodpositional or keyword'*'
cache_timepositional or keywordNone
server_cache_timepositional or keywordNone
pass_cookiespositional or keywordFalse
kwargsextra keyword arguments (**kwargs)optional collection
Server.quick_route(self, route, method='*', cache_time=None)

Source line 763

Register a raw response handler for a method string or iterable of strings.
ParameterPassing conventionDefault / required
routepositional or keywordrequired
methodpositional or keyword'*'
cache_timepositional or keywordNone
Server.error_handler(self, status: int)

Source line 774

Decorator to set a error handler.
ParameterPassing conventionDefault / required
status: intpositional or keywordrequired
Server.create_loop(self, coro)

Source line 788

Create a loop that will run server when started.
ParameterPassing conventionDefault / required
coropositional or keywordrequired
Server.run(self, coro=None)

Source line 839

Run the server.
ParameterPassing conventionDefault / required
coropositional or keywordNone
async Server.start_site(self)

Source line 843

No caller-supplied parameters are declared.

Declared with async def. Normal calls return an awaitable, or an async generator if the body yields. Decorated properties may be accessed differently; follow the object guide.

async Server.run_site(self)

Source line 852

No caller-supplied parameters are declared.

Declared with async def. Normal calls return an awaitable, or an async generator if the body yields. Decorated properties may be accessed differently; follow the object guide.

Server.to_thread(self)

Source line 881

Run the server on a seperate thread.

No caller-supplied parameters are declared.

Server.get_app(self)

Source line 910

No caller-supplied parameters are declared.

Server.import_module(self, module_name)

Source line 915

ParameterPassing conventionDefault / required
module_namepositional or keywordrequired
Server.__getattr__(self, name)

Source line 926

ParameterPassing conventionDefault / required
namepositional or keywordrequired
class MultiServer

Source line 930

Construct: MultiServer(host=None, port=None)

Fields assigned by the constructor: host, port, servers, ssl_context. Some assignments may be conditional; see the object guide for meaning and lifecycle.

Declared functions, properties, and nested objects:

MultiServer.__init__(self, host=None, port=None)

Source line 931

ParameterPassing conventionDefault / required
hostpositional or keywordNone
portpositional or keywordNone
MultiServer.add_server(self, domain, server)

Source line 937

ParameterPassing conventionDefault / required
domainpositional or keywordrequired
serverpositional or keywordrequired
async MultiServer.master_handler(self, request)

Source line 942

ParameterPassing conventionDefault / required
requestpositional or keywordrequired

Declared with async def. Normal calls return an awaitable, or an async generator if the body yields. Decorated properties may be accessed differently; follow the object guide.

MultiServer.create_loop(self, coro)

Source line 952

Create a loop that will run server when started.
ParameterPassing conventionDefault / required
coropositional or keywordrequired
MultiServer.run(self, coro=None)

Source line 1007

Run the server.
ParameterPassing conventionDefault / required
coropositional or keywordNone
async MultiServer.start_site(self)

Source line 1011

No caller-supplied parameters are declared.

Declared with async def. Normal calls return an awaitable, or an async generator if the body yields. Decorated properties may be accessed differently; follow the object guide.

async MultiServer.run_site(self)

Source line 1024

No caller-supplied parameters are declared.

Declared with async def. Normal calls return an awaitable, or an async generator if the body yields. Decorated properties may be accessed differently; follow the object guide.

class ErrorHandler

Source line 1060

Construct: ErrorHandler(func, status)

Fields assigned by the constructor: func, status. Some assignments may be conditional; see the object guide for meaning and lifecycle.

Declared functions, properties, and nested objects:

ErrorHandler.__init__(self, func, status)

Source line 1061

ParameterPassing conventionDefault / required
funcpositional or keywordrequired
statuspositional or keywordrequired
async ErrorHandler.__call__(self, request, ex)

Source line 1070

ParameterPassing conventionDefault / required
requestpositional or keywordrequired
expositional or keywordrequired

Declared with async def. Normal calls return an awaitable, or an async generator if the body yields. Decorated properties may be accessed differently; follow the object guide.

ErrorHandler.__contains__(self, other)

Source line 1072

ParameterPassing conventionDefault / required
otherpositional or keywordrequired
class ARoute

Source line 1084

Construct: ARoute(method, path, f, **kwargs)

Fields assigned by the constructor: cache_time, function, is_async, kwargs, method, parser, pass_cookies, path, server_cache_time. Some assignments may be conditional; see the object guide for meaning and lifecycle.

Declared functions, properties, and nested objects:

ARoute.__init__(self, method, path, f, **kwargs)

Source line 1085

ParameterPassing conventionDefault / required
methodpositional or keywordrequired
pathpositional or keywordrequired
fpositional or keywordrequired
kwargsextra keyword arguments (**kwargs)optional collection
async ARoute.__call__(self, *args, **kwargs)

Source line 1116

ParameterPassing conventionDefault / required
argsextra positional arguments (*args)optional collection
kwargsextra keyword arguments (**kwargs)optional collection

Declared with async def. Normal calls return an awaitable, or an async generator if the body yields. Decorated properties may be accessed differently; follow the object guide.

ARoute.__eq__(self, other)

Source line 1133

ParameterPassing conventionDefault / required
otherpositional or keywordrequired
class Route

Source line 1137

Construct: Route(method, path, f, **kwargs)

Fields assigned by the constructor: cache_time, function, is_async, kwargs, method, parser, pass_cookies, path, server_cache_time. Some assignments may be conditional; see the object guide for meaning and lifecycle.

Declared functions, properties, and nested objects:

Route.__init__(self, method, path, f, **kwargs)

Source line 1138

ParameterPassing conventionDefault / required
methodpositional or keywordrequired
pathpositional or keywordrequired
fpositional or keywordrequired
kwargsextra keyword arguments (**kwargs)optional collection
Route.__call__(self, *args, **kwargs)

Source line 1169

ParameterPassing conventionDefault / required
argsextra positional arguments (*args)optional collection
kwargsextra keyword arguments (**kwargs)optional collection
Route.__eq__(self, other)

Source line 1187

ParameterPassing conventionDefault / required
otherpositional or keywordrequired
class PreRoute

Source line 1195

Construct: PreRoute(func, *args, **kwargs)

Fields assigned by the constructor: args, func, kwargs, route. Some assignments may be conditional; see the object guide for meaning and lifecycle.

Declared functions, properties, and nested objects:

PreRoute.__init__(self, func, *args, **kwargs)

Source line 1197

ParameterPassing conventionDefault / required
funcpositional or keywordrequired
argsextra positional arguments (*args)optional collection
kwargsextra keyword arguments (**kwargs)optional collection
PreRoute.load(self, server)

Source line 1202

ParameterPassing conventionDefault / required
serverpositional or keywordrequired
PreRoute.route(route, method='*', cache_time=None, server_cache_time=None, pass_cookies=False, **kwargs)

Source line 1205

Decorator to set a function for a request to be processed through.
Route can return 1 arg, or 2 args. The first arg is the content to return,
and the seconds would be the status code as an integer. If not specified, it will
use the default status.

method - One HTTP method string or an iterable of strings, e.g. ("GET", "POST"). Defaults to "*" (all methods).

cache_time - `int` representing amount of seconds to tell the user browser to cache for, if cache-control header isnt specified already.

server_cache_time - `int` representing amount of seconds the server caches any response content generated. Note that headers from cached response will be gone.

You may return any of the following as the first arg:

- An `aiohttp.web_response.Response` object

- `str` - Returns `text/html` mimetype

- `NoneType` - Returns No Content response

- `bytes` -  Returns `bytes` as body

- `dict` - Return dict in JSON format, with mimetype `application/json`
ParameterPassing conventionDefault / required
routepositional or keywordrequired
methodpositional or keyword'*'
cache_timepositional or keywordNone
server_cache_timepositional or keywordNone
pass_cookiespositional or keywordFalse
kwargsextra keyword arguments (**kwargs)optional collection
class WSEndpoint

Source line 1240

Construct: WSEndpoint(server)

Fields assigned by the constructor: connections, events, r_events, route_obj, server. Some assignments may be conditional; see the object guide for meaning and lifecycle.

Declared functions, properties, and nested objects:

WSEndpoint.__init__(self, server)

Source line 1241

ParameterPassing conventionDefault / required
serverpositional or keywordrequired
WSEndpoint.on_connect(self)

Source line 1253

Decorators: @property

No caller-supplied parameters are declared.

WSEndpoint.on_connect(self, value)

Source line 1256

Decorators: @on_connect.setter

ParameterPassing conventionDefault / required
valuepositional or keywordrequired
WSEndpoint.on_connect_func(self, value)

Source line 1260

ParameterPassing conventionDefault / required
valuepositional or keywordrequired
WSEndpoint.r_event(self)

Source line 1268

No caller-supplied parameters are declared.

WSEndpoint.event(self)

Source line 1276

No caller-supplied parameters are declared.

WSEndpoint.route(self, route, method='*')

Source line 1283

ParameterPassing conventionDefault / required
routepositional or keywordrequired
methodpositional or keyword'*'
class WSConnection

Source line 1378

Construct: WSConnection(ws, request, ws_endpoint)

Fields assigned by the constructor: closed, constructs, created, events, original_request, r_events, reqs, server, ws, ws_endpoint. Some assignments may be conditional; see the object guide for meaning and lifecycle.

Declared functions, properties, and nested objects:

WSConnection.__init__(self, ws, request, ws_endpoint)

Source line 1379

ParameterPassing conventionDefault / required
wspositional or keywordrequired
requestpositional or keywordrequired
ws_endpointpositional or keywordrequired
WSConnection.__eq__(self, other)

Source line 1390

ParameterPassing conventionDefault / required
otherpositional or keywordrequired
async WSConnection.close(self)

Source line 1394

No caller-supplied parameters are declared.

Declared with async def. Normal calls return an awaitable, or an async generator if the body yields. Decorated properties may be accessed differently; follow the object guide.

async WSConnection.send_req(self, data, event, check_interval=10, timeout=2000)

Source line 1400

ParameterPassing conventionDefault / required
datapositional or keywordrequired
eventpositional or keywordrequired
check_intervalpositional or keyword10
timeoutpositional or keyword2000

Declared with async def. Normal calls return an awaitable, or an async generator if the body yields. Decorated properties may be accessed differently; follow the object guide.

async WSConnection.send_msg(self, data, event, msg_dict=None)

Source line 1427

ParameterPassing conventionDefault / required
datapositional or keywordrequired
eventpositional or keywordrequired
msg_dictpositional or keywordNone

Declared with async def. Normal calls return an awaitable, or an async generator if the body yields. Decorated properties may be accessed differently; follow the object guide.

async WSConnection.check(self, raw_msg)

Source line 1459

ParameterPassing conventionDefault / required
raw_msgpositional or keywordrequired

Declared with async def. Normal calls return an awaitable, or an async generator if the body yields. Decorated properties may be accessed differently; follow the object guide.

async WSConnection.ping(self, msg_size=0, trial_count=1, send_as_bytes=False, timeout=1000, interval=0.5)

Source line 1527

ParameterPassing conventionDefault / required
msg_sizepositional or keyword0
trial_countpositional or keyword1
send_as_bytespositional or keywordFalse
timeoutpositional or keyword1000
intervalpositional or keyword0.5

Declared with async def. Normal calls return an awaitable, or an async generator if the body yields. Decorated properties may be accessed differently; follow the object guide.

class WSMessage

Source line 1539

Represents a websocket message.

Construct: WSMessage()

Fields assigned by the constructor: construct_final, construct_id, construct_index, data, event, msg, msg_type, response_id, type. Some assignments may be conditional; see the object guide for meaning and lifecycle.

Declared functions, properties, and nested objects:

WSMessage.json_load(s)

Source line 1541

ParameterPassing conventionDefault / required
spositional or keywordrequired
WSMessage.__init__(self)

Source line 1543

No caller-supplied parameters are declared.

WSMessage.__repr__(self)

Source line 1555

No caller-supplied parameters are declared.

WSMessage.construct_msg(msg_list)

Source line 1557

ParameterPassing conventionDefault / required
msg_listpositional or keywordrequired
WSMessage.from_msg(msg)

Source line 1576

ParameterPassing conventionDefault / required
msgpositional or keywordrequired
WSMessage.from_msg_dict(msg_dict)

Source line 1604

ParameterPassing conventionDefault / required
msg_dictpositional or keywordrequired
class PmSocket

Source line 1632

Construct: PmSocket(server)

Fields assigned by the constructor: server. Some assignments may be conditional; see the object guide for meaning and lifecycle.

Declared functions, properties, and nested objects:

PmSocket.__init__(self, server)

Source line 1633

Initializes the PmSocket object with the specified server instance.

Parameters:
- server: The server instance to which this PmSocket instance is attached.
ParameterPassing conventionDefault / required
serverpositional or keywordrequired
PmSocket.route(self, route, method='*', cache_time=None, server_cache_time=None, pass_cookies=False, **kwargs)

Source line 1644

Decorator to set a function for a request to be processed through.
Route can return 1 arg, or 2 args. The first arg is the content to return,
and the seconds would be the status code as an integer. If not specified, it will
use the default status.

Parameters:
- route: The URL route to be handled by the decorated function.
- method: What HTTP methods to accept (default is "*").
- cache_time: int representing the amount of seconds to tell the user browser to cache for, if cache-control header isn't specified already.
- server_cache_time: int representing the amount of seconds the server caches any response content generated. Note that headers from cached responses will be gone.
- pass_cookies: Boolean indicating whether to pass cookies.

You may return any of the following as the first arg:

- An `aiohttp.web_response.Response` object

- `str` - Returns `text/html` mimetype

- `NoneType` - Returns websocket response

- `bytes` -  Returns `bytes` as body

- `dict` - Return dict in JSON format, with mimetype `application/json`
ParameterPassing conventionDefault / required
routepositional or keywordrequired
methodpositional or keyword'*'
cache_timepositional or keywordNone
server_cache_timepositional or keywordNone
pass_cookiespositional or keywordFalse
kwargsextra keyword arguments (**kwargs)optional collection
PmSocket.handler(self, f)

Source line 1694

Decorator that passes received WebSocket messages to the attached async function.
The function receives the WebSocket object and the message object as parameters.

Parameters:
- f: The function to be set as the handler.
ParameterPassing conventionDefault / required
fpositional or keywordrequired
PmSocket.on_disconnect(self, f)

Source line 1704

Decorator that sets the given function as the handler for when a WebSocket connection is closed.

Parameters:
- f: The function to be set as the handler.
ParameterPassing conventionDefault / required
fpositional or keywordrequired
PmSocket.__call__(self, f)

Source line 1713

Sets the given function as the handler for processing WebSocket messages.
It allows the instance to be used as a decorator.

Parameters:
- f: The function to be set as the handler.
ParameterPassing conventionDefault / required
fpositional or keywordrequired
async PmSocket.handle_msg(self, ws, msg)

Source line 1723

Handles incoming WebSocket messages. Meant for backend usage. Responds to ::ping:: messages with ::pong::
and closes the WebSocket connection on ::disconnect:: messages. Calls the function
set by the handler method to process other messages.

Parameters:
- ws: The WebSocket connection.
- msg: The message received from the WebSocket.
ParameterPassing conventionDefault / required
wspositional or keywordrequired
msgpositional or keywordrequired

Declared with async def. Normal calls return an awaitable, or an async generator if the body yields. Decorated properties may be accessed differently; follow the object guide.

class TxtParser

Source line 1744

Construct: TxtParser(format_txt, var_chars=['<', '>'], handle_not_found=False, possible_chars=['[', ']'])

Fields assigned by the constructor: format_txt, formats, handle_not_found, possible_chars, regex_format, var_chars. Some assignments may be conditional; see the object guide for meaning and lifecycle.

Declared functions, properties, and nested objects:

TxtParser.__init__(self, format_txt, var_chars=['<', '>'], handle_not_found=False, possible_chars=['[', ']'])

Source line 1750

ParameterPassing conventionDefault / required
format_txtpositional or keywordrequired
var_charspositional or keyword['<', '>']
handle_not_foundpositional or keywordFalse
possible_charspositional or keyword['[', ']']
TxtParser.__call__(self, txt, **kwargs)

Source line 1813

ParameterPassing conventionDefault / required
txtpositional or keywordrequired
kwargsextra keyword arguments (**kwargs)optional collection
class AiohttpResponse

Source line 1904

Allows for requests to be done similar to
requests module w/ aiohttp, with response object being

Construct: AiohttpResponse(r, elapsed, data)

Fields assigned by the constructor: content, elapsed. Some assignments may be conditional; see the object guide for meaning and lifecycle.

Declared functions, properties, and nested objects:

AiohttpResponse.__init__(self, r, elapsed, data)

Source line 1910

ParameterPassing conventionDefault / required
rpositional or keywordrequired
elapsedpositional or keywordrequired
datapositional or keywordrequired
AiohttpResponse.raise_for_status(self)

Source line 1938

No caller-supplied parameters are declared.

AiohttpResponse.json(self)

Source line 1940

Get json content as a dictionary.

No caller-supplied parameters are declared.

AiohttpResponse.text(self)

Source line 1944

Decorators: @property

Get content as a string

No caller-supplied parameters are declared.

async AiohttpResponse.get(*args, **kwargs)

Source line 1949

Make a GET request via aiohttp.
ParameterPassing conventionDefault / required
argsextra positional arguments (*args)optional collection
kwargsextra keyword arguments (**kwargs)optional collection

Declared with async def. Normal calls return an awaitable, or an async generator if the body yields. Decorated properties may be accessed differently; follow the object guide.

async AiohttpResponse.post(*args, **kwargs)

Source line 1959

Make a POST request via aiohttp.
ParameterPassing conventionDefault / required
argsextra positional arguments (*args)optional collection
kwargsextra keyword arguments (**kwargs)optional collection

Declared with async def. Normal calls return an awaitable, or an async generator if the body yields. Decorated properties may be accessed differently; follow the object guide.

async AiohttpResponse.delete(*args, **kwargs)

Source line 1969

Make a DELETE request via aiohttp.
ParameterPassing conventionDefault / required
argsextra positional arguments (*args)optional collection
kwargsextra keyword arguments (**kwargs)optional collection

Declared with async def. Normal calls return an awaitable, or an async generator if the body yields. Decorated properties may be accessed differently; follow the object guide.

async AiohttpResponse.ping(*args, **kwargs)

Source line 1979

Make a GET request without loading all of page content.
ParameterPassing conventionDefault / required
argsextra positional arguments (*args)optional collection
kwargsextra keyword arguments (**kwargs)optional collection

Declared with async def. Normal calls return an awaitable, or an async generator if the body yields. Decorated properties may be accessed differently; follow the object guide.

toggle_badstatusline()

Source line 1998

No caller-supplied parameters are declared.