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 = None
try:
try:
response = self.full_dispatch_request()
except Exception as e:
error = e
response = self.make_response(self.handle_exception(e))
return response(environ, start_response)
finally:
if self.should_ignore_error(error):
error = None
ctx.auto_pop(error)
在这个函数中,首先创建了请求的上下文并将请求推入请求栈,之后调用full_dispatch_request来得到响应,也就是url对应的视图函数的返回值,full_dispatch_request的程序为
def full_dispatch_request(self):
"""Dispatches the request and on top of that performs request
pre and postprocessing as well as HTTP exception catching and
error 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.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)
self.view_functions是通过路由模块产生的endpoint与视图函数相对应的字典。这个就能返回视图函数要返回的值
得到要响应的内容后通过make_response来将其转化为response的对象
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`: .. tabularcolumns:: |p{3.5cm}|p{9.5cm}| ======================= ===========================================
: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
string encoded to utf-8 as body
a WSGI function the function is called as WSGI application
and buffered as response object
:class:`tuple` A tuple in the form ``(response, status,
headers)`` or ``(response, headers)``
where `response` is any of the
types defined here, `status` is a string
or an integer and `headers` is a list or
a dictionary with header values.
======================= =========================================== :param rv: the return value from the view function .. versionchanged:: 0.9
Previously a tuple was interpreted as the arguments for the
response object.
"""
status_or_headers = headers = None
if 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, None if 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 = None
else:
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_headers
else:
rv.status_code = status_or_headers
if 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 WSGI
server.
:return: an application iterator
"""
app_iter, status, headers = self.get_wsgi_response(environ)
start_response(status, headers)
return app_iter
这是response调用时的结果,即返回了可迭代的内容,服务器经过处理将内容发到客户端
Flask对请求的处理的更多相关文章
- Flask关于请求表单的粗浅应用及理解+简单SQL语句温习
1.请求表单 请求表单的知识点是flask数据请求中很小的一部分,首先要了解一下GET和POST请求:http://www.w3school.com.cn/tags/html_ref_httpmeth ...
- python 全栈开发,Day139(websocket原理,flask之请求上下文)
昨日内容回顾 flask和django对比 flask和django本质是一样的,都是web框架. 但是django自带了一些组件,flask虽然自带的组件比较少,但是它有很多的第三方插件. 那么在什 ...
- Flask的请求与响应
Flask的请求与响应 1 请求相关信息 request.method # 请求方法 request.args # get 请求的参数 request.form # post请求的参数 request ...
- Flask 的 请求扩展 与 中间件
Flask 的 请求扩展 与 中间件 flask 可以通过 扩展(装饰器)来实现类似于django 中间件的功能 类似于django 的中间件, 在执行视图函数之前, 之后的执行某些功能 1 @app ...
- Flask框架 请求与响应 & 模板语法
目录 Flask框架 请求与响应 & 模板语法 简单了解Flask框架 Flask 框架 与 Django 框架对比 简单使用Flask提供服务 Flask 中的 Response(响应) F ...
- jmeter测试 flask 接口请求
jmeter测试 flask 接口请求 flask的代码如下: #!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Flas ...
- Flask之 请求,应用 上下文源码解析
什么是上下文? 每一段程序都有很多外部变量.只有像Add这种简单的函数才是没有外部变量的.一旦你的一段程序有了外部变量,这段程序就不完整,不能独立运行.你为了使他们运行,就要给所有的外部变量一个一个写 ...
- Flask的请求钩子与上下文简览
请求钩子(Hook) 在客户端和服务器交互的过程中,有些准备工作或扫尾工作需要处理,比如:在请求开始时,建立数据库连接:在请求结束时,指定数据的交互格式.为了让>每个视图函数避免编写重复功能的代 ...
- Flask 的请求与响应
flask的请求与响应 from flask import Flask,request,make_response,render_template,redirect app = Flask(__nam ...
- flask 之 请求钩子
请求钩子 什么是请求钩子? 在客户端和服务器交互的过程中,有些准备工作或扫尾工作需要统一处理,为了让每个视图函数避免编写重复功能的代码,flask提供了统一的接口可以添加这些处理函数,即请求钩子. f ...
随机推荐
- BZOJ 1196 [HNOI2006]公路修建问题(二分答案+并查集)
[题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=1196 [题目大意] 对于每条可能维修的公路可选择修一级公路或者二级公路,价值不同 要求 ...
- ZOJ Monthly, March 2013
A题 题目大意:给出一棵树,一开始节点值均为0,先要求完成在线操作:将某子树所有节点值取反,或者查询某子树总点权. 题解:很基础的线段树题,既然两个操作都是子树操作,那么就先树链剖分一下,将子树操作转 ...
- 10491 - Cows and Cars
描述:要么全选择牛,要么选择一辆车和p-1头牛,那么剩下n+m-p道门可以选择,求选择p道门以后要选择到车的概率 #include <cstdio> int main() { //freo ...
- pcre函数具体解释
PCRE是一个NFA正则引擎,不然不能提供全然与Perl一致的正则语法功能.但它同一时候也实现了DFA,仅仅是满足数学意义上的正则. PCRE提供了19个接口函数,为了简介,使用PCRE内带的測试程序 ...
- asp.net中实现MD5加密、解密的方法
这个MD5加密.解密的方法会使用即可. 使用时的代码备忘:Response.Write(FormsAuthentication.HashPasswordForStoringInConfigFile(& ...
- OC KVC总结
在iOS开发中,我们一般使用set方法或者点语法来修改对象的属性值,比如说 stu.age = 9 与 [stu setAge:9]. KVC(key value coding)键值编码,这是一种间接 ...
- Hibernate中,left join、inner join以及left join fetch区别(转)
标签: hibernate hql inner join left right 杂谈 分类: SQL 原文地址:http://m33707.iteye.com/blog/829725 Select F ...
- Map(关联式容器)
map是一类关联式容器,自动建立Key - Value的对应 , key 和 Value可以是任意你需要的类型.下面介绍 map 中一些常用的函数: 一.map 中的 begin 和 end 函数 m ...
- windows 下提取目录下所有文件的文件名
tree D:/dir /f >D:/filenames.txt 提取D盘dir目录下所有文件名,写入文件filenames.txt
- 射频识别技术漫谈(16)——Mifare UltraLight
Mifare UltraLight又称为MF0,从UltraLight(超轻的)这个名字就可以看出来,它是一个低成本.小容量的卡片.低成本,是指它是目前市场中价格最低的遵守ISO14443A协议的芯片 ...