Flask框架 之 上下文管理前戏

偏函数

自动传递参数

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维护一个列表,维护成一个栈,对列表中的数据进行添加或移除。通过栈对它进行操作。

全局变量只有在初次加载时执行。

  

posted @ 2018-06-26 15:14  高~雅  阅读(320)  评论(0编辑  收藏  举报