KeyError: <weakref at 0x7fc9e8267ad0; to 'Flask' at 0x7fc9e9ec5750>

Question:

I’ve been having a hard time handling sessions in flask. Since when I manage the application in the local environment everything works perfectly, including flask sessions. But when i already host it in Render i always get this error in every route.

[55] [ERROR] Error handling request /valle-de-guadalupe
Traceback (most recent call last):
    File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask/app.py", line 2525, in wsgi_app
      response = self.full_dispatch_request()
    File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask/app.py", line 1822, in full_dispatch_request
      rv = self.handle_user_exception(e)
    File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask/app.py", line 1820, in full_dispatch_request
      rv = self.dispatch_request()
    File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask/app.py", line 1796, in dispatch_request
      return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
    File "/opt/render/project/src/app_folder/routes/public.py", line 35, in valle_de_guadalupe
     return render_template("public/cities/valle_guadalupe.html")
    File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask/templating.py", line 147, in render_template
      return _render(app, template, context)
    File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask/templating.py", line 128, in _render
      app.update_template_context(context)
    File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask/app.py", line 994, in update_template_context
      context.update(func())
    File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask_login/utils.py", line 407, in _user_context_processor
      return dict(current_user=_get_user())
    File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask_login/utils.py", line 372, in _get_user
      current_app.login_manager._load_user()
    File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask_login/login_manager.py", line 364, in _load_user
      user = self._user_callback(user_id)
    File "/opt/render/project/src/app.py", line 52, in load_user
      return User.get_by_id(int(user_id))
    File "/opt/render/project/src/app_folder/models/models.py", line 82, in get_by_id
      return User.query.get(id)
    File "<string>", line 2, in get
    File "/opt/render/project/src/.venv/lib/python3.7/site-packages/sqlalchemy/util/deprecations.py", line 402, in warned
      return fn(*args, **kwargs)
    File "/opt/render/project/src/.venv/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 947, in get
      return self._get_impl(ident, loading.load_on_pk_identity)
    File "/opt/render/project/src/.venv/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 959, in _get_impl
      execution_options=self._execution_options,
    File "/opt/render/project/src/.venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 2959, in _get_impl
      load_options=load_options,
    File "/opt/render/project/src/.venv/lib/python3.7/site-packages/sqlalchemy/orm/loading.py", line 534, in load_on_pk_identity
      bind_arguments=bind_arguments,
    File "/opt/render/project/src/.venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 1702, in execute
      bind = self.get_bind(**bind_arguments)
    File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask_sqlalchemy/session.py", line 61, in get_bind
      engines = self._db.engines
    File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask_sqlalchemy/extension.py", line 629, in engines
      return self._app_engines[app]
    File "/usr/local/lib/python3.7/weakref.py", line 396, in __getitem__
      return self.data[ref(key)]
KeyError: <weakref at 0x7fc9e8267ad0; to 'Flask' at 0x7fc9e9ec5750>

index.py

from app import app
from app_folder.utils.db import db

db.init_app(app)
with app.app_context():
    db.create_all()

if __name__ == "__main__":
    app.run(
        debug = False,
        port = 5000
)

app.py

from flask import Flask
"""Flask SqlAlchemy"""
from flask_sqlalchemy import SQLAlchemy
"""Flask Login"""
from flask_login import LoginManager
"""Dot Env"""
from dotenv import load_dotenv
"""App Folder Routes"""
from app_folder.handlers.stripe_handlers import stripe_error
from app_folder.handlers.web_handlers import web_error
from app_folder.models.models import User
from app_folder.routes.admin import admin
from app_folder.routes.public import public
from app_folder.routes.users import users
from app_folder.utils.db import db

"""Imports"""
import os
import stripe

load_dotenv()
"""config app"""
app = Flask(__name__, 
        static_url_path="",
        template_folder="app_folder/templates", 
        static_folder="app_folder/static")
app.config['SECRET_KEY'] = os.getenv("SECRET_KEY")
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv("SQLALCHEMY_DATABASE_VERSION")+os.getenv("SQLALCHEMY_USERNAME")+":"+os.getenv("SQLALCHEMY_PASSWORD")+"@"+os.getenv("SQLALCHEMY_SERVER")+"/"+os.getenv("SQLALCHEMY_DATABASE")
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = os.getenv("SQLALCHEMY_TRACK_MODIFICATIONS")

"""blueprints"""
app.register_blueprint(stripe_error)
app.register_blueprint(web_error)
app.register_blueprint(admin)
app.register_blueprint(public)
app.register_blueprint(users)

SQLAlchemy(app)

login_manager = LoginManager(app)

""" stripe """
stripe_keys = {
  'secret_key': os.getenv("STRIPE_SECRET_KEY"),
  'publishable_key': os.getenv("STRIPE_PUBLISHABLE_KEY")
}
stripe.api_key = stripe_keys['secret_key']

"""Login Manager"""
@login_manager.user_loader
def load_user(user_id):
        return User.get_by_id(int(user_id))

"""Teardown"""
@app.teardown_appcontext
def shutdown_session(exception=None):
   db.session.remove()

Regardless of which route i’m on, while handling sessions I get the same error, but in this case use this path.

public.py

"""routes"""
@public.route("/", methods=["GET", "POST"])
def index():
    return redirect(url_for('public.valle_de_guadalupe'))

"""cities"""
@public.route("/valle-de-guadalupe", methods=["GET", "POST"])
def valle_de_guadalupe():
    return render_template("public/cities/valle_guadalupe.html")

I don’t know if this has happened to someone else.

Answers:

It’s usually best to remove as many extra components and identify a minimal example that produces the error, otherwise it’s often hard to help.

That said, I think that error suggests that db (SQLAlachemy() from flask-sqlalchemy) is not being inited with app.

I’m not sure what the db is that is being imported from app_folder.utils.db, but it appears that you may need to call db.init_app(app).

Relatedly, the line SQLAlchemy(app) is not being assigned. Perhaps you meant to assign that to db?

Answered By: David C

Other people report that this issue happens since the upgrade from flask-sqlalchemy v2.5.1 to v3. So downgrading might be a work around (not a permanent solution)

Source

Answered By: Mick