Flask Quick Start (14) - 2 request context

[TOC]

Use request in view of the function, session request is how to achieve it?

from flask import Flask,request,session
app = Flask(__name__)

@app.route('/')
def index():
    print(request)  # <Request 'http://127.0.0.1:5000/' [GET]>
    print(type(request))  # <class 'werkzeug.local.LocalProxy'>
    print(session)  # <NullSession {}>
    print(type(session))  # <class 'werkzeug.local.LocalProxy'>
    return 'ok'

if __name__ == '__main__':
    app.run()

Printing can be seen with the session request it belongs to the same class, but the printed results are not the same. Then take a look at the internal implementation source code, for example request.args. request is a global variable, you can click on to see request = LocalProxy(partial(_lookup_req_object, "request"))the same token session is this class, took request for analysis:

request is an instance of an object LocalProxy the parameter is local=partial(_lookup_req_object, "request")a partial function. Call the _lookup_req_objectmethod, the request as the first argument. Take a look at this partial function

1. partial(_lookup_req_object, "request")

def _lookup_req_object(name):
    # 获取top.其实点进去发现_request_ctx_stack=LocalStack(),所以执行的是LocalStack.top()方法,top=ctx,name='request'
    top = _request_ctx_stack.top
    if top is None:
        raise RuntimeError(_request_ctx_err_msg)
    return getattr(top, name)

@property
def top(self):
    try:
        return self._local.stack[-1]  # 取出的是ctx
    except (AttributeError, IndexError):
        return None

Get "request" from the current request in ctx. Look at request.args actually get args from LocalProxy. Therefore, the implementation of __getattr__the method

2. LocalProxy.__getattr__

def __getattr__(self, name):
    # 在这里name就是args,所以从_get_current_object()去获取
    if name == "__members__":
        return dir(self._get_current_object())
    return getattr(self._get_current_object(), name)  # self._get_current_object()返回的是request,name是args。所以就是从request中去找args

def _get_current_object(self):
    if not hasattr(self.__local, "__release_local__"):
        return self.__local()
    try:
        return getattr(self.__local, self.__name__)  # self.__local里找。而这是实例化中的一个私有属性=传入的参数local=偏函数partial(_lookup_req_object, "request")的返回值=ctx中的request。
    except AttributeError:
        raise RuntimeError("no object bound to %s" % self.__name__))
        
# object.__setattr__(self, "_LocalProxy__local", local)

Guess you like

Origin www.cnblogs.com/863652104kai/p/11705077.html