Menu Close

How to fix Python Flask throwing ‘working outside of request context’ when starting sub thread?

Sometimes, we want to fix Python Flask throwing ‘working outside of request context’ when starting sub thread.

In this article, we’ll look at how to fix Python Flask throwing ‘working outside of request context’ when starting sub thread.

How to fix Python Flask throwing ‘working outside of request context’ when starting sub thread?

To fix Python Flask throwing ‘working outside of request context’ when starting sub thread, we can wrap our request code in with app.test_request_context().

For instance, we write

@app.route('/my_endpoint', methods=['POST'])
def my_endpoint_handler():
    def handle_sub_view(req):
        with app.test_request_context():
            from flask import request
            request = req
            # ...
    thread.start_new_thread(handle_sub_view, (request))
    return "hello"

to call app.test_request_context() to get the request context in the handle_sub_view function.

Then we import request inside the block with

from flask import request

And then we do what we want with it.

Then we use

thread.start_new_thread(handle_sub_view, (request))

to start a new thread.

Conclusion

To fix Python Flask throwing ‘working outside of request context’ when starting sub thread, we can wrap our request code in with app.test_request_context().

Posted in Python, Python Answers