baseresponse响应类_Flask响应

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_

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值