欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python FLASK-SQLAlchemy

程序员文章站 2024-03-03 18:19:58
...

第一次使用时出现一些错误,正确的代码

# -*- coding:utf-8 -*-
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:[email protected]/pyweb'
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

db = SQLAlchemy(app)


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 {}>'.format(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('roles.id'))

    def __repr__(self):
        return '<User {}>'.format(self.username)



def test():
    # 创建数据库
    db.create_all()
    # 插入行,即创建角色和用户
    admin_role = Role(name='Admin')
    mod_role = Role(name='Moderator')
    user_role = Role(name='User')
    user_john = User(username='john', role=admin_role)
    user_susan = User(username='susan', role=user_role)
    user_david = User(username='david', role=user_role)
    # 准备把对象写入数据库前,先要将其调价到会话中
    db.session.add(mod_role)
    db.session.add(user_role)
    db.session.add(user_john)
    db.session.add(user_susan)
    db.session.add(user_david)
    # 提交会话,写入数据库
    db.session.commit()
    # 修改行
    admin_role.name = 'Administrator'
    db.session.add(admin_role)
    db.session.commit()
    # 删除行
    db.session.delete(mod_role)
    db.session.commit()
    # 查询
    Role.query.all()
    # 使用过滤器,条件查询
    User.query.filter_by(role=user_role).all()


if __name__ == '__main__':
    test()