1.安装
pip3 isntall flask-sqlalchemy
2.实例化一个sqlalchemy对象
# __init__.py
from flask import Flask
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
# 因为是初始化数据库,所以操作要放在__init__.py文件中。
# manager.py文件中只需要执行app.run()启动flask即可。
3.初始化数据库表
# 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 day122 import db # 倒入刚才生成的sqlalchemy对象
class Users(db.Model):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(32), index=True, nullable=False)
# depart_id = Column(Integer)
# __init__.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
from .models import *
def create_app():
app = Flask(__name__)
app.config.from_object('settings.ProdConfig')
app.register_blueprint(ac)
app.register_blueprint(user)
# Session(app)
db.init_app(app)
return app
# 这里from .models import *操作必须放在实例化sqlalchemy之后,因为该操作倒入的db模块里面使用了sqlalchemy对象。
4.手动创建数据库表
from mywork 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中获取配置
5.使用数据库
from mywork import db
from mywork import models
@ac.route('/login')
def login():
ret = db.session.query(models.Users).all()
for row in ret:
print(row.id,row.name)
return 'Login'
6.数据库表的迁移
依赖:flask-script
pip3 install flask-migrate
from flask_migrate import Migrate, MigrateCommand
Migrate(app, db)
"""
# 数据库迁移命名
python manage.py db init
python manage.py db migrate
python manage.py db upgrade
"""
manager.add_command('db', MigrateCommand)