Flask-SQLAlchemy 组件
让我们认识SQLAlchemy,它是一个python的第三方ORM数据库操作模块,点击这里学习SQLAlchemy
大家都知道flask框架是一个轻量级框架,框架本身没有像Django框架一样的Model来操作数据库,第三方组件Flask-SQLAlchemy就这么诞生了
一、安装flask-sqlalchemy
# 安装flask-sqlalchemy pip install Flask-SQLAlchemy
二、flask蓝图目录实例(登录实例)
2.1 登录视图函数的应用(MyApp/views/user.py)
from flask import Blueprint, request, render_template user = Blueprint("user", __name__) from MyApp.models import Users from MyApp import db @user.route("/login",methods=["POST","GET"]) def user_login(): if request.method == "POST": username = request.form.get("username") password = request.form.get("password") # 还记不记得我们的 # from sqlalchemy.orm import sessionmaker # Session = sessionmaker(engine) # db_sesson = Session() # 现在不用了,因为 Flask-SQLAlchemy 也已经为我们做好会话打开的工作 # 我们在这里做个弊: db.session.add(Users(username=username,password=password)) db.session.commit() # 然后再查询,捏哈哈哈哈哈 user_info = Users.query.filter(Users.username == username and User.password == password).first() print(user_info.username) if user_info: return f"登录成功{user_info.username}" return render_template("login.html")
2.2 建立models.py ORM模型文件(MyApp/models.py)
from MyApp import db Base = db.Model # 这句话你是否还记的? # from sqlalchemy.ext.declarative import declarative_base # Base = declarative_base() # 每一次我们在创建数据表的时候都要做这样一件事 # 然而Flask-SQLAlchemy已经为我们把 Base 封装好了 # 建立User数据表 class Users(Base): # Base实际上就是 db.Model __tablename__ = "users" __table_args__ = {"useexisting": True} # 在SQLAlchemy 中我们是导入了Column和数据类型 Integer 在这里 # 就和db.Model一样,已经封装好了 id = db.Column(db.Integer,primary_key=True) username = db.Column(db.String(32)) password = db.Column(db.String(32)) if __name__ == '__main__': from MyApp import create_app app = create_app() # 这里你要回顾一下Flask应该上下文管理了 # 离线脚本: with app.app_context(): db.drop_all() db.create_all()
2.3 加入Flask-SQLAlchemy第三方组件(MyApp/__init__.py),Myapp是一个包
from flask import Flask # 导入Flask-SQLAlchemy中的SQLAlchemy from flask_sqlalchemy import SQLAlchemy # 实例化SQLAlchemy db = SQLAlchemy() # PS : 实例化SQLAlchemy的代码必须要在引入蓝图之前 from .views.users import user def create_app(): app = Flask(__name__) # 初始化App配置 这个app配置就厉害了,专门针对 SQLAlchemy 进行配置 # SQLALCHEMY_DATABASE_URI 配置 SQLAlchemy 的链接字符串儿 app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:DragonFire@127.0.0.1:3306/dragon?charset=utf8" # SQLALCHEMY_POOL_SIZE 配置 SQLAlchemy 的连接池大小 app.config["SQLALCHEMY_POOL_SIZE"] = 5 # SQLALCHEMY_POOL_TIMEOUT 配置 SQLAlchemy 的连接超时时间 app.config["SQLALCHEMY_POOL_TIMEOUT"] = 15 app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False # 初始化SQLAlchemy , 本质就是将以上的配置读取出来 db.init_app(app) app.register_blueprint(user) return app
三、flask蓝图目录实例(增加/查询操作)
3.1 蓝图目录结构,app是包结构
3.2 蓝图的视图应用,(app/views/user.py)
from flask import Blueprint from day10120190731.app.models import db, Users user_bp = Blueprint("user_bp", __name__) # 向数据库添加一条记录 @user_bp.route("/add_user/<username>", methods=["POST", "GET"]) def add_user(username): u = Users(name=username) db.session.add(u) db.session.commit() return f"名字 {username} 添加成功!" # 查询一条记录 @user_bp.route("/get_user/<username>", methods=["POST", "GET"]) def get_user(username): ret = Users.query.filter(Users.name == username).first() # print(ret.name) return str(ret.name)
3.3 model文件的建立,(app/model.py)
from flask_sqlalchemy import SQLAlchemy # 实例化db对象 db = SQLAlchemy() class Users(db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(32), nullable=False) if __name__ == '__main__': from day10120190731.app import create_app app = create_app() # 创建数据库 db.create_all(app=app) # 删除数据库 # db.drop_all(app=app)
3.3 加入Flask-SQLAlchemy第三方组件,(app/__init__.py)
from flask import Flask from day10120190731.app.models import db from day10120190731.app.views.user import user_bp def create_app(): app = Flask(__name__) app.config["DEBUG"] = True app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:1234@127.0.0.1:3306/db4?charset=utf8" app.config["SQLALCHEMY_POOL_SIZE"] = 50 app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app) app.register_blueprint(user_bp) return app
3.4 flask启动文件app_manager,(day10120190731/app_manager.py)
from day10120190731.app import create_app app = create_app() if __name__ == '__main__': app.run()
https://www.cnblogs.com/WiseAdministrator/