学到第九章用户角色,数据迁移和单元测试时遇到了两个小bug,这里放在一起说。
-
数据迁移:在model.py中给Role等表增加了几个字段、做了一些改动,但是flask db migrate无反应:
flask db migrate INFO [alembic.runtime.migration] Context impl SQLiteImpl. INFO [alembic.runtime.migration] Will assume non-transactional DDL. ERROR [flask_migrate] Error: Target database is not up to date.
参考Target database is not up to date后解决,首先得运行第一条指令
$ flask db stamp head $ flask db migrate $ flask db upgrade
flask db stamp head INFO [alembic.runtime.migration] Context impl SQLiteImpl. INFO [alembic.runtime.migration] Will assume non-transactional DDL. INFO [alembic.runtime.migration] Running stamp_revision 25eefa409375 -> 301919de891b
-
单元测试,运行flask test,有一条不是报错,是警告
test_duplicate_email_change_token (test_user_model.UserModelTestCase) ... E:\program\Python\Web\MySecondFlaskApp\app\models.py:100: SAWarning: Object of type <User> not in session, add operation along 'Role.users' will not proceed (This warning originated from the Session 'autoflush' process, which was invoked automatically in response to a user-initiated operation. ) self.role = Role.query.filter_by(default=True).first() ok
查到了这个参考答案SAWarning: Object of type not in session, add operation along ‘Parent.children’ will not proceed,问题一样,但是没能解决我的问题。
继续搜索:Why does a query invoke a auto-flush in SQLAlchemy?
给db = SQLAlchemy()加点东西,解决!# 文件:app\__init__ # db = SQLAlchemy() db = SQLAlchemy(session_options={"autoflush": False})