Sanic: CORS support?

Created on 29 Dec 2016  路  9Comments  路  Source: sanic-org/sanic

Hi, thank you for making this framework.

Any plans on implementing CORS support?
Also, what's the best way to set response headers manually?

idea discussion

Most helpful comment

@nderkach @seemethere @guzgarcia
I ported the flask extension flask-cors to Sanic :) get it here: https://github.com/ashleysommer/sanic-cors

See the Readme and examples for how to use it. It's almost identical in usage to flask-cors.

Edit:
(You have to install it from the github repo, it's not published to pypi yet)

All 9 comments

We don't currently support CORS with in sanic core but I'd be open to someone writing an extension for it.

To set the response headers manually you can use:

from sanic import Sanic
from sanic.response import json

app = Sanic(__name__)


@app.route("/")
async def test(request):
    return json({"test": True}, headers={'dummy_header': 'blah'})

@app.route("/another_header_example")
async def foo(request):
    response = json({"initial_response": 1})
    response.headers.update({'dummy_header': 0})
    return response

app.run(host="0.0.0.0", port=8000)

+1. I think cors support would be built in due it's importance. Making a rest service without cors has not much sense.

@nderkach @seemethere @guzgarcia
I ported the flask extension flask-cors to Sanic :) get it here: https://github.com/ashleysommer/sanic-cors

See the Readme and examples for how to use it. It's almost identical in usage to flask-cors.

Edit:
(You have to install it from the github repo, it's not published to pypi yet)

@ashleysommer would be great to automatically return on preflight requests, e.g. now I have to do something like this in my methods:

if request.method == "OPTIONS":
    return text("ok")

Supported by @ashleysommer and it's now featured in our extensions documentation! Thanks guys!

Closing now...

Hey all, just an update to the CORS plugin, I have updated it to work better with Sanic 0.4.0/0.4.1 and it is now released on pypi here: https://pypi.python.org/pypi/Sanic-Cors/

Working about a month and came here after trying to connect to my Sanic app via React.js front end. It is truly unbelievable that Sanic does not support CORS. Also extension did not work for me. Now I have to change my app to Flask.

I hope CORS support will be added in the future. Thanks.

@skynyrd
I am the CORS extension maintainer. I might be able to help with your problem.
To avoid polluting this Issue thread, please open an issue on the Sanic-CORS github issue tracker here:
https://github.com/ashleysommer/sanic-cors/issues

(Also, I got your email and I am replying to it now)

Here is an extremely simple decorator that I coded for another project for another framework (HUG, great library but does not work async AFAIK). IMHO this or something like this should be included by default.

allowed_origins = ['http://www.uutisjuttu.fi']                                                      

def cors():                                                                                                   
    def decorator(f):                                                                                         
        @wraps(f)                                                                                             
        async def decorated_function(request, *args, **kwargs):                                               
            response = await f(request, *args, **kwargs)                                                      
            if 'ORIGIN' in request.headers:                                                                   
                origin = request.headers['ORIGIN']                                                            
                if origin in allowed_origins:                                                                 
                    response.headers['Access-Control-Allow-Origin'] = origin                                                                                       
            return response                                                                                   
        return decorated_function                                                                             
    return decorator                                                                                          

@app.route('/some_function')                                                                                          
@cors()                                                                                                       
# @ttl_cache(maxsize=128, ttl=10)                                                                             
async def some_function(req):
    ... implementation ...
    return json(data)                                                                           

Was this page helpful?
0 / 5 - 0 ratings

Related issues

eseglem picture eseglem  路  4Comments

tonyliuatmobius picture tonyliuatmobius  路  4Comments

geekpy picture geekpy  路  4Comments

woutor picture woutor  路  3Comments

sirex picture sirex  路  4Comments