美文网首页python自学
flask开发之flask-SQLAlchemy

flask开发之flask-SQLAlchemy

作者: 晚上吃火锅吗 | 来源:发表于2018-10-04 15:22 被阅读51次

    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 datetime
    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///tmp/test.db'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db = 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.username
    
    class 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.title
    
    class 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()
    

    参考链接:
    http://flask-sqlalchemy.pocoo.org/2.3/quickstart/#a-minimal-application

    相关文章

      网友评论

      本文标题:flask开发之flask-SQLAlchemy

      本文链接:https://www.haomeiwen.com/subject/mqpxaftx.html