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 ...
随机推荐
- JavaEE Tutorials (14) - 用实体图创建获取计划
14.1实体图基础185 14.1.1默认实体图186 14.1.2在持久化操作中使用实体图18614.2使用命名实体图187 14.2.1对实体类应用命名实体图注解187 14.2.2从命名实体图获 ...
- BZOJ 1177 [Apio2009]Oil(递推)
[题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=1177 [题目大意] 给出一个矩阵,从中选出3个k*k且不相交的矩阵,使得其总和最大 [ ...
- linux下安装python3.3.4
下载安装包 # wget http://www.python.org/ftp/python/3.3.4/Python-3.3.4.tgz 解压 # tar -xzvf Python-3.3.4.tgz ...
- poj 3259Wormholes (spfa最短路径)
#include<stdio.h> #include<string.h> #include<limits.h> #include<queue> usin ...
- jbpmAPI-4
Chapter 4. Examples 4.1.介绍基于web的工作台在默认情况下将安装两个样本库,包含各种示例项目,帮助你开始.本节显示了不同的例子可以发现在jbpm-playground库(也可用 ...
- java 简单的词法分析
package com.seakt.example; import java.io.*; import java.lang.String; public class J_Scanner { publi ...
- 0610 python 基础03
复习: 条件判断 if..else >>> age=28 >>> if age<18: ... print "你还没有成年吧" ... ...
- 两台linux机器文件传输之scp
0.写在前面:一定要注意我们是否有源文件的读权限,是否有目标文件夹的写权限!没有的话要先把权限设置好! *.设置权限的方法:切换到有权限操作文件或文件夹的用户,利用chmod命令修改权限 1.安装: ...
- (Problem 49)Prime permutations
The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual ...
- linux下挂载第二块硬盘
1.第一步:添加硬盘/新建分区(fdisk) a.查看当前系统所有硬盘及分区情况:fdisk -lb.在指定的硬盘(例:/dev/sda)上创建分区:fdisk /dev/sda , 根据提示进行下一 ...