1 .配置应用和基本使用
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
app.db.Model.metadata
手机扫一扫
移动阅读更方便
你可能感兴趣的文章