python - 如何使用 Flask 返回相对 URI Location header ?

标签 python flask werkzeug

在构建我的 HTTP 响应时,Flask 替换了我的 Location header 的内容。 它将我的实际相对 URI Location header 更改为绝对 header 。

@app.route('/votes', methods=['POST'])
def votes():
    return jsonify(), 201, {'location': '/votes/1'}

我的测试:

def test_vote_creation(self):
    response = self.app.post('/votes',
                             data=json.dumps({
                                 'name': 'Test vote'
                             }), content_type='application/json')
    print(response.headers['location'])

返回 http://localhost/votes/1 而不是 /votes/1

如何使用 Flask jsonify 返回相对 URI Location header ?

编辑:根据当前版本的 HTTP/1.1 标准 RFC 2616,Location header 的值必须是 an absolute URI . 但是 RCF 也将更改为允许相对 URI。因此,我想更改我的 API 的默认行为,以在我的位置 header 中使用相对 URI 进行应答。

有关 this post 的更多详细信息

最佳答案

HTTP RFC指定 Location header 必须是绝对 URI:

14.30 Location

The Location response-header field is used to redirect the recipient to a location other than the Request-URI for completion of the request or identification of a new resource. For 201 (Created) responses, the Location is that of the new resource which was created by the request. For 3xx responses, the location SHOULD indicate the server's preferred URI for automatic redirection to the resource. The field value consists of a single absolute URI.

Location       = "Location" ":" absoluteURI

因此,Flask/Werkzeug 响应对象将任何相对 URL Location header 转换为绝对 URL。

可以覆盖此行为,但我不建议您这样做。要覆盖它,请设置 autocorrect_location_header attribute of a Response objectFalsejsonify() 返回一个响应对象,改变它:

@app.route('/votes', methods=['POST'])
def votes():
    response = jsonify()
    response.status_code = 201
    response.headers['location'] = '/votes/1'
    response.autocorrect_location_header = False
    return response

但请注意,即使 Flask 不这样做,您的 WSGI 服务器仍然可以强制执行绝对 URL。

关于python - 如何使用 Flask 返回相对 URI Location header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22669447/

相关文章:

python - 使用配对输入文件和多个输出文件编写 bash 或 python for 循环

python - 从 __future__ 导入注释

javascript + Flask - 通过 post 请求将 json 数组传递到服务器的正确方法?

python - 从 werkzeug 导入安全导入 werkzeug VS

python - 将右侧按钮与右侧表格连接

python - Cx_Freeze 找不到 pkg_resources/*.*'

python - 属性错误 : module 'flask' has no attribute 'Flask'

python - peewee DoubleField 的默认值不会反射(reflect)在 MySQL 数据库中

python - 导入错误 : No module named types