# Fix "RuntimeError: Working outside of application context" from db.create_all() in Flask-SQLAlchemy 3

Yes. An agent wraps every db.create_all() that runs outside a request in app.app_context(), deploy scripts included, and starts the app on a fresh install.

[Run this on Rush](https://cloud.getrush.ai/run/fix-working-outside-of-application-context/flask-sqlalchemy/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

Flask-SQLAlchemy 3.0.0, released in October 2022, stopped remembering the app it was created with. `db.create_all()`, `db.drop_all()` and the session now look up the current app from the active application context, and a call made at import time, in a `__main__` block or from a one-line deploy command raises `RuntimeError: Working outside of application context.` followed by the hint `To solve this, set up an application context with app.app_context().` On 2.5.1 the same call worked anywhere, because `SQLAlchemy(app)` kept a reference. Apps written against 2.x hit this on the day their install resolves 3.x.

yefim/flask-heroku-sample, a small Flask app made to be deployed with one button, shows the three places it hides. `app.py` creates `db = SQLAlchemy(app)`, defines a `User` model with `id`, `name` and `email`, and under `if __name__ == '__main__':` calls `db.create_all()` before `app.run(host='0.0.0.0', port=port, debug=True)`. `app.json` has a `postdeploy` script, `python -c 'from app import db; db.create_all()'`, and the README tells a reader to run the same two lines in `heroku run python`. The `Pipfile` asks for `flask`, `flask-sqlalchemy`, `psycopg2` and `gunicorn` as `*` under Python 3.6, and its `Pipfile.lock` holds the 2019 answer: Flask 1.0.3, Flask-SQLAlchemy 2.4.0, SQLAlchemy 1.3.5, Werkzeug 0.15.4. The first `pipenv update`, or any `pip install flask flask-sqlalchemy` on a current Python, resolves Flask 3.1.3, Flask-SQLAlchemy 3.1.1 and SQLAlchemy 2.1.8, and `python app.py` ends in the `RuntimeError` above before the server starts.

The agent reproduces that on a clean environment, then finds every call that runs without a request: the `__main__` block, the `postdeploy` one-liner in `app.json`, the README snippet, and any `manage.py`, seed script or test fixture a larger app has. Each gets the same two-line change, `with app.app_context(): db.create_all()`. The route handlers are left alone: `User.query.all()` inside `index()` runs during a request, and a request context carries an application context, so it never raised.

Then it starts the app the way the repository does. `python app.py` on the default `sqlite:////tmp/flask_app.db` must create the table and listen; the `postdeploy` command, rewritten as `python -c 'from app import app, db' ...` with the context, must exit 0; and a `POST /user` followed by `GET /` must show the row, which the agent drives with a plain HTTP client. It does not pin Flask-SQLAlchemy back to 2.5.1, which would also drag Flask and SQLAlchemy back to the releases that version supports.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "This Flask app fails with \"RuntimeError: Working outside of application context\" at db.create_all() after Flask-SQLAlchemy was installed fresh. Read the dependency files and the lockfile if there is one, report how flask and flask-sqlalchemy are pinned and what the lockfile holds, then create a clean virtual environment on a current Python, install the dependencies as a new user would, and report the versions that were resolved. Start the app the way the README or Procfile does and save the traceback. Search every .py file, deploy manifest (app.json, Procfile, Dockerfile, CI config) and README for create_all, drop_all and db.session calls that run outside a request handler, and list each with its file and line. Wrap each one in with app.app_context(). Leave route handlers unchanged. Do not pin flask-sqlalchemy below 3 to hide the error. Start the app again, create a row through its own form or endpoint with an HTTP client, read it back, and report the result. Open a pull request with the resolved versions, the list of changed call sites, and the commands that now succeed.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

A pull request that touches each place `db.create_all()` runs without a request. In the fixture above that is a two-line indent in `app.py`, the `postdeploy` string in `app.json`, and the README snippet. The description lists the versions a clean install resolved against what `Pipfile.lock` had frozen, the traceback before, and the three commands after: `python app.py` listening, the deploy one-liner exiting 0, and a `POST /user` whose row appears on `GET /`.

What a reviewer checks is that the fix went where the error was and nowhere else. Route handlers are unchanged, since a request context already carries an application context, and every call the agent wrapped is listed with the file and line it found it at, so a reviewer can confirm the list is complete by reading rather than by trusting.

If the app also uses the SQLAlchemy 1.x `Model.query.get()` or raw string queries, those are listed as warnings or separate findings, because a fresh install also moved SQLAlchemy to 2.x. They are not fixed in this pull request unless they stop the app from starting.

## Run it on every lockfile refresh pull request

A lockfile keeps this bug out until someone refreshes it, so the moment to look is the refresh. Give the Project an automation with a `github` trigger on `pull_request.opened` and a prompt that tells the agent to install from the branch's lockfile, start the app the way the Procfile does, run the deploy script from `app.json`, and report any `RuntimeError` about the application context. The trigger adds the pull request to the prompt, so a lockfile refresh arrives with the broken `create_all` named before it is merged. A pull request a bot opens fires no `github` trigger, so a Dependabot refresh is checked by a `schedule` trigger with a weekly `cron` whose prompt tells the agent to check the open dependency pull requests.

For a set of small Flask services that share this one-file shape, start the request above once per repository from a script with an API key, and read each session's `pr_url` when its `run.completed` webhook arrives. Runs past the key's `max_concurrent` limit are accepted and wait as `queued`.

## Why run it on Rush?

The indent is one line. The work is finding every context-free call, including the ones in deploy manifests and READMEs that no linter reads, and proving on a fresh install that the app starts, creates its table and serves a row. An agent in a sandbox does that with the real `python app.py`, the real deploy command and a real HTTP request, and the session keeps the output.

It also runs where the bug lives. On a laptop that still has the 2019 lockfile installed, Flask-SQLAlchemy is 2.4.0 and `create_all` works anywhere. A sandbox installs what a refreshed lockfile or a plain `pip install` gives today, which is the only environment in which the error appears.

## Frequently asked questions

### Why does db.create_all() need an app context now?

From Flask-SQLAlchemy 3.0.0 the extension no longer keeps the app it was created with and reads `current_app` instead. Inside a request that is set already; in a `__main__` block, a shell one-liner or a deploy script nothing has pushed a context, so the lookup fails with this `RuntimeError`. On 2.5.1 the same call worked anywhere.

### Can I pin flask-sqlalchemy below 3 instead?

Only with SQLAlchemy and Flask pinned back too: 2.5.1 does not even import next to the SQLAlchemy 2 a fresh install resolves (`module 'sqlalchemy' has no attribute '__all__'`). That turns a one-line change into three old pins. The request above tells the agent not to pin.

### Do my route handlers need the context too?

No. A request context carries an application context, so `User.query.all()` in a view keeps working. The agent only wraps calls that run outside a request: startup code, deploy scripts, shells and tests.

### What about the heroku run python snippet in the README?

It is the same call outside a request, so it fails the same way. The agent rewrites it as `from app import app, db` followed by `with app.app_context(): db.create_all()`, in the README and in the `postdeploy` script in `app.json`.

### Will tests that create tables in a fixture break?

Yes, if they call `db.create_all()` with no context pushed. The agent lists those too and wraps them the same way, or uses `app.test_request_context()` where the fixture already builds a client.

## More Flask-SQLAlchemy jobs

- [Fix "AttributeError: 'Flask' object has no attribute 'before_first_request'" with Flask-SQLAlchemy](https://getrush.ai/run/fix-before-first-request-attribute-error/flask-sqlalchemy/)
- [Fix "LegacyAPIWarning: The Query.get() method is considered legacy as of the 1.x series of SQLAlchemy"](https://getrush.ai/run/fix-query-get-legacy-api-warning/flask-sqlalchemy/)

## More jobs like this: Fix a bug from an alert

- [Fix "AttributeError: module 'lib' has no attribute 'X509_V_FLAG_CB_ISSUER_CHECK'" From pyOpenSSL](https://getrush.ai/run/fix-x509-v-flag-cb-issuer-check-attribute-error/pyopenssl/)
- [Fix "XLRDError: Excel xlsx file; not supported" in a Python Project](https://getrush.ai/run/fix-xlrd-xlsx-not-supported/xlrd/)
- [Fix "load() missing 1 required positional argument: 'Loader'" in PyYAML](https://getrush.ai/run/fix-yaml-load-missing-loader/pyyaml/)
- [Replace PyCrypto With PyCryptodome in a Python Project](https://getrush.ai/run/migrate-pycrypto-to-pycryptodome/pycrypto/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
