首页 > 其他分享 >Flask 05

Flask 05

时间:2023-04-06 21:35:18浏览次数:37  
标签:__ 05 Flask request self ctx session local

Flask 04

导出项目依赖模块

# 在此之前我们使用的是
pip freeze>requirments.text  
执行上面的命令,会将该解释环境下的所有的第三方依赖都导出来(这样不太好)

#使用第三方模块,更加精准的到处使用到的依赖 pipreqs

使用步骤:
	1.安装 pip install pipreqs
    2.使用命令,导出依赖  pipreqs ./
    -win系统:由于编码的问题会出错,使用:
    pipreqs ./ --encodeing =utf-8
    
    - mac linx是没什么问题的
    
    3. 执行而来上面的命令,它就会再项目的更路径生成一个:requirement.txt 文件

补充小知识:

函数和方法的区别:

概念: 只要是会自动传值的就是方法,
函数:有几个值就需要传几个值,否则就会报错
函数就是普通的函数,有几个参数就需要传几个参数

方法有:绑定给对象的方法,绑定给类的方法,绑定给谁的就是谁来调用就将自身传入

解释:
绑定给类的方法对象可以调用,就会将类自动传入
对象的绑定方法:类可以调用,但是它就会变成普通函数,有几个值就需要传几个参数,就不能自动传值了

检验是什么类型的方法:
MethodType :检验一个对象是否是一个方法
FunctionTYpe:检验一个对象是否是函数
isinstance :判断一个对象是否是一个类的对象
issubclass :判断一个类是否是另一个类的子类

from type import MethodType,FunctionType

代码:

class Foo(object):
    def fetch(self):
        pass

    @classmethod
    def test(cls):
        pass

    @staticmethod
    def test1():
        pass


# a=Foo()
# print(isinstance(a,Foo))
# print(isinstance('a',Foo))
#
# class Foo2(Foo):
#     pass
# class Foo3():
#     pass
# print(issubclass(Foo2,Foo))
# print(issubclass(Foo3,Foo))


def add():
    pass


# 类来调用对象的绑定方法,
print(isinstance(Foo.fetch, MethodType))  # False  类来调用对象的绑定方法,该方法就变成了普通函数
obj = Foo()
print(isinstance(obj.fetch, MethodType))  # True    对象来调用自己的绑定方法,fetch就是方法
print(isinstance(Foo.fetch, FunctionType))  # True   类来调用对象的绑定方法,该方法就变成了普通函数

print(isinstance(add, FunctionType))  # True  就是个普通函数
print(isinstance(add, MethodType))  # False  就是个普通函数


print(isinstance(Foo.test, MethodType))  # True test 是绑定给类的方法,类来调用,就是方法

print(isinstance(obj.test, MethodType))  # True  对象调用类的绑定方法,还是方法

print(isinstance(Foo.test1, MethodType))  # False 是普通函数
print(isinstance(obj.test1, MethodType))  # False 是普通函数
print(isinstance(obj.test1, FunctionType))  # True,静态方法,就是普通函数,对象和类都可以调用,有几个值就传几个值

threading.local对象

local 对象
	 1.并发编程时,多个线程操作同一个变量,就会出现并发安全的问题,这时候我们就需要加锁
	2.使用local 对象,多线程并发操作时,不需要加锁,也不会出现数据错乱的现象 ,threading.local
    3.其他的语言中也有ThreadLocal,像java的面试就会提问的比较多
    
local 的本质原理:
	多个线程修改同一个数据,复制多分变量给每个线程使用,为的就是每个线程开辟出一块空间出来进行存储数据
	每个线程操作的都是自己的那份数据,互相不会混乱
    
(1)threading local 和 flask的自定义local对象 
		- 基于本地线程 可以实现,为了支持协程,自己定义了一个local对象
(2) 请求到来
		封装  ctx = RequestContext(request,session)
				ctx -- 放入 Local __storage__ { 'id':{stack:[ctx]} }
