flask中local原始碼資料型別首先明確:
原始碼中要構造的資料型別數是這樣的:
__storage__ =}
其次原始碼用local類構造資料型別,然後又用localstack類,作用是操作local,讓我們使用起來更方便,
localstack類中封裝了push方法,用來給呼叫local新增資料,pop方法取資料,下面來看看具體**怎麼實現的
local類構造資料型別
#用執行緒或者協程的唯一標識為鍵,
try:
#協程唯一標識
from greenlet import
getcurrent as get_ident
except
:
#程序唯一標識
from threading import
get_ident
class
local(object):
#__slots__設定只允許呼叫的屬性
__slots__ = ('
__storage__
', '
__ident_func__')
def__init__
(self):
#__storage__ = }
object.__setattr__(self, '
__storage__
', {}) #
__storage__={}
object.__setattr__(self, '
__ident_func__
', get_ident) #
__ident_func__= get_ident
#取資料
def__getattr__
(self, name):
try:
return self.__storage__[self.__ident_func__
()][name]
except
keyerror:
raise
attributeerror(name)
#主要的資料構造過程
def__setattr__
(self, name, value):
#name=stack
#value=
#self物件呼叫屬性
ident = self.__ident_func__() #
get_ident()
storage = self.__storage__
#storage={}
try:
storage[ident][name] = value #
storage=}
except
keyerror:
storage[ident] =
#刪除資料
def__delattr__
(self, name):
try:
del self.__storage__[self.__ident_func__
()][name]
except
keyerror:
raise
attributeerror(name)
#呼叫測試
obj =local()
obj.stack ='胖虎
')'鹹魚
(obj.stack)
(obj.stack.pop())
(obj.stack)
"""資料構造結果:
__storage__ =
}"""
localstack類操作local
#localstack 操作local的類,讓我們用起來更方法
class
localstack(object):
def__init__
(self):
#以local物件作為屬性
self._local =local()
#向local放值
defpush(self,value):
#會先執行local類裡面的__setattr__(self, name, value)方法,儲存資料
rv = getattr(self._local, '
stack
', none) #
self._local.stack =>local.getattr
if rv is
none:
self._local.stack = rv = #
self._local.stack =>local.setattr
return
rv
#呼叫local取資料
defpop(self):
"""removes the topmost item from the stack, will return the
old value or `none` if the stack was already empty.
"""stack = getattr(self._local, '
stack
', none)
if stack is
none:
return
none
elif len(stack) == 1:
return stack[-1]
else
:
return
stack.pop()
#def
top(self):
try:
return self._local.stack[-1]
except
(attributeerror, indexerror):
return none
最終例項化localstack類為_request_ctx_stack通過_request_ctx_stack物件來操作local,然後把ctx.request / ctx.session放到local資料型別中
#例項化_request_ctx_stack =localstack()
_request_ctx_stack.push(requestcontext())
def_lookup_req_object(arg):
ctx =_request_ctx_stack.top()
return getattr(ctx,arg) #
ctx.request / ctx.session
#把request和session都封裝到了local中
request = functools.partial(_lookup_req_object,'
request')
session = functools.partial(_lookup_req_object,'
session
')
mapreduce job提交原始碼流程
waitforcompletion submit 1建立連線 connect 1 建立提交job的 newcluster getconfiguration 1 判斷是本地yarn還是遠端 initialize jobtrackaddr,conf 2 提交job submitter.submitjob...
lucene update流程原始碼分析
update操作buffer到documentswriterdeletequeue裡,flush時處理deletes.documentswriterdeletequeue使用global deleteslice和dwpt deleteslice儲存deletes。dwpt deleteslice 用...
Vue 原始碼流程講解
模組分析vue原始碼,原始碼版本2.6.9 場景1 初始化vue例項,渲染到頁面,點選handlechangeweight方法 watch computed methods 1,data初始化,weight設定為響應式時,有乙個dep儲存依賴,在其他變數獲取當前weigth時,收集其他變數的watc...