current_app, g, and anything that reads configuration are proxies bound to an application context. Touching them at import time, in a background thread, in a Celery task, or in a script that only imported the app raises RuntimeError: Working outside of application context.
The usual cause is module-level code such as a database engine built from current_app.config, which runs when the module is imported rather than when a request arrives. The same error appears in a @click.command that forgot @with_appcontext.
The fix is with app.app_context(): around the code, which pushes a context and pops it afterwards. Two related distinctions save time. request and session need a request context, which is stricter, and the error text says request context instead. And g is scoped to the application context, not to the request, so it is not a place to cache anything across requests; it is cleared when the context pops. In a threaded worker each thread needs its own pushed context because the proxies are backed by context-local storage.