flask-sqlalchemy是Flask和SQLAlchemy的管理者
- db = SQLAlchemy()
- 包含配置
- 包含ORM基类
- 包含create_all
- engine
- 创建连接
举例:
views中的account.py
#!/usr/bin/env python # -*- coding:utf-8 -*- from flask import Blueprint from .. import db from .. import models account = Blueprint('account', __name__) @account.route('/login') def login(): # 添加示例 """ db.session.add(models.Users(username='alex', pwd='123', gender=1)) db.session.commit() obj = db.session.query(models.Users).filter(models.Users.id == 1).first() print(obj) PS: db.session和db.create_session """ # db.session.add(models.Users(username='wupeiqi1', email='wupeiqi1@xx.com')) # db.session.commit() # db.session.close() # # db.session.add(models.Users(username='wupeiqi2', email='wupeiqi2@xx.com')) # db.session.commit() # db.session.close() # db.session.add(models.Users(username='alex1',email='alex1@live.com')) # db.session.commit() # db.session.close() user_list = db.session.query(models.Users).all() db.session.close() for item in user_list: print(item.username) return 'login'
__init__.py
#!/usr/bin/env python # -*- coding:utf-8 -*- from flask import Flask from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() from .models import * from .views import account def create_app(): app = Flask(__name__) app.config.from_object('settings.DevelopmentConfig') # 将db注册到app中 db.init_app(app) # 注册蓝图 app.register_blueprint(account.account) return app
models.py
#!/usr/bin/env python # -*- coding:utf-8 -*- from . import db class Users(db.Model): """ 用户表 """ __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) email = db.Column(db.String(120), unique=True, nullable=False) def __repr__(self): return '<User %r>' % self.username
create_table.py
from sansa import create_app from sansa import db app = create_app() with app.app_context(): db.create_all()
run.py
#!/usr/bin/env python # -*- coding:utf-8 -*- """ 生成依赖文件: pipreqs ./ """ from sansa import create_app app = create_app() if __name__ == '__main__': app.run()
settings.py
#!/usr/bin/env python # -*- coding:utf-8 -*- class BaseConfig(object): # SESSION_TYPE = 'redis' # session类型为redis # SESSION_KEY_PREFIX = 'session:' # 保存到session中的值的前缀 # SESSION_PERMANENT = True # 如果设置为False,则关闭浏览器session就失效。 # SESSION_USE_SIGNER = False # 是否对发送到浏览器上 session:cookie值进行加密 SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root@127.0.0.1:3306/s7day145_2?charset=utf8" SQLALCHEMY_POOL_SIZE = 5 SQLALCHEMY_POOL_TIMEOUT = 30 SQLALCHEMY_POOL_RECYCLE = -1 # 追踪对象的修改并且发送信号 SQLALCHEMY_TRACK_MODIFICATIONS = False class ProductionConfig(BaseConfig): pass class DevelopmentConfig(BaseConfig): pass class TestingConfig(BaseConfig): pass
目录结构
项目根目录下
sansa目录下
views目录下