另外⼀个框架,叫做 Flask-SQLAlchemy
, Flask-SQLAlchemy
是对SQLAlchemy
进行了⼀个简单的封装,使得我们在 flask 中使用sqlalchemy 更加的简单。
可以通过pip install flask-sqlalchemy
。
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
# localhost
HOSTNAME = '127.0.0.1'
DATABASE = 'demo'
PORT = 3306
USERNAME = 'root'
PASSWORD = 'root'
DB_URL = 'mysql+mysqlconnector://{}:{}@{}:{}/{}?charset=utf8'.format(USERNAME, PASSWORD, HOSTNAME, PORT, DATABASE)
app = Flask(__name__)
# engine = create_engine(DB_URL)
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class User(db.Model):
# 如果不写__tablename__ 会以模型名字的小写来定义表名
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
article = db.relationship('Artcile', backref='user')
def __repr__(self):
return "User(name:%s)" % self.name
class Artcile(db.Model):
__tablename__ = 'article'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(50))
uid = db.Column(db.Integer, db.ForeignKey('users.id'))
# user = db.relationship('User', backref='article')
db.drop_all()
db.create_all()
# 添加数据
# user = User(name='ecithy')
# article = Artcile(title='python')
# article.user = user
# db.session.add(article)
# db.session.commit()
# 查询数据
# session.query()
# user = User.query.all()
# print(user)
# users = User.query.order_by(User.id.desc()).all()
# print(users)
# users = db.session.query(User).all()
# print(users)
# user = User.query.filter(User.name == 'ecithy').first()
# db.session.delete(user)
# db.session.commit()
@app.route("/")
def index():
return "首页"
if __name__ == '__main__':
app.run(debug=True)