flask-sqlalchemy集成到flask中
1 下载模块
pip install flask-sqlalchemy --upgrade
2 __init__文件中导入模块
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__, template_folder='../templates', static_folder='../static')
app.config.from_pyfile('./settings.py')
# 等到app和db都创建完再导入
from .views.user import bp_user
app.register_blueprint(bp_user)
-------
# 实例化得到对象
db = SQLAlchemy()
# 将db注册到app中
db.init_app(app)
-------
# 以上两步可以合并为:
db = SQLAlchemy(app)
3 视图函数中使用session查询表数据
from flask import Blueprint, render_template, jsonify
from src.models import User
bp_user = Blueprint('user', __name__)
from src import db
@bp_user.route('/')
def index():
# 把用户表中所有数据都查出来,返回给前端
res = db.session.query(User).filter(User.id >= 1).all()
# 不行 json序列化,只能序列化 数字,字符串,布尔,列表,和字典
# res 列表套对象---》不能序列化
l = []
for item in res:
l.append({'name': item.name, 'email': item.email})
return jsonify({'code': 100, 'msg': "成功", 'results': l})
4 models.py 中继承 db.Model
import datetime
from . import db
class User(db.Model):
__tablename__ = 'users' # 表名
# 写字段
id = db.Column(db.Integer, primary_key=True, autoincrement=True) # id 主键
name = db.Column(db.String(32), index=True, nullable=False) # name列,索引,不可为空
email = db.Column(db.String(32), unique=True)
# datetime.datetime.now不能加括号,加了括号,以后永远是当前时间
ctime = db.Column(db.DateTime, default=datetime.datetime.now)
extra = db.Column(db.Text)
def __str__(self):
return self.name
def __repr__(self):
return self.name
5 配置文件中加入
SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:[email protected]:3306/sqlalchemy03?charset=utf8"
SQLALCHEMY_POOL_SIZE = 5
SQLALCHEMY_POOL_TIMEOUT = 30
SQLALCHEMY_POOL_RECYCLE = -1
# 追踪对象的修改并且发送信号
SQLALCHEMY_TRACK_MODIFICATIONS = False
标签:__,sqlalchemy,name,flask,app,db,模块,import
From: https://www.cnblogs.com/wellplayed/p/18066248