Flask之上下文管理前戏

前戏

偏函数

from functools import partial

def add(a1, a2):
    return a1+a2


func = partial(add, 10)
ret = func(2)
print(ret)  # 12

执行父类的方法

class Base(object):

    def func(self):
        print('Base func')


class Foo(Base):

    def func(self):
        # 方式1:根据mro的顺序执行父类们的方法
        # super(Foo,self).func()

        # 方式2:调用Base类的func方法
        Base.func(self)
        print('Foo func')


obj = Foo()
obj.func()

特殊方法


class Foo(object):

    def __init__(self):
        # 先利用父类的__setattr__方法创建storage字典
        object.__setattr__(self,'storage',{})

    def __setattr__(self, key, value):
        print(key, value, self.storage)
        pass

obj = Foo()
obj.xx = 123

基于列表实现栈

class Stack():

    def __init__(self):
        self.data = []

    def push(self, i):
        self.data.append(i)

    def pop(self):
        return self.data.pop()

    def top(self):
        return self.data[-1]


stack = Stack()
stack.push('1')
stack.push('2')
stack.push('3')

print(stack.pop())
print(stack.pop())
print(stack.pop())

Local对象

作用是为每个线程开辟空间。
Flask中的Local源码:

from flask import globals


# globals.py
_app_ctx_stack = LocalStack()


# locals.py
class LocalStack(object):
    def __init__(self):
        self._local = Local()
        

class Local(object):
    # 限定访问的字段
    __slots__ = ('__storage__', '__ident_func__')

    def __init__(self):
        object.__setattr__(self, '__storage__', {})
        object.__setattr__(self, '__ident_func__', get_ident)

    def __release_local__(self):
        self.__storage__.pop(self.__ident_func__(), None)

    def __getattr__(self, name):
        try:
            return self.__storage__[self.__ident_func__()][name]
        except KeyError:
            raise AttributeError(name)

    def __setattr__(self, name, 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)

LocalStack对象

作用是将Local中的列表维护成栈。

源码:

class LocalStack(object):

    def __init__(self):
        self._local = Local()
        
        def push(self, obj):
            """Pushes a new item to the stack"""
            rv = getattr(self._local, 'stack', None)
            if rv is None:
                self._local.stack = rv = []
            rv.append(obj)
            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:
            release_local(self._local)
            return stack[-1]
        else:
            return stack.pop()

猜你喜欢

转载自www.cnblogs.com/fqh202/p/9585421.html