When you create a new Thread from inside a Flask view, that thread has no request context, so touching request, g, or session raises a RuntimeError. Flask’s copy_current_request_context copies the entire context of the current request into the background thread, so code in the thread can still read request data as if it were running in the view. Use it whenever you need heavy work after the response has gone out — sending email, writing audit logs, calling webhooks — without making the client wait.
The Problem
Suppose the /report endpoint receives an export request: you want to return 202 immediately and generate the file in a background thread, so the client does not have to wait. Code like this looks fine at first glance:
from threading import Threadfrom flask import Flask, requestapp = Flask(__name__)@app.route("/report")def report(): def send_report(): user = request.args.get("user") # fails here print(f"Exporting report for {user}") Thread(target=send_report).start() return {"status": "processing"}, 202
But send_report runs in a brand-new thread with no request context attached. Flask creates a request context for exactly the thread handling the request, so the request.args.get(“user”) line in the background thread raises RuntimeError: Working outside of request context. Worse, the error only fires when the thread actually runs — usually after the response has already been returned — so manual testing can easily look fine, and the error only shows up in the logs once the code runs in production.
The Solution
Just wrap the background function with the copy_current_request_context decorator before handing it to Thread:
from threading import Threadfrom flask import Flask, copy_current_request_context, requestapp = Flask(__name__)@app.route("/report")def report(): @copy_current_request_context def send_report(): user = request.args.get("user") # reads normally print(f"Exporting report for {user}") Thread(target=send_report).start() return {"status": "processing"}, 202
The decorator snapshots the current request context right when the function is defined, and when the thread runs it pushes that context into the thread. That is why request.args, request.path, and request.headers all read normally. Because the request context already includes the app context, current_app and app.config work in the thread too.
Three important notes:
- g in the thread is a new object: values you assign to g in the view do not carry over to the thread, and vice versa. Pass anything you need explicitly as a function argument.
- Only read request data in the thread — do not write to session and expect the browser to receive it; the response was already sent before the thread ran.
- If the background function only needs config and no request data, app.app_context() is lighter — see the Flask-Mail post, which used that approach.
Apply It to Your Project
Attach this pattern to file-export endpoints, confirmation emails after signup, audit logs when a user changes their password, or webhooks to another system. The general flow: the view validates the input, returns 202 right away, and the background thread does the heavy work. Under high traffic, do not spawn a bare Thread per request — use a ThreadPoolExecutor with a limited number of workers so it does not eat all your RAM.
Related Posts
- Flask: Sending Email with Flask-Mail — Don’t Let SMTP Block Your Requests (5 Minutes)
- Flask: Stream Large Data with stream_with_context — Clients Receive It in Chunks, Server Stays Light on RAM in 5 Minutes
- Flask: Stop Circular Imports — Use current_app Instead of Importing app Directly in 5 Minutes
Frequently Asked Questions
How is copy_current_request_context different from app_context()?
copy_current_request_context copies the whole request context, so in the thread you can read request, g, and current_app. app_context() only creates an app context, with no request — touching request still raises RuntimeError.
Does it work with ThreadPoolExecutor?
Yes. Wrap the function with the decorator and submit it as usual; each task gets a copy of the context of the request that submitted it.
Can I use current_app in the background thread?
Yes, because the request context already includes the app context. You can read current_app.config or current_app.logger in the background thread without doing anything extra.
When should I use Celery or RQ instead of a Thread?
When the task takes longer than a few seconds, needs retries on failure, or must survive a server restart. A background thread dies with the process and has no durable queue — it only fits quick, low-stakes work like sending email or writing logs.
💬 Have you tried this in your own project? If you hit an error or have a cleaner approach, leave a comment below — I read them all and will add the best ideas to the post.
References
- Flask docs — copy_current_request_context: https://flask.palletsprojects.com/en/stable/api/#flask.copy_current_request_context
- Flask docs — Request Context: https://flask.palletsprojects.com/en/stable/reqcontext/
