# Fix Flask RuntimeError Working Outside Application Context

> Resolve the Flask 'working outside of application context' RuntimeError by pushing an app context with app.app_context() before accessing context-bound objects

**URL:** https://sentry.io/answers/working-outside-of-application-context/

---

## The Problem

```python
Traceback (most recent call last):
  File "app.py", line 30, in init_db
    db = get_db()
  File "app.py", line 41, in get_db
    g.sqlite_db = connect_db()
  File "/usr/local/lib/python3/site-packages/werkzeug/local.py", line 355, in <lambda>
    __setattr__ = lambda x, n, v: setattr(x._get_current_object(), n, v)
  File "/usr/local/lib/python3/site-packages/werkzeug/local.py", line 297, in _get_current_object
    return self.__local()
  File "/usr/local/lib/python3/site-packages/flask/globals.py", line 27, in _lookup_app_object
    raise RuntimeError('working outside of application context')
RuntimeError: working outside of application context
```

## The Solution

Flask requires application context be available when accessing certain items, such as the `g` construct. Many of these accessors are simply a proxy for the _current_ version, which is bound to the `Flask` application context.

For example, if you've got a command line app, you simply need to instantiate your app and push a context:

```python
from flask import Flask, current_app

app = Flask(__name__)

with app.app_context():
    # within this block, current_app points to app.
    print(current_app.name)
```

### Further Reading

If you're looking to get a deeper understanding of how Flask application monitoring works, take a look at the following articles:

- [How slow is slow?](https://blog.sentry.io/how-slow-is-slow/)
- [How to build a SaaS application block by block](https://blog.sentry.io/how-to-build-saas-application/)
- [Getting started with the Flask SDK (docs)](https://docs.sentry.io/platforms/python/integrations/flask/)

---

*Source: [sentry.io/answers/working-outside-of-application-context/](https://sentry.io/answers/working-outside-of-application-context/)*