(3)执行视图
		导入 request
		print(reqeust) -- >> localproxy __str__
		reqeust.method -- >> localproxy __getattr__
		reqeust + 1 -- >> localproxy __add__	
			调用 _lookup_req_object 函数  去local中的ctx 中 获取 reqeust session
(4) 请求结束
		ctx.auto_pop
		ctx 从 local 中移除

偏函数

概念:使用functools.partial(original_fuc,param1,param....)在原有函数基础上生成一个偏函数。

所谓偏函数,就是以原函数为基础,将某个位置上的参数固定住(默认是从第一个参数固定),后续参数重新扩展传递给原函数,对外则是生成一个新函数。

from functools import partial 

def add(a,b,c):
    return a+b+c

print(add(a,b,c)) # 必须要传三个参数,参数不够就会报错

add =partial(add,2)
"""
现在只有一个参数,后面需要的两个参数,需要到后面才会知道,借助于偏函数,先提前传入一个参数,后面的两个参数,后面再传
"""
print(add(3,4))

Flask整个生命执行流程图(1.1.4版本为例)

Flask 的整体流程
封装 requestContext 对象, full_dispatch_request(视图函数 执行), response返回

从app.run() 开始 -->>

Flask的call方法-->>

wsgi_app (封装RequestContext(request,session )对象到 localstack) -->>

full_dispatch_request(视图函数 执行) -->>

执行扩展(before_request) ,触发信号 -->>

获取response -->>

pop reqeust,session -- >>

结束
# 请求来了---》app()----->Flask.__call__--->self.wsgi_app(environ, start_response)
    def wsgi_app(self, environ, start_response):
        # environ:http请求拆成了字典
        # ctx对象:RequestContext类的对象,对象里有:当次的requets对象,app对象,session对象
        ctx = self.request_context(environ)
        error = None
        try:
            try:
                #ctx RequestContext类 push方法
                ctx.push()
                # 匹配成路由后,执行视图函数
                response = self.full_dispatch_request()
            except Exception as e:
                error = e
                response = self.handle_exception(e)
            except:
                error = sys.exc_info()[1]
                raise
            return response(environ, start_response)
        finally:
            if self.should_ignore_error(error):
                error = None
            ctx.auto_pop(error)
            
            
            
            
            
  # RequestContext :ctx.push
 def push(self):
		# _request_ctx_stack = LocalStack() ---》push(ctx对象)--》ctx:request,session,app
        _request_ctx_stack.push(self)
		#session相关的
        if self.session is None:
            session_interface = self.app.session_interface
            self.session = session_interface.open_session(self.app, self.request)

            if self.session is None:
                self.session = session_interface.make_null_session(self.app)
		# 路由匹配相关的
        if self.url_adapter is not None:
            self.match_request()
            
            
            
# LocalStack()  push --->obj 是ctx对象
    def push(self, obj):
        #self._local  _local 就是咱们刚刚自己写的Local的对象---》LocalStack的init初始化的_local---》self._local = Local()---》Local对象可以根据线程协程区分数据 
        rv = getattr(self._local, "stack", None)
        # 一开始没有值
        if rv is None:
            rv = []
            self._local.stack = rv  # self._local.stack 根据不同线程用的是自己的数据
        rv.append(obj)  # self._local.stack.append(obj)
        # {'线程id号':{stack:[ctx]},'线程id号2':{stack:[ctx]}}
        return rv
    
    
    
 # 再往后执行,就会进入到路由匹配,执行视图函数
	# request = LocalProxy(partial(_lookup_req_object, "request"))
    # LocalProxy 代理类---》method---》代理类去当前线程的stack取出ctx,取出当时放进去的request
	视图函数中:print(request.method)
    
    
# print(request) 执行LocalProxy类的__str__方法
# request.method 执行LocalProxy类的__getattr__
    def __getattr__(self, name): #name 是method
        # self._get_current_object() 就是当次请求的request
        return getattr(self._get_current_object(), name)
    
    
 # LocalProxy类的方法_get_current_object
   def _get_current_object(self):
        if not hasattr(self.__local, "__release_local__"):
            return self.__local()
        try:
            return getattr(self.__local, self.__name__)
        except AttributeError:
            raise RuntimeError("no object bound to %s" % self.__name__)
            
            
            
 # self.__local 是在 LocalProxy 类实例化的时候传入的local

