Python框架。AssertionError:在处理第一个请求后调用了设置函数
我一直在按照flask教程添加数据库,在他们的示例中,他们在使用mysqlite,而我在使用MySQL,但我认为这不会造成很大的区别 这是我正在尝试使用的mysql库 然而,无论我做什么,我似乎都无法摆脱这个断言错误:Python框架。AssertionError:在处理第一个请求后调用了设置函数,python,flask,Python,Flask,我一直在按照flask教程添加数据库,在他们的示例中,他们在使用mysqlite,而我在使用MySQL,但我认为这不会造成很大的区别 这是我正在尝试使用的mysql库 然而,无论我做什么,我似乎都无法摆脱这个断言错误: AssertionError: A setup function was called after the first request was handled. This usually indicates a bug in the application where a mo
AssertionError: A setup function was called after the first request was handled. This usually indicates a bug in the application where a module was not imported and decorators or other functionality was called too late.
To fix this make sure to import all your view modules, database models and everything related at a central place before the application starts serving requests.
该错误仅在尝试使用/dbtest路径时发生
这是我的最小初始值
import os
from flask import Flask, render_template
from . import db
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
MYSQL_DATABASE_HOST='mysql-svc',
MYSQL_DATABASE_USER='root',
MYSQL_DATABASE_PASSWORD='root',
DEBUG=True,
TESTING=True
)
db.init_app(app)
# a simple page that says hello
@app.route('/hello')
def hello():
return 'Hello, World!'
@app.route('/dbtest')
def db_test():
with app.app_context():
cursor = db.get_cursor()
cursor.execute('SHOW DATABASES')
return cursor.fetchall()
return app
这里是db.py,它在同一个目录中
from flaskext.mysql import MySQL
from flask import current_app, g
def get_cursor():
if 'db_cursor' not in g:
mysql = MySQL()
mysql.init_app(current_app)
g.db_cursor = mysql.get_db().cursor()
return g.db_cursor
def close_db(e=None):
db = g.pop('db_cursor', None)
if db is not None:
db.close()
def init_app(app):
app.teardown_appcontext(close_db)
我读到的关于这个错误的所有信息似乎都表明,在我试图访问数据库或其他东西之后,我在某种程度上搞乱了路由?但我只是按照教程介绍如何设置路由。我可能在这里遗漏了一些明显的东西,我相信这是mysql.init_app的一个问题,但我仍然不知道如何做到这一点。最后我不得不说,通过获取光标来解决整个
g
问题,用撕裂关闭数据库也是如此。最后,它在my db.py中仅使用以下内容:
from flaskext.mysql import MySQL
def init_db_connection(app):
mysql = MySQL()
mysql.init_app(app)
return mysql.get_db().cursor()
在我进行任何路由之前,我从我的_uinit__u;py.py调用了一次,这会得到db游标。然后我就可以在路由中自由地使用这个变量
我不确定这将扩展到多大程度,坦率地说,我认为flask教程相当糟糕,因为
g
、应用程序初始化、路由、当前应用程序
和其他应用程序背后的机制解释得很差。但我所拥有的至少在现在起作用。我希望其他人能为这个问题提供更好的答案。如果DEBUG=True
,这个问题可能与此有关,我自己就是遇到这个问题来这里寻找解决方案的。下面关闭的github票证有一条注释,表明它在某个时候是一个问题。到今天为止,这似乎仍然是一个问题。
是的。最后我改成了flask_mysqldb,我发现由于某种原因,如果您处于调试模式,并且在flask中路由之前尝试获取光标,它将始终返回None,就像连接失败一样。不知道如果有人想启用调试,他们应该如何解决这个问题。我改为接受你的答案,因为它比我的答案更有用