Home >Database >Mysql Tutorial >Why Am I Getting a 'RuntimeError: Working Outside of Application Context' in My Flask Unit Tests?
RuntimeError: Working Outside of Application Context
In the given Flask application, an attempt to call the before_request function in a unit test (test.py) results in a "RuntimeError: working outside of application context." The same error occurs when calling the input_info function.
Background:
Flask manages a global Application Context that provides access to services such as the database connection. To work within the context, code needs to be run inside the application's request-response cycle.
Solution:
To resolve the error, the unit tests must establish an Application Context. This can be achieved using app.app_context() as a context manager:
def test_connection(self): with app.app_context(): # Test code here using `g.db`
Alternative Solution:
Instead of manually managing the Application Context, you can use the Flask-Testing extension, which automatically sets up the context for unit tests.
Additional Considerations:
The above is the detailed content of Why Am I Getting a 'RuntimeError: Working Outside of Application Context' in My Flask Unit Tests?. For more information, please follow other related articles on the PHP Chinese website!