Search code examples
pythonflaskcorsflask-restful

TypeError on CORS for flask-restful


While trying the new CORS feature on flask-restful, I found out that the decorator can be only applied if the function returns a string.

For example, modifying the Quickstart example:

class HelloWorld(restful.Resource):
    @cors.crossdomain(origin='*')
    def get(self):
        return {'hello': 'world'}

Throws:

TypeError: 'dict' object is not callable

Am I doing something wrong?


Solution

  • I recently came across this issue myself. @MartijnPieters is correct, decorators can't be called on single methods of the view.

    I created an abstract base class that contained the decorator list. The class that consumes Resource (from flask-restful) also inherits the base class, which is the class actually applying the decorator list to the view.

        class AbstractAPI():
           decorators = [cors.crossdomain(origin='*')]
    
        class HelloWorld(restful.Resource, AbstractAPI):
           #content
    

    nope.

    just add the decorator list to the parameters after you create the Api instance

    api = Api(app)
    api.decorators=[cors.crossdomain(origin='*')]