除了需要自己导入,增删改查等方法与sqlalchemy模块使用没有差别
1、安装
pip install flask-sqlalchemy
2、创建Flask app文件中导入例如__init__.py
# 导入并实例化SQLAlchemy from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() # 初始化 db.init_app(app)
from flask import Flask from flask_session import Session from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() from flask_demo.views import account, user from flask_demo.models import * def create_app(): app = Flask(__name__) # 配置项 app.config.from_object("settings.DevConfig") app.secret_key = app.config["SECRET_KEY"] # 注册蓝图 app.register_blueprint(account.ac, ) app.register_blueprint(user.us) # 将session的值存放至redis,配置信息在settings中 Session(app) # 初始化SQLAlchemy db.init_app(app) return app
3、在配置文件中写入配置
# ##### SQLALchemy配置文件 ##### SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:123456@127.0.0.1:3306/userinfo?charset=utf8" SQLALCHEMY_POOL_SIZE = 10 #线程池最大数量 SQLALCHEMY_MAX_OVERFLOW = 5 # 线程池数量最大溢出数量
4、创建models.py中的类(对应数据库表)
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column from sqlalchemy import Integer,String,Text,Date,DateTime from sqlalchemy import create_engine from flask_demo import db class School(db.Model): __tablename__ = ‘school‘ id = Column(Integer, primary_key=True) name = Column(String(32), index=True, nullable=False) depart_id = Column(Integer)
5、写一个脚本,用于生成表(需要使用app上下文):只能生成和删除表,不能对表字段进行更新或者修改
from flask_demo import db, create_app app = create_app() app_ctx = app.app_context() # app_ctx = app/g with app_ctx: # __enter__,通过LocalStack放入Local中 db.create_all() # 调用LocalStack放入Local中获取app,再去app中获取配置
6、基于ORM对数据库进行操作
from flask import Blueprint, session from flask_demo import db from flask_demo import models ac = Blueprint("ac", __name__) @ac.route("/index") def index(): session["user_id"] = 1 # db.session.add(models.School(name="清华大学计算机科学系", depart_id=1)) # db.session.commit() # 提交更新 # db.session.remove() # 关闭连接 ret = db.session.query(models.School).all() print(ret) db.session.remove() return "index"