I have a flask app that I wanted to add a cache to for API calls, so I wrote a simple caching class that doesn't know anything about flask, just about the cache data, and managing it. It lives in a separate file that starts:
import logging
import time
logger = logging.getLogger(__name__)
class CacheCollection:
and uses logger.debug("xxx")
in various places to let you know what's going on.
That all works fine in standalone test code.
HOWEVER, I would like to create this cache in my flask app, and ideally seed it with data when the application starts up. Since Flask hasn't got a "on startup" event like Django does, I am adding this in the init_bp()
method of my Blueprint. It needs to be after Flask's config is loaded, since the endpoint and key for the API I'm caching is in that config.
When I do that, I get a warning on the first call to the logger in the cache class:
RuntimeError: Working outside of application context.
which is true I guess, but I don't see why it's relevant. Does Flask mess with the logging
config enough to break other modules' logging? Having to create a dependency on current_app.logger in this other module seems perverse (and I don't think it will help).
How should I be creating these objects outside of a request? I don't want to use before_first_request
, since it might take a while to run. Other similar questions on SO seem to be for work unrelated to the application itself, running in another thread or something similar.
from Flask app: logging inside a (non-flask-related) class fails
No comments:
Post a Comment