flask不像django,django有自己的ORM集成实现。flask一般使用sqlalchemy进行集成开发,网上已有flask-sqlchrmy可以直接使用。下面来个入门demo。
安装flask、flask-SQLAlchemy
pip install flask pip install flask-SQLAlchemy
建立三个表的ORM对象,分别是user、post、category。
其中post与category有外键关联。
import datetimefrom flask import Flaskfrom flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///tmp/test.db'app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = Falsedb = SQLAlchemy(app)class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) def __init__(self, username, email): self.username = username self.email = email def __repr__(self): return '<User %r>' % self.usernameclass Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(80)) body = db.Column(db.Text) pub_date = db.Column(db.DateTime) category_id = db.Column(db.Integer, db.ForeignKey('category.id')) category = db.relationship('Category', backref=db.backref('posts', lazy='dynamic')) def __init__(self, title, body, category, pub_date=None): self.title = title self.body = body if pub_date is None: pub_date = datetime.datetime.utcnow() self.pub_date = pub_date self.category = category def __repr__(self): return '<Post %r>' % self.titleclass Category(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50)) def __init__(self, name): self.name = name def __repr__(self): return '<Category %r>' % self.name
一些基本操作
from demo import db, User, Category, Post#创建数据库与表db.create_all()#创建User对象并插入数据库admin = User('admin', 'admin@example.com') guest = User('guest', 'guest@example.com') db.session.add(admin) db.session.add(guest) db.session.commit()#查询users = User.query.all() admin = User.query.filter_by(username='admin').first()#创建Post与Category并插入数据库py = Category('python') p = Post('Hello python!', 'pytho is pretty cool', py) db.session.add(py) db.session.add(p) db.session.commit()
作者:oshimaRyu
链接:https://www.jianshu.com/p/e289068f2d03