sqlalchemy增删改查

今天整理一下flask-sqlalchemy对数据库的操作, 基础代码如下

cat flaskStudy.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import os
basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data.sqllist')
db = SQLAlchemy(app)

class Role(db.Model):
    __tablename__ = 'roles'
    users = db.relationship('User', backref='role')  # roles表与users表一对多的映射关系
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)

    def __repr__(self):
        return "<Role %r>" % self.name

class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))  # role_id 的值根据伪列role的值(指向roles对象)自动生成
    username = db.Column(db.String(64), unique=True, index=True)

    def __repr__(self):
        return "<User %r>" % self.username



if __name__ == '__main__':
    app.run()
  

  

  两张表:roles, users, 一对多关系

1、数据插入

(venv) D:\flaskStudy>set FLASK_APP=flaskStudy.py

(venv) D:\flaskStudy>set FLASK_DEBUG=1

(venv) D:\flaskStudy>flask shell
Python 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 16:02:32) [MSC v.1900 64 bit (AMD64)] on win32
App: flaskStudy [production]
Instance: D:\flaskStudy\instance
>>> from flaskStudy import db, Role, User
>>> db.drop_all()  # 删除所有表
>>> 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)  # 创建用户对象, 根据role对象动态生成role_id
>>> user_susan=User(username='susan', role=user_role)
>>> user_david=User(username='david', role=user_role)
>>> db.session.add(admin_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()

  

2、数据查询

(venv) D:\flaskStudy>flask shell
Python 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 16:02:32) [MSC v.1900 64 bit (AMD64)] on win32
App: flaskStudy [production]
Instance: D:\flaskStudy\instance
>>> from flaskStudy import db, User, Role
>>> user_role=Role.query.filter_by(name='User').first()  # 查询一条roles数据
>>> user_role
<Role 'User'>
>>> user_role.users  # 根据users列正向查询users表对应的用户
[<User 'susan'>, <User 'david'>]
>>> user_david=User.query.filter_by(username='david').first() # 查询一条用户数据
>>> user_david
<User 'david'>
>>> user_david.role  # 根据伪列role查询对应的角色
<Role 'User'>
>>>

 

3、数据修改

(venv) D:\flaskStudy>flask shell
Python 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 16:02:32) [MSC v.1900 64 bit (AMD64)] on win32
App: flaskStudy [production]
Instance: D:\flaskStudy\instance
>>> from flaskStudy import db, User, Role
>>> Role.query.all()  # roles表有三条数据
[<Role 'Admin'>, <Role 'Moderator'>, <Role 'User'>]
>>> admin_role=Role.query.filter_by(name='Admin').first()  # 查询其中一条数据
>>> admin_role
<Role 'Admin'>
>>> admin_role.name='Administrator'  # 将name值修改为Administrator
>>> db.session.add(admin_role)
>>> db.session.commit()
>>> Role.query.all()
[<Role 'Administrator'>, <Role 'Moderator'>, <Role 'User'>]

  

4、删除数据

>>> Role.query.all()  # 角色中三条记录
[<Role 'Administrator'>, <Role 'Moderator'>, <Role 'User'>]
>>> user_role=Role.query.filter_by(name='User').first()  # 其中一条数据对象
>>> user_role
<Role 'User'>
>>> db.session.delete(user_role) # 删除此对象
>>> db.session.commit()
>>> Role.query.all()
[<Role 'Administrator'>, <Role 'Moderator'>]
>>> User.query.all()  # users表中后两条数据的role_id没有了依赖被置空
[<User 'John'>, <User 'susan'>, <User 'david'>]

  

5、集成Python shell

  每次启动flask shell会话都要手动导入数据库实例和模型才能进行数据库操作, 当启动flask shell时如何实现自动导入呢?

  shell_context_processor:  注册并创建一个shell上下文处理器。

@app.shell_context_processor  # 注册并创建shell上下文处理器
def make_shell_context():
    return dict(db=db, User=User, Role=Role)  # 返回包含实例和模型的字典


再次运行flask shell, 这些实例和模型都可以使用了

(venv) D:\flaskStudy>flask shell
Python 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 16:02:32) [MSC v.1900 64 bit (AMD64)] on win32
App: flaskStudy [production]
Instance: D:\flaskStudy\instance
>>> db
<SQLAlchemy engine=sqlite:///D:\flaskStudy\data.sqllist>
>>> app
<Flask 'flaskStudy'>
>>> User
<class 'flaskStudy.User'>
>>> Role
<class 'flaskStudy.Role'>

  

6、创建迁移仓库

  项目迁移后, 数据库同样需要迁移

from flask_migrate import Migrate
migrate = Migrate(app, db)

   db init子命令添加添加数据库迁移支持, 此时自动创建目录存储数据 

 

posted on 2020-06-05 13:19  孔扎根  阅读(555)  评论(0编辑  收藏  举报

导航