All jobs

Fix "AttributeError: 'Flask' object has no attribute 'before_first_request'" with Flask-SQLAlchemy

Yes. An agent moves the table creation out of before_first_request into an app context, fixes the bind keyword Flask-SQLAlchemy 3 renamed, and runs the app's test.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent reads the app and the file that installs it. In pynickle/cishen, a Flask vocabulary trainer deployed with web: gunicorn app:app, requirements.txt lists flask, flask-sqlalchemy, flask-wtf, github-flask, psycopg2, requests, gunicorn and python-dotenv with no versions, so a rebuild resolves Flask 3.1.3, Flask-SQLAlchemy 3.1.1, Werkzeug 3.1.9 and SQLAlchemy 2.1.8. The function in the title is on line 159 of app.py: @app.before_first_request decorates before_first_request(), which sets module globals, marks the session permanent, writes three session keys, and then calls db.create_all() once for the default database and three times with bind= for the wrongwords, github-users and admin-users databases that config.py maps from Heroku Postgres URLs.

That decorator is not the first thing to fail, and the agent says so. Line 14, from werkzeug import secure_filename, raises ImportError: cannot import name 'secure_filename' from 'werkzeug' on any Werkzeug from 1.0; Werkzeug 0.16.1 accepts it with a warning naming werkzeug.utils. With that import corrected, the next error is the one in the title, which Flask 2.2.5 still avoids while warning that before_first_request will be removed in Flask 2.3 and that set-up code should run while creating the application. Flask 2.3.3 has no such attribute. One more is waiting behind it: Flask-SQLAlchemy 2.5.1 accepts db.create_all(bind='wrongwords'), and 3.0.5 raises TypeError: SQLAlchemy.create_all() got an unexpected keyword argument 'bind', because the argument is now bind_key.

The fix follows Flask's own advice. The agent creates the tables at import time inside with app.app_context():, one create_all() for the default database and one create_all(bind_key=...) per bind, which is where the models declare __bind_key__ on lines 119, 134 and 149. The session defaults move to a before_request function that uses setdefault, so a returning visitor's progress is not reset, and session.permanent is set there too. The agent notes the one behaviour change in the pull request: the old hook touched only the first request's session, and the new one touches every request's.

Then it runs what the project has. The sandbox cannot build psycopg2 from source without pg_config, so the agent installs psycopg2-binary for the check and points the four database URLs at SQLite files through the environment variables config.py reads. The app's own test in test/test_flask.py, which creates the tables in an app context and expects the home page to contain the site's name, passes, and a test client gets the home, register and login pages with status 200 from the application's twenty-five routes.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "This Flask app fails to start with \"AttributeError: 'Flask' object has no attribute 'before_first_request'\". Read the dependency files and say which Flask, Flask-SQLAlchemy, Werkzeug and SQLAlchemy a clean install resolves. Start the app in a fresh environment and list every error in the order they appear, fixing each in turn: an import Werkzeug moved, the removed decorator, and any keyword Flask-SQLAlchemy 3 renamed. For each, find by installing them the last release that accepted the old code and the first that refused it, and quote the deprecation warning the last one printed. Move the code in the before_first_request function to where Flask says it belongs: database set-up inside an application context at start-up, per-request session defaults into a before_request function that does not overwrite values a session already has. Point any database the app needs at SQLite through its existing configuration, run the project's tests and request the main pages with a test client. Open a pull request with the version findings, the behaviour change if any, and the outputs.",
  "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 changes one import, replaces the decorated function with an application-context block and a before_request function, and renames three bind= arguments to bind_key=. The description lists the three errors in the order a clean start hits them, each with the release that introduced it and the warning the previous release printed, and quotes the test run and the status codes of the pages the test client fetched.

A reviewer checks that every statement from the old function has a new home: the globals, the four create_all calls and the session keys. They also read the note about session.permanent, which now applies on every request, and decide whether that is what they want. If the app runs several gunicorn workers, creating tables at import means each worker runs create_all, which is idempotent, and the pull request says so.

What the run does not prove is the GitHub sign-in: github-flask is imported and configured from the environment, but no client id exists in the sandbox, so that route is not exercised. The pull request says so.

Run it on every failed deploy

This error shows up when a host rebuilds the environment, not when code changes, so a failed deploy is the signal. A deploy job that can run a command on failure, in GitHub Actions or any CI system, posts the log tail to a Rush webhook trigger's URL with the trigger's secret in Authorization: Bearer, and the automation's prompt tells the agent to find the first traceback in the log before reading the code.

A platform that only sends its own signed notification needs a handler on your server that receives it and forwards the log. Have the handler send an Idempotency-Key header to the trigger's URL built from the deploy id, so a retried delivery does not start a second run on the same failure.

The use case this job follows, with its automation and trigger: Fix a bug from an alert.

Why run it on Rush?

Three libraries changed under this app, and each error hides the next. On a laptop the first fix is followed by a surprise, then another. In a Rush sandbox the agent starts the app, fixes the first error, starts it again, and repeats until the pages load, with every traceback kept in the session, so the pull request can list the chain instead of the one error the alert showed.

Finding the boundaries takes installs that nobody wants in their own environment: Werkzeug 0.16, Flask 2.2 and 2.3, Flask-SQLAlchemy 2.5 and 3.0. The agent makes a throwaway environment for each, quotes the warning the last good release printed, and leaves the laptop alone.

Frequently asked questions

What replaces before_first_request?

Flask 2.3 removed it and says to run set-up code while creating the application. For table creation that is with app.app_context(): db.create_all() next to where the app is built. Code that needs a request, such as session defaults, moves to before_request, guarded so it runs its set-up only once per session.

Why does create_all fail after that fix?

Flask-SQLAlchemy 3.0 renamed the bind argument of create_all and drop_all to bind_key, matching the __bind_key__ attribute on models. The agent renames each call and keeps the key names as the models declare them.

Does the agent need my Postgres databases?

No. It points the configuration's database URLs at SQLite files in the sandbox, which is enough to create the tables and load the pages. The pull request says the Postgres path was not exercised and names it as the check after deploy.

Why not pin Flask below 2.3?

Because Werkzeug and Flask-SQLAlchemy moved at the same time, and a Flask pin alone leaves the other two breaks in place. Pinning all three freezes the app on releases that no longer get fixes. The rewrite is a few lines and the pull request shows the app running on current releases.

More Flask-SQLAlchemy jobs

More jobs like this: Fix a bug from an alert

Keep reading