Flask 如何在代码中往数据库插入数据

在models函数中:

@staticmethod
def insert_roles():
    roles = {
        'User': (Permission.FOLLOW |
                 Permission.COMMENT |
                 Permission.WRITE_ARTICLES, True),
        'Moderator': (Permission.FOLLOW |
                      Permission.COMMENT |
                      Permission.WRITE_ARTICLES |
                      Permission.MODERATE_COMMENTS, False),
        'Administrator': (0xff, False)
    }
    for r in roles:
        role = Role.query.filter_by(name=r).first()
        if role is None:
            role = Role(name=r)
        role.permissions = roles[r][0]
        role.default = roles[r][1]
        db.session.add(role)
    db.session.commit()

在manage.py  中添加插入的命令:

 

@manager.command
def insertdb():
    from flask_migrate import upgrade
    upgrade()
    Role.insert_roles()

你可能感兴趣的:(FlaskPython,flask,python)