# 在这里实例化的:request = LocalProxy(partial(_lookup_req_object, "request"))
# local 是 partial(_lookup_req_object, "request")

#_lookup_req_object ,name=request
def _lookup_req_object(name):
    top = _request_ctx_stack.top  # 取出了ctx,是当前线程的ctx
    if top is None:
        raise RuntimeError(_request_ctx_err_msg)
    return getattr(top, name)  #从ctx中反射出request,当次请求的request
请求上下文执行流程(ctx):
		-0 flask项目一启动,有6个全局变量
			-_request_ctx_stack:LocalStack对象
			-_app_ctx_stack :LocalStack对象
			-request : LocalProxy对象
			-session : LocalProxy对象
		-1 请求来了 app.__call__()---->内部执行:self.wsgi_app(environ, start_response)
		-2 wsgi_app()
			-2.1 执行:ctx = self.request_context(environ):返回一个RequestContext对象,并且封装了request(当次请求的request对象),session,flash,当前app对象
			-2.2 执行: ctx.push():RequestContext对象的push方法
				-2.2.1 push方法中中间位置有:_request_ctx_stack.push(self),self是ctx对象
				-2.2.2 去_request_ctx_stack对象的类中找push方法(LocalStack中找push方法)
				-2.2.3 push方法源码:
				    def push(self, obj):
						#通过反射找self._local,在init实例化的时候生成的:self._local = Local()
						#Local(),flask封装的支持线程和协程的local对象
						# 一开始取不到stack,返回None
						rv = getattr(self._local, "stack", None)
						if rv is None:
							#走到这,self._local.stack=[],rv=self._local.stack
							self._local.stack = rv = []
						# 把ctx放到了列表中
						#self._local={'线程id1':{'stack':[ctx,]},'线程id2':{'stack':[ctx,]},'线程id3':{'stack':[ctx,]}}
						rv.append(obj)
						return rv
		-3 如果在视图函数中使用request对象,比如:print(request)
			-3.1 会调用request对象的__str__方法,request类是:LocalProxy
			-3.2 LocalProxy中的__str__方法:lambda x: str(x._get_current_object())
				-3.2.1 内部执行self._get_current_object()
				-3.2.2 _get_current_object()方法的源码如下:
				    def _get_current_object(self):
						if not hasattr(self.__local, "__release_local__"):
							#self.__local()  在init的时候,实例化的,在init中:object.__setattr__(self, "_LocalProxy__local", local)
							# 用了隐藏属性
							#self.__local 实例化该类的时候传入的local(偏函数的内存地址:partial(_lookup_req_object, "request"))
							#加括号返回,就会执行偏函数,也就是执行_lookup_req_object,不需要传参数了
							#这个地方的返回值就是request对象(当此请求的request,没有乱)
							return self.__local()
						try:
							return getattr(self.__local, self.__name__)
						except AttributeError:
							raise RuntimeError("no object bound to %s" % self.__name__)
				-3.2.3 _lookup_req_object函数源码如下:
					def _lookup_req_object(name):
						#name是'request'字符串
						#top方法是把第二步中放入的ctx取出来,因为都在一个线程内,当前取到的就是当次请求的ctx对象
						top = _request_ctx_stack.top
						if top is None:
							raise RuntimeError(_request_ctx_err_msg)
						#通过反射,去ctx中把request对象返回
						return getattr(top, name)
				-3.2.4 所以:print(request) 实质上是在打印当此请求的request对象的__str__
		-4 如果在视图函数中使用request对象,比如:print(request.method):实质上是取到当次请求的reuquest对象的method属性
		
		-5 最终,请求结束执行: ctx.auto_pop(error),把ctx移除掉
		
	其他的东西:
		-session:
			-请求来了opensession
				-ctx.push()---->也就是RequestContext类的push方法的最后的地方:
					if self.session is None:
						#self是ctx,ctx中有个app就是flask对象,   self.app.session_interface也就是它:SecureCookieSessionInterface()
						session_interface = self.app.session_interface
						self.session = session_interface.open_session(self.app, self.request)
						if self.session is None:
							#经过上面还是None的话,生成了个空session
							self.session = session_interface.make_null_session(self.app)
			-请求走了savesession
				-response = self.full_dispatch_request() 方法内部:执行了before_first_request,before_request,视图函数,after_request,savesession
				-self.full_dispatch_request()---->执行:self.finalize_request(rv)-----》self.process_response(response)----》最后:self.session_interface.save_session(self, ctx.session, response)
		-请求扩展相关
			before_first_request,before_request,after_request依次执行
		-flask有一个请求上下文,一个应用上下文
			-ctx:
				-是:RequestContext对象:封装了request和session
				-调用了:_request_ctx_stack.push(self)就是把:ctx放到了那个位置
			-app_ctx:
				-是:AppContext(self) 对象:封装了当前的app和g
				-调用 _app_ctx_stack.push(self) 就是把:app_ctx放到了那个位置
	-g是个什么鬼?
		专门用来存储用户信息的g对象,g的全称的为global 
		g对象在一次请求中的所有的代码的地方,都是可以使用的 
		
		
	-代理模式
		-request和session就是代理对象,用的就是代理模式

