Flask-上下文管理
1.
案例1
class Foo(object): def __str__(self): return "asdf" def __getattr__(self, item): return "99" def __getitem__(self, item): return "87" def __add__(self, other): return other +1
obj =Foo() print(obj) #asdf print(obj.x) # 99 print(obj.y) # 99 print(obj["x"]) #87 print(obj["y"]) #87 print(obj +8) #9
案例二
py1(s11)
DATA ={ "request":{ "x1":"xxx1", "x2":"xxx2" } } class LocalProxy(object): def get_dict(self): return DATA['request'] def __str__(self): return "asdf" def __getattr__(self, item): data_dict=self.get_dict() return data_dict[item] def __getitem__(self, item): data_dict =self.get_dict() return data_dict[item] def __add__(self, other): return other +1 request =LocalProxy() #实例化request对象
session =LocalProxy()
py2
from s11 import request print(request) print(request.x1) print(request.x2)
执行py2 打印结果为
asdf
xxx1
xxx2
案例三(案例二的改进版)
DATA ={ "request":{ "method":"GET", "form":{} }, "session":{ "user":"alex", "age":"19", } } class LocalProxy(object): def __init__(self,key): #此对象增加初始化方法,定义属性 ,将此属性传到实例化方法中. self.key =key def get_dict(self): return DATA[self.key] def __str__(self): return "asdf" def __getattr__(self, item): data_dict=self.get_dict() return data_dict[item] def __getitem__(self, item): data_dict =self.get_dict() return data_dict[item] def __add__(self, other): return other +1 request =LocalProxy("request") session =LocalProxy("session")
执行如下文件.
from s11 import request,session print(request.method) #GET print(request.form) #{} print(session.user) #alex print(session.age) #19
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 from flask import Flask,request,session 2 3 app = Flask(__name__) 4 5 6 @app.route('/index') 7 def index(): 8 # 1. request是LocalProxy对象 9 # 2. 对象中有method、执行__getattr__ 10 print(request.method) 11 # request['method'] 12 # request + 1 13 14 # 1. session是LocalProxy对象 15 # 2. LocalProxy对象的__setitem__ 16 session['x'] = 123 17 18 return "Index" 19 20 21 if __name__ == '__main__': 22 app.run() 23 # app.__call__ 24 # app.wsgi_app 25 26 """ 27 第一阶段:请求到来 28 将request和Session相关数据封装到ctx=RequestContext对象中。 29 再通过LocalStack将ctx添加到Local中。 30 __storage__ = { 31 1231:{'stack':[ctx(request,session)]} 32 } 33 第二阶段:视图函数中获取request或session 34 方式一:直接找LocalStack获取 35 from flask.globals import _request_ctx_stack 36 print(_request_ctx_stack.top.request.method) 37 38 方式二:通过代理LocalProxy(小东北)获取 39 from flask import Flask,request 40 print(request.method) 41 42 """