Flask框架 之 上下文管理前戲
阿新 • • 發佈:2018-06-26
light elf local fun img AI delattr none lookup
偏函數
自動傳遞參數
import functools def index(a1,a2): return a1 + a2 # 原來的調用方式 # ret = index(1,23) # print(ret) # 偏函數,幫助開發者自動傳遞參數 new_func = functools.partial(index,666) ret = new_func(1) print(ret)
super和執行類的區別?
python3裏所有的類默認繼承Object。
super:根據mro的順序執行方法
類.方法:主動執行類的方法
示例一:
class Base(object): def func(self): print(‘Base.func‘) class Foo(Base): def func(self): # 方式一:根據mro的順序執行方法 # super(Foo,self).func() # 方式二:主動執行Base類的方法 # Base.func(self) print(‘Foo.func‘) obj = Foo() obj.func()
實例二:
class Base(object): def func(self): super(Base, self).func() #Bar.func print(‘Base.func‘) class Bar(object): def func(self): print(‘Bar.func‘) class Foo(Base,Bar): 先繼承base,然後bar pass # 示例一 # obj = Foo() # obj.func() #先找Base,再找Bar # print(Foo.__mro__) # 示例二 # obj = Base() #找自己,沒有再找父類,object沒有func(),報錯 # obj.func()
面向對象中特殊方法 setattr/getattr註意事項:
class Foo(object): def __init__(self): # self.storage = {} #實例化對象就會執行__init__方法,self是對象,對象.storage={} ,執行setattr方法 object.__setattr__(self,‘storage‘,{}) #直接調用父類的setattr方法,防止還沒設置就調用報錯 def __setattr__(self, key, value): print(key,value,self.storage) obj = Foo() obj.xx = 123
基於列表實現棧
後進先出,相當於彈夾。
有兩個方法:push()和pop().
class Stack(object): def __init__(self): self.data = [] #可以使redis,可以使字典,也可以是其他 def push(self,val): #添加是傳一個參數 self.data.append(val) def pop(self): #刪除不要參數 return self.data.pop() def top(self): return self.data[-1] #每次取最後一次,只是讀,不刪 _stack = Stack() _stack.push(‘佳俊‘) _stack.push(‘鹹魚‘) print(_stack.pop()) print(_stack.pop())
slots
class Foo(object): __slots__ = (‘name‘,) #允許訪問的字段 (對象.字段) def __init__(self): self.name = ‘alex‘ # self.age = 18 obj = Foo() print(obj.name) # print(obj.age)
import functools try: from greenlet import getcurrent as get_ident except: from threading import get_ident class Local(object): __slots__ = (‘__storage__‘, ‘__ident_func__‘) def __init__(self): # __storage__ = {1231:{‘stack‘:[]}} object.__setattr__(self, ‘__storage__‘, {}) object.__setattr__(self, ‘__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=[] ident = self.__ident_func__() storage = self.__storage__ try: storage[ident][name] = value except KeyError: storage[ident] = {name: value} def __delattr__(self, name): try: del self.__storage__[self.__ident_func__()][name] except KeyError: raise AttributeError(name)源碼
以上知識綜合應用:
import functools try: from greenlet import getcurrent as get_ident except: from threading import get_ident class Local(object): __slots__ = (‘__storage__‘, ‘__ident_func__‘) def __init__(self): # __storage__ = {1231:{‘stack‘:[]}} object.__setattr__(self, ‘__storage__‘, {}) object.__setattr__(self, ‘__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=[] ident = self.__ident_func__() storage = self.__storage__ try: storage[ident][name] = value except KeyError: storage[ident] = {name: value} def __delattr__(self, name): try: del self.__storage__[self.__ident_func__()][name] except KeyError: raise AttributeError(name) """ __storage__ = { 12312: {stack:[ctx(session/request) ,]} } """ # obj = Local() # obj.stack = [] # obj.stack.append(‘佳俊‘) # obj.stack.append(‘鹹魚‘) # print(obj.stack) # print(obj.stack.pop()) # print(obj.stack) class LocalStack(object): def __init__(self): self._local = Local() def push(self,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 rv.append(value) # self._local.stack.append(666) return rv def pop(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 class RequestContext(object): def __init__(self): self.request = "xx" self.session = ‘oo‘ _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 = functools.partial(_lookup_req_object,‘request‘) session = functools.partial(_lookup_req_object,‘session‘) print(request()) print(session())
local:幫助我們為每個協程或線程開辟空間的,
localstark:幫助我們在local維護一個列表,維護成一個棧,對列表中的數據進行添加或移除。通過棧對它進行操作。
全局變量只有在初次加載時執行。
Flask框架 之 上下文管理前戲