Flask:如何在响应中设置状态码?

3

一切运行良好,API(flask)很好地返回数据。然而,当我尝试自定义响应代码时,我无法做到。
以下是我尝试的两种方式:

from flask import make_response
dictionary = {1:'a', 2:'b'}
resp = make_response(dictionary,1001)
return resp

#In developer tools, I could see the data, but status-code is 200

.

from flask import Response
dictionary = {1:'a', 2:'b'}
resp = Response(dictionary, status = 1001)
return resp

#Here again, I see the data, but the status code is 200

我该如何将状态码设置为其他数值?


1
尝试: return Response("{1:'a', 2:'b'}", status=201, mimetype='application/json') 顺便说一下,1001不是有效的HTTP状态码。 - T.M Luan
这是一个关于HTTP状态码的参考链接:https://zh.wikipedia.org/wiki/HTTP%E7%8A%B6%E6%80%81%E7%A0%81列表。 - marxmacher
@T.MLuan 感谢您的回复,先生。如果我想设置自定义状态码,该怎么做呢?比如说,如果我想根据返回类型触发不同的操作。 - Mr.President
1个回答

6

我修改了答案,使其更准确。最初的答案提到了Flask API,这与您通常使用的Flask不同。如果有人需要,我在此留下Flask API链接:https://www.flaskapi.org/api-guide/status-codes/。 - marxmacher
您可以在答案中添加您所做的更改,无需进行评论 :) - sahasrara62
我已经做了,只是想确保没有人会感到困惑 :) - marxmacher
https://dev59.com/fmsz5IYBdhLWcg3wTl0T - marxmacher
简而言之,是的。他们只需要遵循相同的逻辑。 - marxmacher
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接