Flask 学习 四 数据库
class Role(db.Model): __tablename__='roles' id = db.Column(db.Integer,primary_key=True) name = db.Column(db.String(64),unique=True) users = db.relationship('User',backref='role') def __repr__(self): return '<Role %r>'% self.name class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), unique=True,index=True) role_id=db.Column(db.Integer,db.ForeignKey('role.id')) def __repr__(self): return '<User %r>' % self.username
设置SQLALCHEMY_TRACK_MODIFICATIONS 为True或False
报错:FSADeprecationWarning:
需要:提示给的839行,在前面几行的位置有这样的setdefault,
把None改为True;:
视图函数中操作数据库
@app.route('/', methods=['get', 'post']) def index1(): #name = None form = NameForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.name.data).first() if user is None: user = User(username=form.name.data) db.session.add(user) session['known']=False else: session['known'] = True session['name']=form.name.data form.name.data='' return redirect(url_for('index1')) return render_template('index.html', name=session.get('name'), form=form, known=session.get('known',False))
# 集成python shell def make_shell_context(): return dict(app=app, db=db, User=User, Role=Role) manager.add_command("shell", Shell(make_context=make_shell_context))
数据库迁移
pip install flask-migrate
from flask_migrate import Migrate,MigrateCommand
# 数据库迁移 migrate = Migrate(app,db) manager.add_command('db',MigrateCommand)
# init命令创建迁移仓库
python flask_blog.py db init
# 创建迁移脚本
python flask_blog.py db migrate -m 'initial migration'
# 更新数据库
python flask_blog.py db upgrade