Flask的数据库框架是 Flask-SQLAlchemy
1.安装Flask-SQLAlchemy
(venv) $ pip install flask-sqlalchemy
2.配置数据库
from flask.ext.sqlalchemy import SQLAlchemy basedir = os.path.abspath(os.path.dirname(__file__)) app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] =\ 'sqlite:///' + os.path.join(basedir, 'data.sqlite') app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True db = SQLAlchemy(app)
3.定义模型
class Role(db.Model): __tablename__ = 'roles' 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) username = db.Column(db.String(64), unique=True, index=True) def __repr__(self): return '<User %r>' % self.username
4.定义关系
一对多的关系
class Role(db.Model): # ... users = db.relationship('User', backref='role') class User(db.Model): # ... role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
5.数据库操作
Flask-SQLAlchemy 根据模型类创建数据库
(venv) $ python hello.py shell >>> from hello import db >>> db.create_all()
(1).插入记录
>>> from hello import Role, User >>> 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)
(2)删除记录
>>> user = User.query.filter_by(username='john').first()
>>> db.session.delete(user)
>>> db.session.commit()
(3)修改记录
>>> admin_role.name = 'Administrator' >>> db.session.add(admin_role) >>> db.session.commit()
(4)查询记录
查询表中的所有记录
>>> Role.query.all() [<Role u'Administrator'>, <Role u'User'>] >>> User.query.all() [<User u'john'>, <User u'susan'>, <User u'david'>]
使用过滤器可以配置 query 对象进行更精确的数据库查询。下面这个例子查找角色为
"User" 的所有用户
>>> User.query.filter_by(role=user_role).all() [<User u'susan'>, <User u'david'>]