Flask 上下文管理

簡單闡述:session

一、'請求剛進來':
     將request,session封裝在RequestContext類中
     app,g封裝在AppContext類中
     並經過LocalStack將requestcontext和appcontext放入Local類中
二、'視圖函數中':
     經過localproxy--->偏函數--->localstack--->local取值
三、'請求響應時':
      先執行save.session()再各自執行pop(),將local中的數據清

偏函數:app

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函數使用ide

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)
相關文章
相關標籤/搜索