首页 > 代码库 > Flask入门之SQLAlchemy配置与数据库连接

Flask入门之SQLAlchemy配置与数据库连接

1. 安装SQLAlchemy

pip install flask-sqlalchemy

2. 导入和配置

from flask_sqlalchemy import SQLAlchemy
basedir = path.dirname(__file__)

app.config.from_pyfile(config)
app.config[SQLALCHEMY_DATABASE_URI] =     sqlite:/// + path.join(base.dir, data.sqlite)
app.config[SQLALCHEMY_COMMIT_ON_TEARDOWN] = True

3. 创建表类

class Role(db.Model):
    __tablename__ = roles
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=True)
    users = db.relationship(User, backref=True)


class User(db.Model):
    __tablename__ = users
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=True)
    password = db.Column(db.String, devnull=True)
    role_id = db.Column(db.Integer,db.ForeignKey(roles.id))

 

Flask入门之SQLAlchemy配置与数据库连接