wtfroms

  • wtfroms用于前后端混合的项目,与django中的forms类似
    用于校验数据,渲染页面,显示提示信息

使用

创建一个py文件编写wtforms
myform.py

from flask import Flask, render_template, request
from wtforms.fields import simple
from wtforms import Form
from wtforms import validators
from wtforms import widgets

app = Flask(__name__)
app.debug = True


class Myvalidators(object):
    '''自定义验证规则'''

    # 在__init__中将提示信息放入message中
    def __init__(self, message):
        self.message = message

    # 编写一些基础判断意外的验证规则
    def __call__(self, form, field):
        if field.data == "bbc":
            return None
        raise validators.ValidationError(self.message)

# 通过继承Form来设计字段验证规则
class LoginForm(Form):
    '''Form'''
    name = simple.StringField(
        label="用户名",
        widget=widgets.TextInput(),
        validators=[
            Myvalidators(message="用户名错误"),  # 也可以自定义正则
            validators.DataRequired(message="用户名不能为空"),
            validators.Length(max=8, min=3, message="用户名长度必须大于%(max)d且小于%(min)d")
        ],
        render_kw={"class": "form-control"}  # 设置展示在前端时的属性
    )

    pwd = simple.PasswordField(
        label="密码",
        validators=[
            validators.DataRequired(message="密码不能为空"),
            validators.Length(max=8, min=3, message="密码长度必须大于%(max)d且小于%(min)d"),
            validators.Regexp(regex="d+", message="密码必须是数字"),
        ],
        widget=widgets.PasswordInput(),
        render_kw={"class": "form-control"}
    )


@app.route('/login', methods=["GET", "POST"])
def login():
    if request.method == "GET":
        form = LoginForm()
        return render_template("login.html", form=form)
    else:
        form = LoginForm(formdata=request.form)
        if form.validate():
            # print("用户提交的数据用过格式验证,值为:%s" % form.data)
            return "登录成功"
        else:
            # print(form.errors, "错误信息")
            pass
        return render_template("login.html", form=form)


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


login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
<form action="" method="post" novalidate>
    <p>{{ form.name.label }} {{ form.name }} {{ form.name.errors.0 }}</p>
    <p>{{ form.pwd.label }} {{ form.pwd }} {{ form.pwd.errors.0 }}</p>
    <input type="submit" value="提交">
</form>
</body>
</html>

img

标签:__,05,Flask,request,self,ctx,session,local
From: https://www.cnblogs.com/qiguanfusu/p/17294271.html

