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+.
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
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.")