python flask的进出栈中有local本地变量,通过wsgi的端口监控,每一个前端url请求都经历进栈出栈操作,通过相关执行过程了解,里面涉及到了local对象,request虽然是全局对象但是每一个请求的值都只是自己线程取值。实在的差不多
{'线程1':{'request':{'path_info':'/',methods:['GET','POST'},'values':'100'}}}
{'线程2':{'request':{'path_info':'/info',methods:['GET','POST'},'values':'200'}}}
{'线程3':{'request':{'path_info':'/index',methods:['GET','POST'},'values':'300'}}}
{'线程4':{'request':{'path_info':'/crm/manager',methods:['GET','POST'},'values':'500'}}}
{'线程5':{'request':{'path_info':'/student/manager',methods:['GET','POST'},'values':'800'}}}
上面每一个线程的request对象都是独立,所以彼此之间不混淆
先采用global函数,global只能写在函数,引用函数外的数据
先写个python程序验证下
gl=100
def fun():
gl=200
def fun2():
global gl
print("g1的值是",gl)
return fun2
f1=fun()
f1()
运行结果
g1的值是 100
换个写法:
gl=100
def fun():
gl=200
def fun2():
print("g1的值是",gl)
return fun2
f1=fun()
f1()
g1的值是 200
上面结果可以看出来global的变量只能是函数外的值
采用global变量实现每一个线程独立的结果
import time
from threading import Thread
import threading
x=1
def fun(i):
global x
print('线程号:{},线程名字{}'.format(threading.get_ident(),threading.current_thread().name))
x=i
time.sleep(2)
print(x)
tsk=[]
for i in range(10):
t=Thread(target=fun,args=(i,))
t.start()
tsk.append(t)
for i in tsk:
i.join()
time.sleep(1)
print(threading.current_thread().name)
线程号:9840,线程名字Thread-1
线程号:4364,线程名字Thread-2
线程号:11684,线程名字Thread-3
线程号:5268,线程名字Thread-4
线程号:12540,线程名字Thread-5
线程号:13248,线程名字Thread-6
线程号:10300,线程名字Thread-7
线程号:11328,线程名字Thread-8
线程号:12872,线程名字Thread-9
线程号:10812,线程名字Thread-10
9
9
9
9
9
9
9
9
9
9
MainThread
可以看出来并没有得出想要结果,最后的结果都是9,这个明显不能满足我们要求(join起到一个堵塞的作用,不然主线程会提前结束)
下面采用local
import time
from threading import Thread
import threading
from threading import local
localval=local()
def fun2(arg):
global localval
localval.value=arg
print(f"当前的线程是:{threading.current_thread().name},当前线程id是:{threading.get_ident()}")
time.sleep(2)
print(f"{threading.current_thread().name}-{threading.get_ident()}线程的localval值是",localval.value)
tsk=[]
for i in range(10):
t=Thread(target=fun2,args=(i,))
t.start()
tsk.append(t)
for j in tsk:
j.join()
运行result:
当前的线程是:Thread-1,当前线程id是:12640
当前的线程是:Thread-2,当前线程id是:12324
当前的线程是:Thread-3,当前线程id是:1568
当前的线程是:Thread-4,当前线程id是:10360
当前的线程是:Thread-5,当前线程id是:7588
当前的线程是:Thread-6,当前线程id是:13112
当前的线程是:Thread-7,当前线程id是:13120
当前的线程是:Thread-8,当前线程id是:12044
当前的线程是:Thread-9,当前线程id是:10616
当前的线程是:Thread-10,当前线程id是:13148
Thread-9-10616线程的localval值是 8
Thread-10-13148线程的localval值是 9
Thread-7-13120线程的localval值是 6
Thread-6-13112线程的localval值是 5
Thread-5-7588线程的localval值是 4
Thread-3-1568线程的localval值是 2
Thread-2-12324线程的localval值是 1
Thread-1-12640线程的localval值是 0
Thread-8-12044线程的localval值是 7
Thread-4-10360线程的localval值是 3
满足了我们的需求
所以flask采用了local来满足每个线程都有独立数据和外界无关