Flask 上下文管理

简单阐述:

1、'请求刚进来':
     将request,session封装在RequestContext类中
     app,g封装在AppContext类中
     并通过LocalStack将requestcontext和appcontext放入Local类中
2、'视图函数中':
     通过localproxy--->偏函数--->localstack--->local取值
3、'请求响应时':
      先执行save.session()再各自执行pop(),将local中的数据清

偏函数:

from functools import partial,reduce

def fun(a,b):
    print(a)
    print(b)
    return a+b

new_fun=partial(fun,10)
ret=new_fun(20)   #将函数作为第一项作为参数
print(ret)

reduce函数使用

res=reduce(lambda a,b:a+b,[1,2,3,4,5,6,7,8])
print(res)
#所有数相加

函数基础

class MyClass(object):
    def __call__(self, *args, **kwargs):
        print(66666)

    def __setattr__(self, key, value):
        print(key,value)

    def __getattr__(self, item):
        print(item)

    def __setitem__(self, key, value):
        print(key,value,"item")

    def __getitem__(self, item):
        print(item,"item")

foo=MyClass()
foo()           #执行的是__call__方法
foo.name        #执行的是__getattr__
foo.name="小王"  #执行的是__setaattr__
foo["name"]      #执行的是__getitem__
foo["name"]="小王"   #执行的是__setitem__
#实例化类的时候先执行__new__方法没写默认执行object.__new__,在执行实例化对象的__init__实例化单例

自己写一个栈:

# LocalStack

from threading import get_ident   #一如获取线程id
import threading


class MyLocalStack(object):

    storage={}

    def push(self,item):
        try:
            self.storage[get_ident()].append(item)
        except:
            self.storage[get_ident()]=[item]

    def top(self):
        return self.storage[get_ident()].pop()


my_local_stack = MyLocalStack()

import time
def go(i):
    my_local_stack.push(i)
    # time.sleep(1)
    # my_local_stack.top()


for i in range(5):
    th = threading.Thread(target=go,args=(i,))
    th.start()


print(my_local_stack.storage)
posted @ 2019-02-28 17:12  admin9s  阅读(107)  评论(0编辑  收藏  举报