• flask 使用 SQLAlchemy 的两种方式


    1. 使用 flask-SQLAlchemy 扩展

    # flask-ext-sqlalchemy.py
    
    from flask import Flask
    from flask.ext.sqlalchemy import SQLAlchemy
    
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    db = SQLAlchemy(app)
    
    
    # 定义ORM
    class User(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(80), unique=True)
        email = db.Column(db.String(120), unique=True)
    
        def __init__(self, name, email):
            self.name = name
            self.email = email
    
        def __repr__(self):
            return '<User %r>' % self.name
            
    
    # 创建表格、插入数据
    @app.before_first_request
    def setup():
        # Recreate database each time for demo
        db.create_all()
        
        admin = User('admin', 'admin@example.com')
        db.session.add(admin)
    
        guestes = [User('guest1', 'guest1@example.com'),
                   User('guest2', 'guest2@example.com'),
                   User('guest3', 'guest3@example.com'),
                   User('guest4', 'guest4@example.com')]
        db.session.add_all(guestes)
        db.session.commit()
        
        
    # 查询
    @app.route('/user')
    def users():
        users = User.query.all()
        return "<br>".join(["{0}: {1}".format(user.name, user.email) for user in users])
        
    # 查询
    @app.route('/user/<int:id>')
    def user(id):
        user = User.query.filter_by(id=id).one()
        return "{0}: {1}".format(user.name, user.email)
        
    # 运行
    if __name__ == '__main__':
        app.run('127.0.0.1', 5000) 

    2. 使用原生 SQLAlchemy

    # flask-pure-sqlalchemy.py
    
    from flask import Flask
    from sqlalchemy import Column, Integer, String
    from sqlalchemy import create_engine
    from sqlalchemy.orm import Session
    from sqlalchemy.ext.declarative import declarative_base
    
    app =  Flask(__name__)
    
    Base = declarative_base()
    # 定义ORM
    class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String(50), unique=True) email = Column(String(120), unique=True) def __init__(self, name=None, email=None): self.name = name self.email = email def __repr__(self): return '<User %r>' % (self.name) # 创建表格、插入数据 @app.before_first_request def setup(): # Recreate database each time for demo engine = create_engine('sqlite://', echo=True) global session session = Session(engine) Base.metadata.drop_all(bind=engine) Base.metadata.create_all(bind=engine) admin = User('admin', 'admin@example.com') session.add(admin) guestes = [User('guest1', 'guest1@example.com'), User('guest2', 'guest2@example.com'), User('guest3', 'guest3@example.com'), User('guest4', 'guest4@example.com')] session.add_all(guestes) session.commit() # 查询 @app.route('/user') def users(): users = session.query(User).all() return "<br>".join(["{0}: {1}".format(user.name, user.email) for user in users]) @app.route('/user/<int:id>') def user(id): user = session.query(User).filter(User.id == id).one() return "{0}: {1}".format(user.name, user.email) if __name__ == '__main__': app.run('127.0.0.1', 5000)

    区别

  • 相关阅读:
    Arduino 各种模块篇 DHT11 温度湿度 数字模块 单总线
    Arduino 各种模块篇 火焰传感器
    exception
    google c++ code style
    昙花一现
    晏才宏
    win 2003 玩3D游戏设置
    生成多文件的Assembly 的两种方法
    怎样使自己写的程序集出现在Visual Studio Add Reference 的 .NET Tab页中
    安装将仅在管理模式下运行,安装终止
  • 原文地址:https://www.cnblogs.com/hhh5460/p/5529538.html
Copyright © 2020-2023  润新知