day03

今日内容

  • 蓝图的使用
  • g对象
  • 数据库连接池

蓝图的使用

blueprint 翻译过来的,称之为蓝图

作用是:之前全在一个py中写flask项目,后期肯定要划分目录

  • 不用蓝图,划分目录

    image-20230404154929614

# 不用蓝图,划分目录
	no_blueprint_flask  # 项目名
        src             #核心源码位置
            __init__.py # 包 里面实例化得到了app对象,
            models.py   #放表模型
            views.py    # 放视图函数
        static          # 放静态资源
        templates       # 放模板
        	home.html   # 模板
        manage.py       # 启动文件

蓝图的使用步骤

  1. 导入蓝图类

    from flask  import Blueprint
    
  2. 实例化得到蓝图对象

    image-20230404160326136

    us = Bluepring("user", __name__)
    
  3. 在app中注册蓝图

    app.register_blueprint(us)

  4. 第四步

    在不同的views.py使用蓝图注册路由

    @us.route("/login")
    

补充:蓝图可以有自己的静态文件和模板

补充:注册蓝图时,可以使用前缀,必须以/开头

使用蓝图划分小型项目

image-20230404161556727

# 使用蓝图,划分小型项目目录
    little_blueprint              # 项目名
        -src                      # 核心代码
            -static               # 静态文件
                -1.jpg            # 图片
            -templates            # 模板文件
            -user.html            # 模板
            -views                # 视图函数存放位置
                -order.py         # 订单相关视图
                -user.py          # 用户相关视图
            -__init__.py          # 包
            -models.py            # 表模型
        -manage.py                # 启动文件

image-20230404164740170

image-20230404164812448

大型项目 app的一个init文件

image-20230404165326610

image-20230404165352144

# 使用蓝图,划分大型项目目录  多个app,像django一样
big_blueprint  								# 项目名
    -src									# 核心文件
        -admin								# admin的app
        	-static							# 静态文件
        		-1.jpg						# 图片
        	-templates						# 模板文件目录
        		-admin_home.html			# 模板文件
        	-__init__.py					# 包
        	-models.py						# 表模型
        	-views.py						# 视图函数
        -home								# home app
        -order								# orderapp
        -__init__.py						# 包
        -settings.py						# 配置文件
    -manage.py								# 启动文件

每一个蓝图都有自己的请求扩展,与其他蓝图互补干扰,

@user.before_request

app的请求扩展是全局的

g对象

g对象是什么

global的缩写,在python中是个关键字,不能以关键字作为变量名,干脆用了g

g 对象,在整个请求的全局,可以放值,可以取值

全局变量,在任意位置导入使用即可

它为什么不学dajngo使用request作为上下文

因为使用request,可能会造成request数据污染,不小心改了request属性,但是你不知道

g和session有什么区别

g 只针对当此请求

session针对于多次请求

使用

from flask import Flask, g

app = Flask(__name__)
app.debug = True


def add():
    print(g.xx)


@app.route("/")
def home():
    g.xx = 'xx'
    add()
    return "home"


@app.route("/index")
def index():
    add()
    return "index"


if __name__ == '__main__':
    app.run()

我访问/执行home,把xx放到 g.xx然后add去g里面取出xx

我访问/index执行index然后执行add这次请求中没有往g里面放xx对象点一个不存在的属性会执行__getattr__如果没有做操作,则直接报没有这个属性。而g直接报错

image-20230404170912535

image-20230404170918638

访问index

image-20230404170936366

image-20230404170943288

数据连接池

flask 操作mysql

  • 使用pymysql

    在视图函数中,创建pymysql的连接,查数据,查完,返回给前端

  • 有什么问题?来一个请求,创建一个连接,请求结束,连接关闭(django就是这么做的)

  • 把连接对象,做成全局的,在视图函数中,使用全局的连接,查询,返回给前端

image-20230404171824660

解决上面的问题

  • 数据库连接池
  • 创建一个全局的池
  • 每次进入视图函数,从池中取出一个连接使用,使用完返回到池中,只要控制池的大小,就能控制mysql连接数

使用

  1. 按照pip install dbutils
  2. 使用:实例化得到一个池对象
  3. 在视图函数中导入使用

连接池

from DBUtils.PooledDB import PooledDB
import pymysql

POOL = PooledDB(
    creator=pymysql,  # 使用链接数据库的模块
    maxconnections=6,  # 连接池允许的最大连接数,0和None表示不限制连接数
    mincached=2,  # 初始化时,链接池中至少创建的空闲的链接,0表示不创建
    maxcached=5,  # 链接池中最多闲置的链接,0和None不限制
    maxshared=3,
    # 链接池中最多共享的链接数量,0和None表示全部共享。PS: 无用,因为pymysql和MySQLdb等模块的 threadsafety都为1,所有值无论设置为多少,_maxcached永远为0,所以永远是所有链接都共享。
    blocking=True,  # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
    maxusage=None,  # 一个链接最多被重复使用的次数,None表示无限制
    setsession=[],  # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."]
    ping=0,
    # ping MySQL服务端,检查是否服务可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always
    host='127.0.0.1',
    port=3306,
    user='root',
    password='123',
    database='luffy',
    charset='utf8',
    autocommit='True'
)


逻辑

"""
conn = pool.connection()
cursor = conn.cursor(pymysql.cursors.DictCursor)
cursor.execute("select id,name from luffy_course limit 2")
res = cursor.fetchall()

"""
import pymysql

from myPool import POOL
from flask import Flask

app = Flask(__name__)


@app.route("/")
def home():
    conn = POOL.connection()
    cursor = conn.cursor()
    cursor.execute("select id,name from luffy_course")
    res = cursor.fetchall()
    print(res)
    return "哈哈"

if __name__ == '__main__':
    app.run()

image-20230404183445262

image-20230404183456072

posted @ 2023-04-04 19:17  可否  阅读(35)  评论(0)    收藏  举报