flask生命周期相关

发布时间 2023-04-06 15:24:52作者: 李阿鸡

导出项目依赖问题

我们使用

pip freeze >requirments.txt

会把当前环境下的所有依赖都导出到requirements.py里,这样有些不用的也会被导进去。

使用模块导出

只会导出当前使用到的依赖到 requirements.py

下载

pip install pipreqs

使用

# Linux  
pipreqs ./
# windows
pipreqs ./ --encoding=utf8

函数和方法

函数就是普通的函数,有几个参数就要传几个参数

方法:

1.绑定给对象的方法

2.绑定给类的方法 classmethod

绑定给谁的,就由谁来调用,会自动把自身传入

1.类的绑定方法,对象可以来调用,会自动把产生对象的类当做第一个参数的传入
2.对象的绑定方法,类可以调用.	
	但是它就变成了普通函数,有几个值,就要传几个值,没有自动传值了

补充知识

isinstance 判断是不是一个类的对象
isinstance(对象,类)  # 返回True或False
issubclass 判断一个类是不是另一个类的子类
issubclass(子类,父类)  # 返回True或False
MethodType    检查一个对象,是不是方法
FunctionType   检查一个对象,是不是函数

from types import MethodType, FunctionType

class Foo(object):
    def fetch(self):
        pass
    
    @classmethod
    def test(cls):
        pass

    @staticmethod
    def test1():
        pass

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对象 多线程并发操作时不需要加锁,不会出现数据错乱的问题。

其他语言也有 名字叫 ThreadLocal

原理:

​ 多个线程修改同一个数据,复制多份变量给每个线程用。

​ 为每个线程开辟一块空间进行数据存储每个线程操作自己的那部分数据

不使用loacl 并发编程

from threading import Thread, get_ident

import time
from threading import Lock
count = 0
L=Lock()

def task(arg):
    L.acquire()#加锁
    global count
    count = arg
    time.sleep(2)  # 我们本意是想每个线程打印自己入的传入的i,但是由于sleep了, 等cpu再调度该线程执行是,count被改成了 9 ,所有人打印出来都是9,数据错乱了,必须要加锁
    print('子线程id为:%s ====>' % get_ident(), count)
    L.release()#释放锁

for i in range(10):
    t = Thread(target=task, args=(i,))
    t.start()

使用local对象 并发编程

from threading import Thread, local,get_ident

l = local()  # 创建一个local对象,每个线程都有自己的一份,互不影响
def task(arg):
    l.arg = arg
    time.sleep(2)
    print('子线程id为:%s ====>' % get_ident(), l.arg)

for i in range(10):
    t = Thread(target=task, args=(i,))
    t.start()

自己封装一个local 了解其原理

# 自己封装local,实现兼容线程和协程

# 尝试导入greenlet试一下,如果导入不进来,说明根本没有用greenlet,因为前面使用了模块导出依赖,如果我们没有使用协程,就会报错,反之用了协程就不报错
try:
    from greenlet import getcurrent as get_ident
except Exception as e:
    from threading import get_ident

from threading import Thread
import time


class Local(object):
    def __init__(self):
        object.__setattr__(self, 'storage', {})  # 这个不会触发setattr
        # self.storage={}  # 它会触发 __setattr__,就会递归

    def __setattr__(self, k, v):
        ident = get_ident() #如果用协程,这就是协程号,如果是线程,这就是线程号
        if ident in self.storage:  #{'协程id号':{arg:1},'协程id号':{arg:2},'协程id号':{arg:3}}
            self.storage[ident][k] = v
        else:
            self.storage[ident] = {k: v}

    def __getattr__(self, k):
        ident = get_ident()
        return self.storage[ident][k]


lqz = Local()
def task(arg):
    lqz.arg = arg
    print(lqz.arg)


for i in range(10):
    t = Thread(target=task, args=(i,))
    t.start()

偏函数

一般我们有几个形参就要传几个参数,传少了会报错

目前手上只有一个参数,后面需要过一会才知道
可以使用偏移函数

from functools import partial
def add(a,b,c):
    return a+b+c

add= partial(add,2)  # 先把2传给他了
print(add(3,4))  # 里面已经有2了。

回顾知识点

# 进程
进程是资源分配的最小单位,一个应用程序运行,至少会开启一个进程

# 线程
cpu调度(执行)的最小单位,遇到io操作系统层面的切换。


# 协程
单线程下实现并发,程序层面遇到io自己切换

请求上下文分析

源码得知flask的生命周期执行流程

# 请求来了---》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就是代理对象,用的就是代理模式

wtforms(了解)

一个第三方模块来实现 django的forms组件生成前端模板,校验数据,渲染错误信息的功能。

下载

pip install wtforms

代码

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

app = Flask(__name__, template_folder='templates')

app.debug = True


class LoginForm(Form):
    # 字段(内部包含正则表达式)
    name = simple.StringField(
        label='用户名',
        validators=[
            validators.DataRequired(message='用户名不能为空.'),
            validators.Length(min=6, max=18, message='用户名长度必须大于%(min)d且小于%(max)d')
        ],
        widget=widgets.TextInput(), # 页面上显示的插件
        render_kw={'class': 'form-control'}

    )
    # 字段(内部包含正则表达式)
    pwd = simple.PasswordField(
        label='密码',
        validators=[
            validators.DataRequired(message='密码不能为空.'),
            validators.Length(min=8, message='用户名长度必须大于%(min)d'),
            validators.Regexp(regex="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}",
                              message='密码至少8个字符,至少1个大写字母,1个小写字母,1个数字和1个特殊字符')

        ],
        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('用户提交数据通过格式验证,提交的值为:', form.data)
        else:
            print(form.errors)
        return render_template('login.html', form=form)

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

# html代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>登录</h1>
<form 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>