日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Flask对请求的处理

發布時間:2023/12/31 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Flask对请求的处理 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

由http://www.cnblogs.com/steinliber/p/5133386.html 中可得服務器會把environ和start_response發送給Flask的實例app,返回的是app中的wsgi_app

def wsgi_app(self, environ, start_response):ctx = self.request_context(environ)ctx.push()error = Nonetry:try:response = self.full_dispatch_request()except Exception as e:error = eresponse = self.make_response(self.handle_exception(e))return response(environ, start_response)finally:if self.should_ignore_error(error):error = Nonectx.auto_pop(error)

在這個函數中,首先創建了請求的上下文并將請求推入請求棧,之后調用full_dispatch_request來得到響應,也就是url對應的視圖函數的返回值,full_dispatch_request的程序為

def full_dispatch_request(self):"""Dispatches the request and on top of that performs requestpre and postprocessing as well as HTTP exception catching anderror handling... versionadded:: 0.7"""self.try_trigger_before_first_request_functions()try:request_started.send(self)rv = self.preprocess_request()if rv is None:rv = self.dispatch_request()except Exception as e:rv = self.handle_user_exception(e)response = self.make_response(rv)response = self.process_response(response)request_finished.send(self, response=response)return response

try_trigger_before_request_function會觸發在app中注冊的在接受第一個請求前要調用的函數,request_started是信號機制通知請求開始處理,preprocess_request會調用app中注冊的請求前函數,若函數的返回值不是None,response的內容就設為該返回值。否則就調用dispatch_request來找到對應的視圖函數得到返回值

def dispatch_request(self):req = _request_ctx_stack.top.requestif 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 automaticallyif getattr(rule, 'provide_automatic_options', False) \and req.method == 'OPTIONS':return self.make_default_options_response()# otherwise dispatch to the handler for that endpointreturn self.view_functions[rule.endpoint](**req.view_args)

self.view_functions是通過路由模塊產生的endpoint與視圖函數相對應的字典。這個就能返回視圖函數要返回的值

得到要響應的內容后通過make_response來將其轉化為response的對象

def make_response(self, rv):"""Converts the return value from a view function to a realresponse object that is an instance of :attr:`response_class`.The following types are allowed for `rv`:.. tabularcolumns:: |p{3.5cm}|p{9.5cm}|======================= ===========================================:attr:`response_class` the object is returned unchanged:class:`str` a response object is created with thestring as body:class:`unicode` a response object is created with thestring encoded to utf-8 as bodya WSGI function the function is called as WSGI applicationand buffered as response object:class:`tuple` A tuple in the form ``(response, status,headers)`` or ``(response, headers)``where `response` is any of thetypes defined here, `status` is a stringor an integer and `headers` is a list ora dictionary with header values.======================= ===========================================:param rv: the return value from the view function.. versionchanged:: 0.9Previously a tuple was interpreted as the arguments for theresponse object."""status_or_headers = headers = Noneif isinstance(rv, tuple):rv, status_or_headers, headers = rv + (None,) * (3 - len(rv))if rv is None:raise ValueError('View function did not return a response')if isinstance(status_or_headers, (dict, list)):headers, status_or_headers = status_or_headers, Noneif not isinstance(rv, self.response_class):# When we create a response object directly, we let the constructor# set the headers and status. We do this because there can be# some extra logic involved when creating these objects with# specific values (like default content type selection).if isinstance(rv, (text_type, bytes, bytearray)):rv = self.response_class(rv, headers=headers,status=status_or_headers)headers = status_or_headers = Noneelse:rv = self.response_class.force_type(rv, request.environ)if status_or_headers is not None:if isinstance(status_or_headers, string_types):rv.status = status_or_headerselse:rv.status_code = status_or_headersif headers:rv.headers.extend(headers)return rv

make_response可以將字符串,函數,列表等轉換成包含狀態碼以及響應頭的response實例,得到response后會調用process_response,他會調用app中注冊的after_request_funcs對response進行處理,返回處理過的response,然后full_dispatch_request會發信號通知請求處理結束,返回response,wsgi_app得到response后就返回response(environ,start_response)

def __call__(self, environ, start_response):"""Process this response as WSGI application.:param environ: the WSGI environment.:param start_response: the response callable provided by the WSGIserver.:return: an application iterator"""app_iter, status, headers = self.get_wsgi_response(environ)start_response(status, headers)return app_iter

這是response調用時的結果,即返回了可迭代的內容,服務器經過處理將內容發到客戶端

?

轉載于:https://www.cnblogs.com/steinliber/p/5173334.html

總結

以上是生活随笔為你收集整理的Flask对请求的处理的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。