Cosmo Harrigan Cosmo Harrigan - 6 months ago 30
Python Question

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

In the Flask-RESTful example application posted here, the

collection is a global variable.

After the
Resource is registered:

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

methods access the global
variable when web requests are processed.

Instead, I want to instantiate the API within a class and pass a
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?


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

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

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

    def run(self)