Answer guide
Read the answer guide
Flask uses contexts so code can reach things like current_app, g and, during a request, request without passing them around explicitly. The g object is a per-context scratch space, commonly used for a database connection during one request, and it is cleaned up when the context ends. A frequent error is using current_app or g in a background thread or at import time, where no context exists, which raises the familiar 'working outside of application context' error. Use app.app_context in scripts and tests, and pass real objects to threads.
What the interviewer is assessing
Basic understanding of why Flask has contexts and where code can and cannot rely on them.
A strong answer covers
- Contexts let code reach current_app, g and request without passing them around explicitly.
- g holds per-context data, commonly a database connection for one request, and is cleaned up when the context ends.
- Using current_app or g in a background thread or at import time raises the working-outside-of-application-context error.
- Use app.app_context in scripts and tests, and pass real objects to threads.
Common mistakes
- Using current_app or g at import time or in a separate thread and being surprised by the context error.
- Treating g as global storage shared between requests.
Practise a follow-up
- What is the difference between the application context and the request context?
- How do you run code that needs the app outside a request, for example in a script?