[PYTHON] The most crude CORS support method on aiohttp Server

For CORS [^ cors] support when implementing an API server with aiohttp Server, a module called aiohttp_cors is provided by the aiohttp official.

[^ cors]: Cross-origin Resource Sharing (CORS)-HTTP | MDN

However, when I read Usage, it seems that it is not straightforward because it is necessary to wrap each resource and each route with cors.add. It is convenient to be able to make detailed settings, but there are also cases where "I just want to allow all requests".

So, this time, I will write about how to support CORS roughly without using aiohttp_cors.

from aiohttp import web

@web.middleware
async def cors_middleware(request, handler):
    response = await handler(request)
    response.headers['Access-Control-Allow-Origin'] = '*'
    return response

app = web.Application(middlewares=[cors_middleware])

**It's the end. ** **

Just add the ʻAccess-Control-Allow-Origin: *` header to every response.

If you say "What about*," you should be able to specify the Origin that is allowed in the environment variable.

import os
from aiohttp import web

@web.middleware
async def cors_middleware(request, handler):
    response = await handler(request)
    response.headers['Access-Control-Allow-Origin'] = os.environ.get('CORS_ALLOW_ORIGIN', '*')
    return response

app = web.Application(middlewares=[cors_middleware])

By the way, it does not correspond to the case where Preflight Request flies. If you want to respond, you can make a guy who will respond to all ʻOPTION` requests.

It's a really crude story, so I'd like you to think about whether security is okay or not.

Recommended Posts

The most crude CORS support method on aiohttp Server
Probably the most unhelpful Python implementation method on Qiita
Notes on using matplotlib on the server
Insufficient var space on the mail server
Discover the most yabe functions on github
Publish the current directory on the web server
Run the task in the background on the sshed server
Drawing tips with matplotlib on the server side
Remotely open Jupyter notebook launched on the server