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.
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()
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
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 / attribute | Meaning |
|---|---|
host, port | Bind address and TCP port used by the run helpers. |
loop | Optional asyncio event loop. When omitted, the startup helper gets the current loop or creates one. |
max_size | Accepted for compatibility. The current constructor does not apply this value. |
default_max_age | Default lifetime in seconds for values set through Cookies. |
default_status | Status used when route output omits one; initialized to 200. |
max_msg_size | Maximum HTTP/WebSocket message size; defaults to 4 MiB. |
ssl_context | Assign an ssl.SSLContext before starting to enable TLS in supported run modes. |
routes | Routes registry holding all HTTP and WebSocket route wrappers. |
ws_endpoints / connections | Registered WebSocket endpoints and a flattened read-only connection list. |
runner, app | Populated 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 return | Response behavior |
|---|---|
dict or list | JSON response with application/json. |
str or int | Text response with text/html. |
bytes | Raw response body. |
None | Empty response with status 204. |
aiohttp.web.Response | Returned unchanged. |
(value, status) | Normalizes value using the rules above and uses the integer status. |
| Other object | Passed through unchanged; it must be acceptable to aiohttp. |
Cache controls
cache_timeaddsCache-Control: max-age=<seconds>, publicunless the response already has that header.server_cache_timecaches 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
| Hook | Signature | Behavior |
|---|---|---|
before_requests | async (request) | Runs before the route. A non-None return short-circuits the route but still flows through the after hook. |
during_requests | async (request) | Started with asyncio.create_task; it is not awaited before the response. |
after_requests | async (request, response) | Runs after normalization. Return None to keep the response or return a replacement value/tuple. |
internal_error_dec | async (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"}
*_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.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.
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.
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
| Method | Use |
|---|---|
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
}
| Field | Meaning |
|---|---|
event | Dispatch key. RESPONSE is reserved for correlated replies; PING is registered automatically as a response event. |
type | string, bytes (base64 on the wire), or json. |
data | Decoded payload exposed as WSMessage.data. |
response_id | Correlation ID generated by send_req(). |
construct_* | Chunk metadata used to rebuild a larger logical message. |
WSConnection
| Method | Behavior |
|---|---|
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")
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())
| Member | Meaning |
|---|---|
get, post, delete | Async helpers forwarding arguments to aiohttp.request. |
ping | Opens 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, reason | Status metadata. |
headers, cookies, links, history | Response metadata copied from aiohttp. |
url, request, raw, elapsed | Final URL, request info, underlying response, and measured duration. |
encoding, apparent_encoding, charset, content_type | Decoding and content-type metadata. |
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
| Class | Role | Public surface |
|---|---|---|
Routes | Method/path registry. | add_route, get_handler, values, mapping/iteration operations. |
responses | Response helper namespace. | base, redirect, send_file. |
CookieValue | Cookie value and options. | value, max_age, domain, samesite, value comparisons. |
Cookies | Tracked incoming/outgoing cookies. | Mapping operations, get, pop, clear. |
Server | Main HTTP/WebSocket server. | Routing, hooks, errors, events, startup, embedding, dynamic route modules. |
MultiServer | Host-header dispatcher. | add_server, master_handler, startup methods. |
ErrorHandler | Async error callback plus status selector. | Callable with (request, exception); supports membership testing by status. |
ARoute | Async route wrapper. | method, path, function, cache settings, async call. |
Route | Sync route wrapper. | method, path, function, cache settings, call. |
PreRoute | Deferred global route registration. | route, load, class-level routes. |
WSEndpoint | WebSocket route and event registry. | route, event, r_event, on_connect_func, connections. |
WSConnection | Connected WebSocket peer. | send_msg, send_req, check, ping, close. |
WSMessage | Decoded event envelope. | from_msg, from_msg_dict, construct_msg, payload/correlation fields. |
PmSocket | Legacy/simple browser socket adapter. | route, handler, on_disconnect, handle_msg. |
TxtParser | Internal-facing route-pattern parser. | Construct with a pattern, then call it with text to receive named captures. |
AiohttpResponse | Buffered 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 construction | Useful state | How 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 helpers | event, 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 theaiohttp.serverlogger. - 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:
WSEndpointuses its own route wrapper. It does not setrequest._aiohttp_ws_serverbefore 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:
CookieValuedirectly models onlymax_age,domain, andsamesite. Use a custom aiohttp response when you need other flags such assecureorhttponly. - Buffered bodies: both
responses.send_fileandAiohttpResponseload 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 callingawait 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
RoutesresponsesCookieValueCookiesServerMultiServerErrorHandlerARouteRoutePreRouteWSEndpointWSConnectionWSMessagePmSocketTxtParserAiohttpResponse
Module functions
ts(dt=None)
Source line 107
| Parameter | Passing convention | Default / required |
|---|---|---|
dt | positional or keyword | None |
from_ts(t)
Source line 111
| Parameter | Passing convention | Default / required |
|---|---|---|
t | positional or keyword | required |
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__— methodRoutes.add_route— methodRoutes.get_handler— methodRoutes.values— methodRoutes.__getitem__— methodRoutes.__setitem__— methodRoutes.__contains__— methodRoutes.__iter__— methodRoutes.__getattr__— method
Routes.__init__(self)
Source line 158
No caller-supplied parameters are declared.
Routes.add_route(self, path, handler, method='*')
Source line 163
| Parameter | Passing convention | Default / required |
|---|---|---|
path | positional or keyword | required |
handler | positional or keyword | required |
method | positional or keyword | '*' |
Routes.get_handler(self, path, method='*')
Source line 168
| Parameter | Passing convention | Default / required |
|---|---|---|
path | positional or keyword | required |
method | positional or keyword | '*' |
Routes.values(self, method='*')
Source line 176
| Parameter | Passing convention | Default / required |
|---|---|---|
method | positional or keyword | '*' |
Routes.__getitem__(self, key)
Source line 189
| Parameter | Passing convention | Default / required |
|---|---|---|
key | positional or keyword | required |
Routes.__setitem__(self, key, value)
Source line 195
| Parameter | Passing convention | Default / required |
|---|---|---|
key | positional or keyword | required |
value | positional or keyword | required |
Routes.__contains__(self, key)
Source line 200
| Parameter | Passing convention | Default / required |
|---|---|---|
key | positional or keyword | required |
Routes.__iter__(self)
Source line 205
No caller-supplied parameters are declared.
Routes.__getattr__(self, key)
Source line 213
| Parameter | Passing convention | Default / required |
|---|---|---|
key | positional or keyword | required |
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— methodresponses.send_file— method
responses.redirect(url)
Source line 219
Redirect response to given url.
| Parameter | Passing convention | Default / required |
|---|---|---|
url | positional or keyword | required |
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.
| Parameter | Passing convention | Default / required |
|---|---|---|
filename_or_fp | positional or keyword | required |
mimetype | positional or keyword | None |
as_attachment | positional or keyword | False |
attachment_filename | positional or keyword | None |
max_age | positional or keyword | None |
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__— methodCookieValue.__eq__— methodCookieValue.__repr__— methodCookieValue.__gt__— methodCookieValue.__lt__— methodCookieValue.__le__— methodCookieValue.__ge__— method
CookieValue.__init__(self, value, max_age=None, domain=None, samesite=None, _cookies=None)
Source line 281
| Parameter | Passing convention | Default / required |
|---|---|---|
value | positional or keyword | required |
max_age | positional or keyword | None |
domain | positional or keyword | None |
samesite | positional or keyword | None |
_cookies | positional or keyword | None |
CookieValue.__eq__(self, other)
Source line 296
| Parameter | Passing convention | Default / required |
|---|---|---|
other | positional or keyword | required |
CookieValue.__repr__(self)
Source line 300
No caller-supplied parameters are declared.
CookieValue.__gt__(self, other)
Source line 302
| Parameter | Passing convention | Default / required |
|---|---|---|
other | positional or keyword | required |
CookieValue.__lt__(self, other)
Source line 306
| Parameter | Passing convention | Default / required |
|---|---|---|
other | positional or keyword | required |
CookieValue.__le__(self, other)
Source line 310
| Parameter | Passing convention | Default / required |
|---|---|---|
other | positional or keyword | required |
CookieValue.__ge__(self, other)
Source line 314
| Parameter | Passing convention | Default / required |
|---|---|---|
other | positional or keyword | required |
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__— methodCookies.__delitem__— methodCookies.__getitem__— methodCookies.__setitem__— methodCookies.__contains__— methodCookies.get— methodCookies.pop— methodCookies.clear— method
Cookies.__init__(self, request, default_max_age=None)
Source line 322
| Parameter | Passing convention | Default / required |
|---|---|---|
request | positional or keyword | required |
default_max_age | positional or keyword | None |
Cookies.__delitem__(self, key)
Source line 342
| Parameter | Passing convention | Default / required |
|---|---|---|
key | positional or keyword | required |
Cookies.__getitem__(self, key)
Source line 346
| Parameter | Passing convention | Default / required |
|---|---|---|
key | positional or keyword | required |
Cookies.__setitem__(self, key, value)
Source line 348
| Parameter | Passing convention | Default / required |
|---|---|---|
key | positional or keyword | required |
value | positional or keyword | required |
Cookies.__contains__(self, i)
Source line 387
| Parameter | Passing convention | Default / required |
|---|---|---|
i | positional or keyword | required |
Cookies.get(self, key, default=None)
Source line 396
| Parameter | Passing convention | Default / required |
|---|---|---|
key | positional or keyword | required |
default | positional or keyword | None |
Cookies.pop(self, key, value=None)
Source line 401
| Parameter | Passing convention | Default / required |
|---|---|---|
key | positional or keyword | required |
value | positional or keyword | None |
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__— methodServer.master_handler— async methodServer.create_ws_endpoint— methodServer.connections— propertyServer.before_requests— propertyServer.before_requests— property setterServer.during_requests— propertyServer.during_requests— property setterServer.after_requests— propertyServer.after_requests— property setterServer.before_requests_dec— methodServer.during_requests_dec— methodServer.after_requests_dec— methodServer.internal_error_dec— methodServer.r_event— methodServer.event— methodServer.route— methodServer.quick_route— methodServer.error_handler— methodServer.create_loop— methodServer.run— methodServer.start_site— async methodServer.run_site— async methodServer.to_thread— methodServer.get_app— methodServer.import_module— methodServer.__getattr__— method
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)
| Parameter | Passing convention | Default / required |
|---|---|---|
host | positional or keyword | None |
port | positional or keyword | None |
loop | positional or keyword | None |
max_size | positional or keyword | None |
default_max_age | positional or keyword | None |
async Server.master_handler(self, request)
Source line 501
| Parameter | Passing convention | Default / required |
|---|---|---|
request | positional or keyword | required |
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
| Parameter | Passing convention | Default / required |
|---|---|---|
f | positional or keyword | None |
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
| Parameter | Passing convention | Default / required |
|---|---|---|
value | positional or keyword | required |
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
| Parameter | Passing convention | Default / required |
|---|---|---|
value | positional or keyword | required |
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
| Parameter | Passing convention | Default / required |
|---|---|---|
value | positional or keyword | required |
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.
| Parameter | Passing convention | Default / required |
|---|---|---|
value | positional or keyword | required |
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.
| Parameter | Passing convention | Default / required |
|---|---|---|
value | positional or keyword | required |
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.
| Parameter | Passing convention | Default / required |
|---|---|---|
value | positional or keyword | required |
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.
| Parameter | Passing convention | Default / required |
|---|---|---|
value | positional or keyword | required |
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`
| Parameter | Passing convention | Default / required |
|---|---|---|
route | positional or keyword | required |
method | positional or keyword | '*' |
cache_time | positional or keyword | None |
server_cache_time | positional or keyword | None |
pass_cookies | positional or keyword | False |
kwargs | extra 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.
| Parameter | Passing convention | Default / required |
|---|---|---|
route | positional or keyword | required |
method | positional or keyword | '*' |
cache_time | positional or keyword | None |
Server.error_handler(self, status: int)
Source line 774
Decorator to set a error handler.
| Parameter | Passing convention | Default / required |
|---|---|---|
status: int | positional or keyword | required |
Server.create_loop(self, coro)
Source line 788
Create a loop that will run server when started.
| Parameter | Passing convention | Default / required |
|---|---|---|
coro | positional or keyword | required |
Server.run(self, coro=None)
Source line 839
Run the server.
| Parameter | Passing convention | Default / required |
|---|---|---|
coro | positional or keyword | None |
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
| Parameter | Passing convention | Default / required |
|---|---|---|
module_name | positional or keyword | required |
Server.__getattr__(self, name)
Source line 926
| Parameter | Passing convention | Default / required |
|---|---|---|
name | positional or keyword | required |
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__— methodMultiServer.add_server— methodMultiServer.master_handler— async methodMultiServer.create_loop— methodMultiServer.run— methodMultiServer.start_site— async methodMultiServer.run_site— async method
MultiServer.__init__(self, host=None, port=None)
Source line 931
| Parameter | Passing convention | Default / required |
|---|---|---|
host | positional or keyword | None |
port | positional or keyword | None |
MultiServer.add_server(self, domain, server)
Source line 937
| Parameter | Passing convention | Default / required |
|---|---|---|
domain | positional or keyword | required |
server | positional or keyword | required |
async MultiServer.master_handler(self, request)
Source line 942
| Parameter | Passing convention | Default / required |
|---|---|---|
request | positional or keyword | required |
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.
| Parameter | Passing convention | Default / required |
|---|---|---|
coro | positional or keyword | required |
MultiServer.run(self, coro=None)
Source line 1007
Run the server.
| Parameter | Passing convention | Default / required |
|---|---|---|
coro | positional or keyword | None |
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__— methodErrorHandler.__call__— async methodErrorHandler.__contains__— method
ErrorHandler.__init__(self, func, status)
Source line 1061
| Parameter | Passing convention | Default / required |
|---|---|---|
func | positional or keyword | required |
status | positional or keyword | required |
async ErrorHandler.__call__(self, request, ex)
Source line 1070
| Parameter | Passing convention | Default / required |
|---|---|---|
request | positional or keyword | required |
ex | positional or keyword | required |
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
| Parameter | Passing convention | Default / required |
|---|---|---|
other | positional or keyword | required |
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__— methodARoute.__call__— async methodARoute.__eq__— method
ARoute.__init__(self, method, path, f, **kwargs)
Source line 1085
| Parameter | Passing convention | Default / required |
|---|---|---|
method | positional or keyword | required |
path | positional or keyword | required |
f | positional or keyword | required |
kwargs | extra keyword arguments (**kwargs) | optional collection |
async ARoute.__call__(self, *args, **kwargs)
Source line 1116
| Parameter | Passing convention | Default / required |
|---|---|---|
args | extra positional arguments (*args) | optional collection |
kwargs | extra 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
| Parameter | Passing convention | Default / required |
|---|---|---|
other | positional or keyword | required |
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__— methodRoute.__call__— methodRoute.__eq__— method
Route.__init__(self, method, path, f, **kwargs)
Source line 1138
| Parameter | Passing convention | Default / required |
|---|---|---|
method | positional or keyword | required |
path | positional or keyword | required |
f | positional or keyword | required |
kwargs | extra keyword arguments (**kwargs) | optional collection |
Route.__call__(self, *args, **kwargs)
Source line 1169
| Parameter | Passing convention | Default / required |
|---|---|---|
args | extra positional arguments (*args) | optional collection |
kwargs | extra keyword arguments (**kwargs) | optional collection |
Route.__eq__(self, other)
Source line 1187
| Parameter | Passing convention | Default / required |
|---|---|---|
other | positional or keyword | required |
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__— methodPreRoute.load— methodPreRoute.route— method
PreRoute.__init__(self, func, *args, **kwargs)
Source line 1197
| Parameter | Passing convention | Default / required |
|---|---|---|
func | positional or keyword | required |
args | extra positional arguments (*args) | optional collection |
kwargs | extra keyword arguments (**kwargs) | optional collection |
PreRoute.load(self, server)
Source line 1202
| Parameter | Passing convention | Default / required |
|---|---|---|
server | positional or keyword | required |
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`
| Parameter | Passing convention | Default / required |
|---|---|---|
route | positional or keyword | required |
method | positional or keyword | '*' |
cache_time | positional or keyword | None |
server_cache_time | positional or keyword | None |
pass_cookies | positional or keyword | False |
kwargs | extra 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__— methodWSEndpoint.on_connect— propertyWSEndpoint.on_connect— property setterWSEndpoint.on_connect_func— methodWSEndpoint.r_event— methodWSEndpoint.event— methodWSEndpoint.route— method
WSEndpoint.__init__(self, server)
Source line 1241
| Parameter | Passing convention | Default / required |
|---|---|---|
server | positional or keyword | required |
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
| Parameter | Passing convention | Default / required |
|---|---|---|
value | positional or keyword | required |
WSEndpoint.on_connect_func(self, value)
Source line 1260
| Parameter | Passing convention | Default / required |
|---|---|---|
value | positional or keyword | required |
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
| Parameter | Passing convention | Default / required |
|---|---|---|
route | positional or keyword | required |
method | positional 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__— methodWSConnection.__eq__— methodWSConnection.close— async methodWSConnection.send_req— async methodWSConnection.send_msg— async methodWSConnection.check— async methodWSConnection.ping— async method
WSConnection.__init__(self, ws, request, ws_endpoint)
Source line 1379
| Parameter | Passing convention | Default / required |
|---|---|---|
ws | positional or keyword | required |
request | positional or keyword | required |
ws_endpoint | positional or keyword | required |
WSConnection.__eq__(self, other)
Source line 1390
| Parameter | Passing convention | Default / required |
|---|---|---|
other | positional or keyword | required |
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
| Parameter | Passing convention | Default / required |
|---|---|---|
data | positional or keyword | required |
event | positional or keyword | required |
check_interval | positional or keyword | 10 |
timeout | positional or keyword | 2000 |
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
| Parameter | Passing convention | Default / required |
|---|---|---|
data | positional or keyword | required |
event | positional or keyword | required |
msg_dict | positional or keyword | None |
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
| Parameter | Passing convention | Default / required |
|---|---|---|
raw_msg | positional or keyword | required |
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
| Parameter | Passing convention | Default / required |
|---|---|---|
msg_size | positional or keyword | 0 |
trial_count | positional or keyword | 1 |
send_as_bytes | positional or keyword | False |
timeout | positional or keyword | 1000 |
interval | positional or keyword | 0.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— methodWSMessage.__init__— methodWSMessage.__repr__— methodWSMessage.construct_msg— methodWSMessage.from_msg— methodWSMessage.from_msg_dict— method
WSMessage.json_load(s)
Source line 1541
| Parameter | Passing convention | Default / required |
|---|---|---|
s | positional or keyword | required |
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
| Parameter | Passing convention | Default / required |
|---|---|---|
msg_list | positional or keyword | required |
WSMessage.from_msg(msg)
Source line 1576
| Parameter | Passing convention | Default / required |
|---|---|---|
msg | positional or keyword | required |
WSMessage.from_msg_dict(msg_dict)
Source line 1604
| Parameter | Passing convention | Default / required |
|---|---|---|
msg_dict | positional or keyword | required |
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__— methodPmSocket.route— methodPmSocket.handler— methodPmSocket.on_disconnect— methodPmSocket.__call__— methodPmSocket.handle_msg— async method
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.
| Parameter | Passing convention | Default / required |
|---|---|---|
server | positional or keyword | required |
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`
| Parameter | Passing convention | Default / required |
|---|---|---|
route | positional or keyword | required |
method | positional or keyword | '*' |
cache_time | positional or keyword | None |
server_cache_time | positional or keyword | None |
pass_cookies | positional or keyword | False |
kwargs | extra 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.
| Parameter | Passing convention | Default / required |
|---|---|---|
f | positional or keyword | required |
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.
| Parameter | Passing convention | Default / required |
|---|---|---|
f | positional or keyword | required |
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.
| Parameter | Passing convention | Default / required |
|---|---|---|
f | positional or keyword | required |
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.
| Parameter | Passing convention | Default / required |
|---|---|---|
ws | positional or keyword | required |
msg | positional or keyword | required |
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__— methodTxtParser.__call__— method
TxtParser.__init__(self, format_txt, var_chars=['<', '>'], handle_not_found=False, possible_chars=['[', ']'])
Source line 1750
| Parameter | Passing convention | Default / required |
|---|---|---|
format_txt | positional or keyword | required |
var_chars | positional or keyword | ['<', '>'] |
handle_not_found | positional or keyword | False |
possible_chars | positional or keyword | ['[', ']'] |
TxtParser.__call__(self, txt, **kwargs)
Source line 1813
| Parameter | Passing convention | Default / required |
|---|---|---|
txt | positional or keyword | required |
kwargs | extra 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__— methodAiohttpResponse.raise_for_status— methodAiohttpResponse.json— methodAiohttpResponse.text— propertyAiohttpResponse.get— async methodAiohttpResponse.post— async methodAiohttpResponse.delete— async methodAiohttpResponse.ping— async method
AiohttpResponse.__init__(self, r, elapsed, data)
Source line 1910
| Parameter | Passing convention | Default / required |
|---|---|---|
r | positional or keyword | required |
elapsed | positional or keyword | required |
data | positional or keyword | required |
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.
| Parameter | Passing convention | Default / required |
|---|---|---|
args | extra positional arguments (*args) | optional collection |
kwargs | extra 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.
| Parameter | Passing convention | Default / required |
|---|---|---|
args | extra positional arguments (*args) | optional collection |
kwargs | extra 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.
| Parameter | Passing convention | Default / required |
|---|---|---|
args | extra positional arguments (*args) | optional collection |
kwargs | extra 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.
| Parameter | Passing convention | Default / required |
|---|---|---|
args | extra positional arguments (*args) | optional collection |
kwargs | extra 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.