在使用 Flask 写一个接口时候需要给客户端返回 JSON 数据,在 Flask 中可以直接使用 jsonify 生成一个 JSON 的响应
# 返回JSON @app.route(‘/demo4‘) def demo4(): json_dict = { "user_id": 10, "user_name": "laowang" } return jsonify(json_dict)
# return json_dict # 字典对象不可直接调用
不推荐使用 json.dumps 转成 JSON 字符串直接返回,因为返回的数据要符合 HTTP 协议规范,如果是 JSON 需要指定 content-type:application/json
# 重定向 @app.route(‘/demo5‘) def demo5(): return redirect(‘http://www.baidu.com‘)
@app.route(‘/demo1‘) def demo1(): return ‘demo1‘ # 重定向 @app.route(‘/demo5‘) def demo5():
# return redirect(url_for(‘demo1‘))
return redirect(‘/demo1‘)
# 路由传递参数 @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))
@app.route(‘/demo6‘) def demo6(): return ‘状态码为 666‘, 666
原文:https://www.cnblogs.com/zeug/p/11362888.html