aiohttp-cors
aiohttp-cors provides Cross-Origin Resource Sharing (CORS) support for aiohttp, the asynchronous HTTP client/server framework for Python. It integrates seamlessly with aiohttp applications, enabling configuration of CORS policies for routes and resources. The library is actively maintained, with version 0.8.1 being the latest stable release, and typically follows the development of aiohttp, requiring Python 3.9+.
Common errors
-
AttributeError: 'CORS' object has no attribute 'add'
cause This error occurs when attempting to use the 'add' method on a 'CORS' object, which does not have such a method.fixEnsure that you are using the correct methods provided by the 'aiohttp-cors' library, such as 'setup' and 'add' on the 'CorsConfig' object returned by 'setup'. -
ImportError: cannot import name 'CORS' from 'aiohttp_cors'
cause This error occurs when trying to import 'CORS' directly from 'aiohttp_cors', which does not expose a 'CORS' class.fixImport 'setup' from 'aiohttp_cors' and use it to configure CORS in your application. -
TypeError: setup() missing 1 required positional argument: 'app'
cause This error occurs when calling 'setup()' without passing the 'app' instance as an argument.fixPass your 'app' instance to the 'setup()' function: 'cors = aiohttp_cors.setup(app)'. -
TypeError: add() missing 1 required positional argument: 'route'
cause This error occurs when calling 'add()' without passing a route to be configured for CORS.fixEnsure you pass the route to the 'add()' method: 'cors.add(app.router.add_route("GET", "/path", handler))'. -
AttributeError: 'Resource' object has no attribute 'add_route'
cause This error occurs when attempting to call 'add_route' on a 'Resource' object, which does not have such a method.fixUse 'app.router.add_route' to add routes before configuring CORS.
Warnings
- breaking aiohttp-cors has strict compatibility requirements with `aiohttp` and `Python` versions. As of v0.8.0, it requires `aiohttp>=3.9` and `Python>=3.9`. Earlier versions of aiohttp-cors were compatible with older aiohttp and Python versions, but upgrading both libraries simultaneously is often necessary.
- gotcha CORS configuration must be explicitly applied to each route or resource you wish to expose. Simply initializing `aiohttp_cors.setup(app)` does not automatically enable CORS on all your application's routes.
- deprecated The use of `asyncio.coroutine` decorators for handlers is deprecated in Python 3.5+ in favor of `async def` syntax. While `aiohttp-cors` itself supports this, ensure your application handlers use modern async/await syntax.
- breaking In `aiohttp-cors` v0.7.0, the web view check became implicit and type-based, and support for Python 3.4 was disabled. If you were relying on explicit view checks or using Python 3.4, this will break your application.
Install
-
pip install aiohttp-cors
Imports
- aiohttp_cors
from aiohttp_cors import setup
import aiohttp_cors
- CorsViewMixin
from aiohttp_cors import CorsViewMixin
Quickstart
import aiohttp_cors
from aiohttp import web
async def handler(request):
return web.Response(text="Hello from CORS-enabled endpoint!")
async def main():
app = web.Application()
# Setup CORS for all origins, allowing all headers and methods
cors = aiohttp_cors.setup(app, defaults={
"*": aiohttp_cors.ResourceOptions(
allow_credentials=True,
expose_headers="*",
allow_headers="*",
allow_methods="*"
)
})
# Add a route and enable CORS for it
resource = cors.add(app.router.add_resource("/hello"))
resource.add_route("GET", handler)
# Alternatively, you can add CORS to existing routes directly
# For example, if you had:
# app.router.add_post("/data", data_handler)
# cors.add(app.router.get("/data"))
# To apply CORS to ALL existing routes:
# for route in list(app.router.routes()):
# if not route.is_cors_enabled():
# cors.add(route)
print("Server starting on http://localhost:8080")
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, 'localhost', 8080)
await site.start()
await asyncio.Event().wait() # Keep server running
if __name__ == '__main__':
import asyncio
try:
asyncio.run(main())
except KeyboardInterrupt:
print("Server stopped.")