Flask响应
基本使用
看一个例子:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'hello world!', 200, {'Content-Type': 'application/json'}
if __name__ == '__main__':
app.run()
在 index 方法中,返回了了 http 状态、body 以及 header 等,该方法返回的其实是一个 tuple
思考:这里究竟发送了什么?才让一个 tuple 变为一个 Response
Response
开始源码分析吧,
简单而言,app.run () 会启动一个满足 WSGI 协议的 web 服务,它会监听指定的端口,将 HTTP 请求解析为 WSGI 格式的数据,然后将 environ, start_response 传递给 Flask () 实例对象。
类对象作为方法被调用,需要看到__call__()方法
class Flask(_PackageBoundObject):
...
def __call__(self, environ, start_response):
"""The WSGI server calls the Flask application object as theWSGI application. This calls :meth:`wsgi_app` which can bewrapped to applying middleware."""
return self.wsgi_app(environ, start_response)
def __repr__(self):
return "" % (self.__class__.__name__, self.name)
wsgi_app
看到这里是调用self.wsgi_app方法 开启WSGI服务
进行深入看看这个方法:
def wsgi_app(self, environ, start_response):
ctx = self.request_context(environ)
error = None
try:
try:
ctx.push()
response = self.full_dispatch_request()
except Exception as e:
error = e
response = self.handle_exception(e)
except: # noqa: B001
error = sys.exc_info()[1]
raise
return response(environ, start_response)
finally:
if self.should_ignore_error(error):
error = None
ctx.auto_pop(error)
该方法会找到当前请求路由对应的方法,调用该方法,获得返回 (即 response),如果请求路由不存在,则进行错误处理,返回 500 错误。
full_dispatch_request
这个重点看看full_dispatch_