If it MUST coincide with the instantiation of your app, then you should subclass Flask. This really doesn't do a whole lot if all your doing is attaching a resource to the object, considering the creation of the app is a process. Truth is, you probably don't need to do this if the application doesn't need to use your resource during instantiation.
class MyApp(Flask):
def __init__(self, *args, **kwargs):
setattr(self, 'some_resource', SomeResource())
super(Flask, self).__init__(*args, **kwargs)
app = MyApp(__name__)
app.some_resource.do_something()
Unless you have some specific use case, you are probably better off writing a wrapper class, turning it into a flask-extension, creating it on the module level and storing it on app.extensions.
class MyExtensions(object):
def __init__(self, app=None):
self.app = app
if app is not None:
self.init_app(app)
def init_app(self, app):
app.extensions['my_extension'] = SomeResource()
app = Flask(__name__)
my_extension = MyExtension(app)
Then you can choose if you want to give each app its own resource (like above), or if you'd rather use a shared resource that is always pointing to the current app
from flask import _request_ctx_stack
try:
from flask import _app_ctx_stack
except ImportError:
_app_ctx_stack = None
stack = _app_ctx_stack or _request_ctx_stack
class SomeResource(object):
def do_something(self):
ctx = stack.top
app = ctx.app
my_resource = SomeResource()
my_resource.do_something()
I don't think you want to store this on the application context, because " it starts when the Flask object is instantiated, and it implicitly ends when the first request comes in"
Instead, you want your resource created at the module level. Then you can attach it to the application as an extension, or yes, even in the config- though it would be more consistent and logical to make a quick extension out of it.