相关文章

  • flask-day4——pipreqs模块、函数和方法的区别、threading.local对象、偏函数、flask
    目录一、请求上下文分析(源码:request原理)1.1导出项目的依赖(pipreqs模块)1.2函数和方法1.3threading.local对象代码演示自定义封装local,实现兼容线程和协程1.4偏函数1.5flask整个生命执行流程(1.1.4版本为例)二、wtforms(了解)三、作业1、为什么有了gil锁还要互斥锁2、什么是进程,线......
  • flask-请求上下文分析
    1.请求上下文分析预备知识1.1导出项目依赖我们之前使用导出项目依赖的命令是:pipfreeze>requirements.txt#导出项目依赖pipinstall-rrequirements.txt#安装项目依赖这种方式更适合在虚拟环境的导出和导入,因为它会导出当前解释器所有的依赖。但是如果在本机的解......
  • 请求上下文分析、函数和方法、threading.local对象、偏函数、flask整个生命执行流程(1
    请求上下文分析(源码:request原理)导出项目的依赖#之前pipfreeze>requirments.txt把当前解释器环境下的所有第三方依赖都导出来#使用第三方模块,更精确的导出依赖pipreqs第一步:安装pip3installpipreqs第二步:使用命令,导出项目依赖pipreqs./w......
  • 【flask】flask请求上下文分析 threading.local对象 偏函数 flask1.1.4生命执行流程
    目录上节回顾今日内容1请求上下文分析(源码:request原理)1.1导出项目的依赖1.2函数和方法1.3threading.local对象1.4偏函数1.5flask整个生命执行流程(1.1.4版本为例)2wtforms(了解)补充上节回顾#1蓝图 -第一步:导入-第二步:实例化得到对象,可以指定static和templates......
  • flask之request源码和第三方模块wtforms
    目录请求上下文分析(源码:request原理)1.导出项目的依赖2.函数和方法3.threading下的local对象4.偏函数5.flask整个生命执行流程---flask1.1.41版本为例wtforms---了解请求上下文分析(源码:request原理)1.导出项目的依赖以前导出项目的依赖:pipfreeze>requirements.txt......
  • flask源码分析
    目录请求上下文分析(源码:request原理)导出项目的依赖函数和方法threading.local对象偏函数flask整个生命执行流程(1.1.4版本为例)wtforms请求上下文分析(源码:request原理)导出项目的依赖之前的pipfreeze>requeirments.txt会把当前解释器环境下的所有第三方依赖都导出来......
  • flask4
    今日内容1请求上下文分析(源码:request原理)1.1导出项目的依赖#之前pipfreeze>requirments.txt把当前解释器环境下的所有第三方依赖都导出来#使用第三方模块,更精确的导出依赖pipreqs 第一步:安装pip3installpipreqs第二步:使用命令,导出项目依赖pipreqs./......
  • flask:蓝图(blueprint)、g对象、数据库连接池
    目录一、蓝图(blueprint)1、蓝图介绍2、蓝图的使用3、使用蓝图,划分小型项目目录4、使用蓝图,划分大型项目目录5、其他知识点二、g对象三、数据库连接池一、蓝图(blueprint)1、蓝图介绍在Flask中,使用蓝图Blueprint来分模块组织管理。蓝图实际可以理解为是一个存储一组视图方法的容器......
  • flask生命周期相关
    导出项目依赖问题我们使用pipfreeze>requirments.txt会把当前环境下的所有依赖都导出到requirements.py里,这样有些不用的也会被导进去。使用模块导出只会导出当前使用到的依赖到requirements.py下载pipinstallpipreqs使用#Linuxpipreqs./#windowspipreqs......
  • dxSpreadSheet1学习(05)
    基本操作与  dxRichEditControl控件学习(02) 类似 多了一个公式栏dxSpreadSheetFormulaBar1设置dxSpreadSheetFormulaBar1的Align为alTopdxSpreadSheet1的Align为alClientTdxSpreadSheet基本上还原了EXCEL的基本功能,用户可以像EXCEL一样正常操作这个控件,比如控件下ct......