处理响应

需求

如何在不同的场景里返回不同的响应信息?

1 返回模板

使用render_template方法渲染模板并返回
例如,新建一个模板index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. 我的模板html内容
  9. <br/>{{ my_str }}
  10. <br/>{{ my_int }}
  11. </body>
  12. </html>

后端视图

  1. from flask import render_template
  2. @app.route('/')
  3. def index():
  4. mstr = 'Hello 黑马程序员'
  5. mint = 10
  6. return render_template('index.html', my_str=mstr, my_int=mint)

2 重定向

  1. from flask import redirect
  2. @app.route('/demo2')
  3. def demo2():
  4. return redirect('http://www.itheima.com')

3 返回JSON

  1. from flask import jsonify
  2. @app.route('/demo3')
  3. def demo3():
  4. json_dict = {
  5. "user_id": 10,
  6. "user_name": "laowang"
  7. }
  8. return jsonify(json_dict)

4 自定义状态码和响应头

1) 元祖方式

可以返回一个元组,这样的元组必须是 (response, status, headers) 的形式,且至少包含一个元素。 status 值会覆盖状态代码, headers 可以是一个列表或字典,作为额外的消息标头值。

  1. @app.route('/demo4')
  2. def demo4():
  3. # return '状态码为 666', 666
  4. # return '状态码为 666', 666, [('Itcast', 'Python')]
  5. return '状态码为 666', 666, {'Itcast': 'Python'}

2) make_response方式

  1. @app.route('/demo5')
  2. def demo5():
  3. resp = make_response('make response测试')
  4. resp.headers[“Itcast”] = Python
  5. resp.status = 404 not found
  6. return resp