flask响应

介绍

在flask中,响应的方式有很多种,可以是普通字符串、json数据、html文本、模板或者是重定向。视图函数的返回值会自动转换为一个响应对象

当响应对象是字符串时

  • 根据这个字符串和缺省参数自动生成一个用于返回的 响应对象

@app.route("/test")
def test():
    return "hello world test!!!!"
 
 

调用(从header中可以看出,响应的报文是文本内容)

图片

图片

当响应对象是字典时

  • 会自动调用 jsonify 创建一个响应对象

@app.route("/test2")
def test2():
    cc={"name":"zhangsan","age":11}
    return cc

调用

图片

图片

当响应对象是元组时

元组必需包含报文体,可以包含响应码和响应头,返回的元组如下

  • (response, status) 

  • (response, headers)  

  • (response, status, headers) 

响应码默认是200

@app.route("/test3")
def test3():
    # 设置响应体与状态码
    return {"name":"zhangsan","age":11},201

@app.route("/test4")
def test4():
    # 设置响应体与响应头
    return {"name":"zhangsan","age":11}, {"token":"dslfjlsf","phone":"133333333"}

@app.route("/test5")
def test5():
    # 设置响应体、状态码与响应头
    return {"name":"zhangsan","age":11}, 202,{"token":"dslfjlsf","phone":"133333333"}

调用1

图片

调用2

图片

图片

调用3

图片

图片

返回其它格式

  • 除了常用的Json和文本外,还有其它格式,如:html、xml等,这时我们可以用 render_template() 函数来进行处理。

  • 使用之前先导入

from flask import render_template
  • render_template(template_name_or_list,**context)  接收两个参数

    • template_name_or_list:一般传入模板的名称,模板必须放在脚本同级的 templates 目录下(手动建立此目录)

图片

  • context:上下文,一般模板里面有些需要替换的变量,可以通过这个参数传入,以键值对的形式

当响应对像是 html时

@app.route("/test6")
def test6():
    return render_template("demo.html",name="hello world!!!")

demo.html

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
    <h1>{
   
   { name }}</h1>
</body>
</html>

调用

图片

当响应对像是 xml时

@app.route("/test7")
def test7():
    # 返回的是xml数据,需要设置响应头的 content-type,否则会被当成html数据
    return render_template("demo.xml",name="hello xml!!!"),{"content-type":"application/xml"}

demo.xml

<a>
    <b>
        {
   
   { name }}
    </b>
    <c>
        我是xml
    </c>
</a>

调用

图片

图片

设置更多的响应数据——make_response()

  • 如果想设置更多的响应信息,如:cookie等,可以通过make_response()来获取一个响应对象,从而设置cookie和请求头

@app.route("/test8")
def test8():
    dict_data={"name": "zhangsan", "age": 11}
    resp=make_response(dict_data)

    resp.set_cookie("cookie1","aaaa")
    resp.headers["phone"]="133333333"

    return resp

图片

图片

结合render_template 使用

  • 定位到错误页面

@app.errorhandler(404)
def not_fund(error):
    resp=make_response(render_template("login_err.html"),404)
    resp.set_cookie("cookie1","aaaa")
    resp.headers["phone"]="133333333"
    return resp

login_err.html

图片

注:@app.errorhandler 修饰符,会将一个响应代码映射到一个视图函数上,这里是将404码,处理成一个个性的错误页面 

 程序猿与投资生活实录已改名为  程序猿知秋,WX 公众号同款,欢迎关注!​​​​​​​

猜你喜欢

转载自blog.csdn.net/qq_25702235/article/details/132062049