在使用flask_sqlalchemy
删表、建表时出现报错:
Traceback (most recent call last):
File "xxx\test.py", line 40, in <module>
db.drop_all()
File "xxx\Python\Python38\lib\site-packages\flask_sqlalchemy\extension.py", line 901, in drop_all
self._call_for_binds(bind_key, "drop_all")
File "xxx\Python\Python38\lib\site-packages\flask_sqlalchemy\extension.py", line 855, in _call_for_binds
engine = self.engines[key]
File "xxx\Python\Python38\lib\site-packages\flask_sqlalchemy\extension.py", line 636, in engines
app = current_app._get_current_object() # type: ignore[attr-defined]
File "xxx\Python\Python38\lib\site-packages\werkzeug\local.py", line 513, in _get_current_object
raise RuntimeError(unbound_message) from None
RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that needed
the current application. To solve this, set up an application context
with app.app_context(). See the documentation for more information.
源代码如下(代码借鉴于站内另一大佬文章):
运行环境软件包版本:flask_sqlalchemy:3.0.3
,flask:2.2.3
:
# -*- coding: UTF-8 -*-
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:[email protected]:3306/test'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_ECHO'] = True
# 创建组件对象
db = SQLAlchemy(app)
# 构建模型类 类->表 类属性->字段 实例对象->记录
class User(db.Model):
__tablename__ = 't_user' # 设置表名, 表名默认为类名小写
id = db.Column(db.Integer, primary_key=True) # 设置主键, 默认自增
name = db.Column('username', db.String(20), unique=True) # 设置字段名 和 唯一约束
age = db.Column(db.Integer, default=10, index=True) # 设置默认值约束 和 索引
if __name__ == '__main__':
db.drop_all()
db.create_all()
app.run(debug=True)
运行代码时出现文章开头错误,网上查询解决方法未果。重新阅读报错信息,发现信息最后一行To solve this, set up an application context with app.app_context()
。于是找到app.app_context()
源码,部分如下:
def app_context(self) -> AppContext:
"""Create an :class:`~flask.ctx.AppContext`. Use as a ``with``
block to push the context, which will make :data:`current_app`
point at this application.
An application context is automatically pushed by
:meth:`RequestContext.push() <flask.ctx.RequestContext.push>`
when handling a request, and when running a CLI command. Use
this to manually create a context outside of these situations.
::
with app.app_context():
init_db()
发现使用方法为:
with app.app_context():
init_db() # 这个地方替换为自己需要运行的函数/方法
于是将源码更改为:
# -*- coding: UTF-8 -*-
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:[email protected]:3306/test'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_ECHO'] = True
# 创建组件对象
db = SQLAlchemy(app)
# 构建模型类 类->表 类属性->字段 实例对象->记录
class User(db.Model):
__tablename__ = 't_user' # 设置表名, 表名默认为类名小写
id = db.Column(db.Integer, primary_key=True) # 设置主键, 默认自增
name = db.Column('username', db.String(20), unique=True) # 设置字段名 和 唯一约束
age = db.Column(db.Integer, default=10, index=True) # 设置默认值约束 和 索引
if __name__ == '__main__':
with app.app_context():
# 删除所有继承自db.Model的表
db.drop_all()
# 创建所有继承自db.Model的表
db.create_all()
app.run(debug=True)
运行程序后,成功建表
2023-03-10 09:47:41,843 INFO sqlalchemy.engine.Engine
CREATE TABLE t_user (
id INTEGER NOT NULL AUTO_INCREMENT,
username VARCHAR(20),
age INTEGER,
PRIMARY KEY (id),
UNIQUE (username)
)
数据库内也建表成功,问题解决