视图函数的响应对象

视图函数return除了返回如‘hello,world!’内容,还会返回一些附加信息,如:

状态码 status code :200,404,301等

content-type:放置于http headers属性中,告诉接收方如浏览器如何解析返回的内容。默认值为content-type=text/html,即把返回的主体内容作为html解析。

视图函数中本质上永远返回的是一个Response对象。

可用make_response创建这个对象

from flask import Flask, make_response

app = Flask(__name__)


@app.route('/')
def hello_world():
    headers ={
        'content-type': 'text/plain'
    }
    response = make_response('<html>Hello World!</html>', 404)
    response.headers = headers
    return response
    # return '<html>Hello World!</html>'


if __name__ == '__main__':
    app.run()

content-type': 'text/plain,将内容作为普通字符串解析,则会显示<html>的标签

我们把状态码设置成了404,但浏览器中仍然显示我们的内容,说明状态码并不会对内容产生本质的影响,它只是一个标识。

另一种更方便的写法:

@app.route('/')
def hello_world():
    headers ={
        'content-type': 'text/plain'
    }
    # response = make_response('<html>Hello World!</html>', 404)
    # response.headers = headers
    return '<html>Hello World!</html>', 200, headers
    # return '<html>Hello World!</html>'

这里return的其实是一个元组,flask内部最后还是会把它变成response对象再返回

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值