aiohttp-cors

0.8.1 · active · verified Sun Apr 05

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

Install

Imports

Quickstart

This quickstart sets up a basic aiohttp web application and applies a permissive CORS policy to a '/hello' endpoint, allowing requests from any origin. It demonstrates how to initialize CORS for the application and then apply it to specific routes or resources. It also shows a commented-out section for applying CORS to all routes programmatically.

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

view raw JSON →