1、首先根据WSGI发送的environ变量获取请求上下文,主要是根据函数ctx = self.request_context(environ),然后将该请求上下文推入全局变量_request_ctx_stack中(ctx.push()).
1 2 |
def request_context(self, environ): return RequestContext(self, environ) |
2、得到请求后,要触发第一次请求函数,如果是该应用是第一次实例化,并存在第一次请求之前函数(存在before_first_req_func字典中中),会调用存在该字典中的函数。当然一个实例也只执行一次,即在初始化的时候执行。
3、会发送请求开始信号,request_started,告知subscriber请求开始了。
4、如果存在before_request装饰的函数(函数位置在before_request_func字典中),那么在调用正常请求前会调用该函数。
1 2 3 4 5 6 7 8 9 10 |
@setupmethod def before_request(self, f): """Registers a function to run before each request. The function will be called without any arguments. If the function returns a non-None value, it's handled as if it was the return value from the view and further request handling is stopped. """ self.before_request_funcs.setdefault(None, []).append(f) return f |
从函数可以看到,这是一个装饰器,被该装饰器修饰的函数会添加到字典中。
5、调用正常的请求,返回一个该请求函数的值。 调用请求的源代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
def dispatch_request(self): """Does the request dispatching. Matches the URL and returns the return value of the view or error handler. This does not have to be a response object. In order to convert the return value to a proper response object, call :func:make_response. req = _request_ctx_stack.top.request if req.routing_exception is not None: self.raise_routing_exception(req) rule = req.url_rule # if we provide automatic options for this URL and the # request came with the OPTIONS method, reply automatically if getattr(rule, 'provide_automatic_options', False) and req.method == 'OPTIONS': return self.make_default_options_response() # otherwise dispatch to the handler for that endpoint return self.view_functions[rule.endpoint](**req.view_args) |
6、将请求函数返回值构造成响应类。
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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
def make_response(self, rv): """Converts the return value from a view function to a real response object that is an instance of :attr:response_class. The following types are allowed for `rv`: ======================= =========================================== :attr:`response_class` the object is returned unchanged :class:`str` a response object is created with the string as body :class:`unicode` a response object is created with the quest_ctx_stack中(ctx.push()).
2、得到请求后,要触发第一次请求函数,如果是该应用是第一次实例化,并存在第一次请求之前函数(存在before_first_req_func字典中中),会调用存在该字典中的函数。当然一个实例也只执行一次,即在初始化的时候执行。 3、会发送请求开始信号,request_started,告知subscriber请求开始了。 4、如果存在before_request装饰的函数(函数位置在before_request_func字典中),那么在调用正常请求前会调用该函数。
从函数可以看到,这是一个装饰器,被该装饰器修饰的函数会添加到字典中。 5、调用正常的请求,返回一个该请求函数的值。 调用请求的源代码:
6、将请求函数返回值构造成响应类。
|