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

回答 2 浏览 3965 2022-10-20

我一直很难处理 Flask 中的会话。自从我在本地环境中管理应用程序以来,一切都运行良好,包括flask会话。但当我已经在Render中托管它时,我总是在每个路由中得到这个错误。

[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()

无论我在哪条路线上,在处理会话时,我都会得到同样的错误,但在这种情况下,要使用这个路径。

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")

我不知道这种情况是否发生在其他人身上。

Jose Joel Vargas Martinez 提问于2022-10-20
2 个回答
#1楼 已采纳
得票数 6

通常最好是尽可能多地删除多余的组件,并确定产生错误的最小的示例,否则往往很难提供帮助。

也就是说,我认为这个错误表明,dbSQLAlachemy()来自flask-sqlalchemy)没有被appinit

我不确定从app_folder.utils.db中导入的db是什么,但看起来你可能需要调用db.init_app(app)

与此相关,SQLAlchemy(app)这一行没有被分配。也许你是想把它分配给db

David C 提问于2022-10-20
解决了!,显然问题是它没有调用db.init_app(app),而且db没有被分配到white SQLAlchemy(app),现在app在Render上工作得很好!。Jose Joel Vargas Martinez 2022-10-21
#2楼
得票数 0

其他人报告说,这个问题是在从flask-sqlalchemy v2.5.1升级到v3后发生的。 因此,降级可能是一个解决方法(不是永久的解决方案)。

来源

Mickster 提问于2023-01-02