Flask-上下文管理

 

 

 

1. flask

 

 

案例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)session

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()

py2app

from s11 import request
print(request)
print(request.x1)
print(request.x2)

執行py2 打印結果爲ide

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

 

 

 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 """
View Code
相關文章
相關標籤/搜索