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

Cosmo Harrigan picture Cosmo Harrigan · Sep 29, 2013 · Viewed 10.4k times · Source

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?

Answer

Greg picture Greg · Sep 29, 2013

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()