flask<3>

1 Storage Management

Flask support Coroutines by dict and greenlet.getcurrent, it allocates space for each greenlet and store them in a dictionary

  1. create a dictionary called __storage__
  2. set, get from __storage__ using greenlet.getcurrent as key
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
try:
from greenlet import getcurrent as get_ident
except ImportError:
try:
from thread import get_ident
except ImportError:
from _thread import get_ident

class (object):
__slots__ = ('__storage__', '__ident_func__')

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

def __iter__(self):
return iter(self.__storage__.items())

def __call__(self, proxy):
"""Create a proxy for a name."""
return LocalProxy(self, proxy)

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)

2 Request Context

  • Request context includes request and session
  • Basically, each request comes
    1. Capsulate environ into a RequestContext object
    2. Add it into __storage__ dictionary
    3. Dispatch request to each view file and do operation
    4. Remove it from __storage__ dictionary

Picture for step 1, 2, 4

RequestContext

Picture for step 3 example

Request

partial(): it is quite funcional programming
object.__setattr__(self, '_LocalProxy__local', local): stuck here for quite a while.
python3 documentation

3 App Context

  • It is quite similar as Request Context
  • It includes current_app and g