Skip to content Skip to sidebar Skip to footer

Flask Restful Add Resource Parameters

I am looking to pass an object instance as a parameter into a Flask-RESTfull Resource. Here is my setup: # in main.py from flask import Flask from flask.ext.restful import Api from

Solution 1:

Since version 0.3.3 (released May 22, 2015), add_resource() is able to pass parameters to your Resource constructor.

Following the original example, here is the views.py:

from flask.ext.restful import Resource

classApiPage(Resource):
    def__init__(self, bar):
        self.bar = bar

    defget(self):
        serialized = str(my_bar)
        return serialized

And the relevant code for main.py:

# ...
my_bar = Bar()
api.add_resource(views.ApiPage, '/api/my/end/point/',
                 resource_class_kwargs={'bar': my_bar})

Solution 2:

In version 0.3.5 documentation you can do it this way

# in main.py
...
my_bar = Bar()
api.add_resource(views.ApiPage, '/api/my/end/point/',
             resource_class_kwargs={'my_bar': my_bar})

pass your object in the add_resource method and use it in the resource init method

and in your class init

classApiPage(Resource):def__init__(self, **kwargs):
       self.my_bar= kwargs['my_bar']

Solution 3:

After struggling with the same problem I found you can use add_url_rule coupled with as_view

So in your case I guess the code would be something like

classApiPage(Resource):
    def__init__(self, bar=None)
        self.__my_bar=bar

    defget(self):
        serialized = str(self.__my_bar)
        return serialized

my_bar = Bar()

app = Flask(__name__)
app.add_url_rule('/api/my/end/point/', bar=my_bar)

api = Api(app)

Solution 4:

Given the documentation such thing can not be done at this level. One way to circumvent this issue would be to put the initialisation of Bar inside another module, then fetch the instance through an import in your views module.

Post a Comment for "Flask Restful Add Resource Parameters"