aiohttp-middlewares
aiohttp-middlewares is a collection of useful middlewares for aiohttp applications, providing common web-development needs like error handling, CORS, timeout, and shielding view handlers. The library is currently at version 2.4.0 and maintains a regular monthly release cadence.
Common errors
-
TypeError: 'type' object is not subscriptable
cause Using type hints like `list[str]` or `dict[str, int]` in Python versions older than 3.9 without `from __future__ import annotations` or `typing.List`.fixUpgrade to Python 3.9+ or use `from __future__ import annotations` (if on 3.7/3.8) or import from the `typing` module (e.g., `from typing import List, Dict`). Note that aiohttp-middlewares 2.x requires Python 3.8+. -
ModuleNotFoundError: No module named 'aiohttp_middlewares.cors_middleware'
cause Attempting to import a middleware directly from a submodule (e.g., `aiohttp_middlewares.cors`) instead of the top-level `aiohttp_middlewares` package.fixAlways import middlewares directly from `aiohttp_middlewares`. For example, `from aiohttp_middlewares import cors_middleware` is correct, not `from aiohttp_middlewares.cors import cors_middleware`. -
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host ... connection refused
cause While not directly an `aiohttp-middlewares` error, if `timeout_middleware` or `shield_middleware` are misconfigured, they might mask or prematurely terminate connection attempts, leading to unexpected connection issues or 504 errors.fixEnsure `timeout_middleware` settings align with your reverse proxy (e.g., Nginx) timeouts to avoid premature timeouts. Test `shield_middleware` with non-idempotent methods (`POST`, `PUT`) as recommended. -
RuntimeError: 'Application.middlewares' should be a list of functions
cause Passing a middleware factory without calling it, or a regular coroutine function without the `@web.middleware` decorator if attempting to use a custom middleware directly.fixEnsure that if you are using middleware factories (like `cors_middleware()`, `error_middleware()`), you call them when passing to `Application(middlewares=...)`. For custom middlewares, ensure they are decorated with `@web.middleware` and accept `request` and `handler` parameters.
Warnings
- breaking In `v2.1.0`, CORS middleware handling was changed to correctly add CORS headers even if the request results in an `aiohttp.web.HTTPException`. This might alter behavior for applications relying on previous incorrect handling.
- breaking Python 3.6 support was dropped in `v2.0.0`, and Python 3.7 support was dropped in `v2.3.0`. Applications on older Python versions will fail to install or run.
- breaking Version `2.0.0` introduced new lower bounds for core dependencies: `aiohttp>=3.8.1,<4.0` and `async-timeout>=4.0.2,<5.0`. Older versions of these dependencies are no longer supported.
- gotcha By default, `cors_middleware` does not allow any origins to access content. You must explicitly configure allowed origins, URLs, or set `allow_all=True` for it to function.
- gotcha The `error_middleware` should generally be placed at the top of your `middlewares` list to catch all exceptions, but specifically *after* `cors_middleware` if both are used, to ensure CORS headers are applied to error responses.
- gotcha `timeout_middleware` raises `asyncio.TimeoutError` but does not handle it by itself. To provide custom error pages or logging for timeouts, `error_middleware` must also be used and placed correctly.
Install
-
pip install aiohttp-middlewares
Imports
- cors_middleware
from aiohttp_middlewares import cors_middleware
- error_middleware
from aiohttp_middlewares import error_middleware
- timeout_middleware
from aiohttp_middlewares import timeout_middleware
- shield_middleware
from aiohttp_middlewares import shield_middleware
- https_middleware
from aiohttp_middlewares import https_middleware
Quickstart
from aiohttp import web
from aiohttp_middlewares import (
cors_middleware,
error_middleware,
)
async def handler(request):
return web.Response(text="Hello, aiohttp-middlewares!")
app = web.Application(
middlewares=(
cors_middleware(origins=("http://localhost:8081", "http://127.0.0.1:8081")),
error_middleware(),
)
)
app.router.add_get('/', handler)
if __name__ == '__main__':
web.run_app(app)