Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-RESTful how to add_resource and pass it non-global data

In the Flask-RESTful example application posted here, the TODOS collection is a global variable.

After the Todo Resource is registered:

api.add_resource(Todo, '/todos/<string:todo_id>')

The Todo methods access the global TODOS variable when web requests are processed.

Instead, I want to instantiate the API within a class and pass a TODOS collection that is a class variable rather than a global variable.

When using Flask-RESTful, what is the proper way to allow methods in a Resource class to gain access to a variable provided by the calling class without using global variables?

like image 308
Cosmo Harrigan Avatar asked Feb 16 '23 03:02

Cosmo Harrigan


1 Answers

Looks like I didn't understand you the first time, You can just use a classmethod to construct your API. Then add it as a resource

from flask import Flask
from flask.ext.restful import Api

class SomeApi(Resource):
    def get(self):
        return self.response

    @classmethod
    def make_api(cls, response):
        cls.response = response
        return cls


class KillerApp(object):
    def __init__(self):
        self.app = Flask()
        app_api = Api(self.app)
        MyApi = SomeAPI.make_api({"key": "value"})
        app_api.add_resource(MyApi, "/api/path")

    def run(self)
        self.app.run()


KillerApp().run()
like image 108
Greg Avatar answered Mar 23 '23 02:03

Greg