flask-sqlalchemy的基本使用
flask-sqlalchemy
1 .配置应用和基本使用
和sqlalchemy一样,先定义好数据库配置和db_url。然后在app的config加入SQLALCHEMY_DATABASE_URI
等于配置好的db_url。在初始化db对象即可。
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from settings import DATABASES
app = Flask(__name__)
DB_URL = 'mysql+pymysql://{USERNAME}:{PASSWORD}@{HOST}:{PORT}/{DATABASE}'.format(**DATABASES)
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(50))
class Article(db.Model):
__tablename__ = 'article'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(50))
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
user = db.relationship('User', backref=db.backref(__tablename__, lazy='dynamic'))
@app.route('/')
def hello_world():
return 'hello world'
db.create_all()
# 增加数据
user = User(name='ivy')
article = Article(name='title')
article.user = user
db.session.add(article)
db.session.commit()
# 查询数据
first_user = user = db.session.query(User).first()
print(first_user.name)
print(first_user.article.first().name)
if __name__ == '__main__':
app.run()
2 .配合alembic
- alembic.ini的文件的配置不变
- 在alembic的文件夹的env.py中, 将生成的db对象文件模块导入,
app.db.Model.metadata