Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 bar import Bar
from foo import views

app = Flask(__name__)
api = Api(app)

my_bar = Bar()

api.add_resource(views.ApiPage, "/api/my/end/point/")

Then in views.py I have the resource set up as follows:

# In views.py
from flask.ext.restful import Resource

class ApiPage(Resource):
    def get(self):
        serialized = str(my_bar)
        return serialized

So the issue that I am having is that I need to pass my instance of Bar() into the api resource. Is there any way to pass it in through the add_resource method like api.add_resource(views.ApiPage, "/api/my/end/point/", instance=bar)?

like image 437
Gunther Avatar asked Aug 02 '14 19:08

Gunther


People also ask

What is resource in Flask-RESTful?

resource ( Type[Resource] ) – the class name of your resource. urls (str) – one or more url routes to match for the resource, standard flask routing rules apply. Any url variables will be passed to the resource method as args. endpoint (str) – endpoint name (defaults to Resource. __name__.

Is FastAPI better than Flask?

FastAPI surpasses Flask in terms of performance, and it is one of the fastest Python web frameworks. Only Starlette and Uvicorn are faster. Because of ASGI, FastAPI supports concurrency and asynchronous code by declaring the endpoints. For concurrent programming, Python 3.4 introduced Async I/O.

Is Reqparse deprecated?

reqparse has been deprecated (https://flask-restful.readthedocs.io/en/latest/reqparse.html):


2 Answers

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

class ApiPage(Resource):
    def __init__(self, bar):
        self.bar = bar

    def get(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})
like image 105
el.atomo Avatar answered Sep 20 '22 00:09

el.atomo


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

class ApiPage(Resource):
    def __init__(self, **kwargs):
       self.my_bar= kwargs['my_bar']
like image 32
ron Avatar answered Sep 19 '22 00:09

ron