flask 里的response

常用响应逻辑

  • 响应对象
  • 返回JSON
  • 重定向
    • url_for
  • 自定义状态码

1. 响应对象

视图函数返回的 str / bytes 类型数据会被包装为 Response 响应对象, 也可以 创建响应对象来 自定义响应头等信息

@app.route('/')
def index():
    # 创建自定义响应对象    将想要在网页上显示的内容设置为参数即可
    response = make_response("hello flask")  # type: Response
    print(response.headers)  # 响应头信息
    print(response.content_type)  # 响应的content-type    默认为 text/html 返回网页
    return response  # 返回自定义的响应对象
    # return "hello flask"

2. 返回JSON

在使用 Flask 写一个接口时候需要给客户端返回 JSON 数据,在 Flask 中可以直接使用 jsonify 生成一个 JSON 的响应

# 返回JSON
@app.route('/demo4')
def demo4():
    json_dict = {
        "user_id": 10,
        "user_name": "laowang"
    }
    return jsonify(json_dict)

不推荐使用 json.dumps 转成 JSON 字符串直接返回,因为返回的数据要符合 HTTP 协议规范,如果是 JSON 需要指定 content-type:application/json

3. 重定向

  • 重定向到 百度
# 重定向
@app.route('/demo5')
def demo5():
    return redirect('http://www.baidu.com')
  • 重定向到自己写的视图函数
    • 可以直接填写自己 url 路径
    • 也可以使用 url_for 生成指定视图函数所对应的 url

@app.route('/demo1')
def demo1():
    return 'demo1'

# 重定向
@app.route('/demo5')
def demo5():
    return redirect(url_for('demo1'))
  • 重定向到带有参数的视图函数
    • 在 url_for 函数中传入参数
# 路由传递参数
@app.route('/user/<int:user_id>')
def user_info(user_id):
    return 'hello %d' % user_id

# 重定向
@app.route('/demo5')
def demo5():
    # 使用 url_for 生成指定视图函数所对应的 url
    return redirect(url_for('user_info', user_id=100))

4. 自定义状态码

  • 在 Flask 中,可以很方便的返回自定义状态码,以实现不符合 http 协议的状态码,例如:status code: 666
@app.route('/demo6')
def demo6():
    return '状态码为 666', 666
  • jsonify、redirect、自定义状态码的 本质仍是包装为Reponse对象

猜你喜欢

转载自blog.csdn.net/lczdada/article/details/82984195