目录
一、threading.local(和flask没有关系)
1.local为每个线程的数据开辟一个独立的空间,使得线程对自己空间中的数据进行操作(数据隔离)
import threading
from threading import local
import time
obj = local()
def task(i):
obj.xxx = i
time.sleep(1)
print(obj.xxx,i)
for i in range(10):
t = threading.Thread(target = task,args=(i,))
t.start()
2. 获取线程的唯一标记
import threading
import time
def task(i):
print(threading.get_ident(),i)
for i in range(10):
t = threading.Thread(target = task,args=(i,))
t.start()
3. 自定义类似local的函数—Local 为每个协程或者线程开辟独立空间
import threading
try:
import greenlet # 导入协程模块
get_ident = greenlet.getcurrent # 获得协程唯一标识函数
except:
get_ident = threading.get_ident # 获得线程唯一标识函数
class Local(object):
DIC = {}
def __getattr__(self,item):
ident = get_ident()
if ident in self.DIC:
return self.DIC[ident].get(item)
else:
return None
def __setattr__(self,key,balue):
ident = get_ident()
if ident in self.DIC:
self.DIC[ident][key] = value
else:
self.DIC[ident] = {key:value}
二、flask上下文管理
- 请求上下文管理
- 应用上下文管理
1. 简单总结
请求到来:
- 将请求和sessions封装到ctx = RequestContext()对象中
- 将app和g封装到app_ctx = AppContext()对象中
"""
- g是什么鬼?
答:在一次的请求周期中,可以在g中设置值,在本次周期都可以读取或者复制
- 相当于一次请求周期的全局变量。
"""
- 通过localstack对象 将ctx和app_ctx 封装到local对象中
问题:
1 local是什么?以及作用?
目的就是存储数据,维护成一个字典
作用:在flask中根据每一个协程开辟空间,让数据存储保证数据之间的隔离
存储格式:__storage__={协程唯一id:{stack:[ctx 栈]}}
2 localstack是什么?作用?
将__storage__维护成一个栈
方法:push()\pop()
3 localProxy作用:
在视图中通过localproxy去__storage__中获取数据,获取数据交给视图
4 before_request实现原理:
执行时机,是在local之前,视图之前 放到一个列表中, 循环列表函数,如果函数没有返回值执行视图函数
- 视图获取数据: 通过localPorxy+偏函数,内部调用localstack获取ctx和app_stack对象中封装的值
问题:
1 为什么把 ctx=request/session app_ctx=app/g
2 为什么把request/session放到ctx中,app和g放到app_ctx中?
答:因为离线脚本会用到app_ctx,而不需要使用ctx
- 请求结束:
调用localstack的pop方法,将ctx和app_ctx移除
-------------------------------------------------------------------------
- 什么时候使用app上下文管理
配置文件
current_app.Config # current_app就是当前app
2. 详细源码解析
进一步了解请转:五:flask:源码解析
三、偏函数
-
python中有一个小工具包functools,这个包中包含了几个在很有用的小功能,比如:
- wraps:在使用装饰器时,使用这个方法可以保护函数的元信息。
- reduce:一个合并序列项为一个单一值的小方法。
- partial:偏函数
- 等等…
-
一句话来总结partial的作用,固定函数中的一些参数,返回一个新的函数,方便调用
from functools import partial
class Foo(object):
def __init__(self):
self.request = "request"
self.session = "session"
foo = Foo()
def func(args):
return getattr(foo,args)
re_func = partial(func,'request')
se_func = partial(func,'session')
print(re_func())