gpt4 book ai didi

python - 将 Flask-Restful API 调整为 JSON API 规范

转载 作者:太空宇宙 更新时间:2023-11-04 04:28:47 25 4
gpt4 key购买 nike

我只使用一种方法构建了一个小型 Flask-Restful API。我的 API 接收一个词和一个 URL 列表,并返回每个 URL 给定词的出现次数。

from flask import Flask, request, jsonify
from flask_restful import Resource, Api
import sys
sys.path.append("..")

from word_count import WordCount


app = Flask(__name__)
api = Api(app=app)

class WordApp(Resource):
def get(self):
word = request.args.get('word')
url = request.args.get('url').split(",")
return {'data': WordCount(url, word).count_words()}


api.add_resource(WordApp, '/')

if __name__ == '__main__':
app.run(debug=False)

如果请求的资源调用成功,返回的内容为

{"data": {"foo": {"http://www.foobar.com": 42}}}

尽管如此,如果请求调用不成功,返回的内容将不符合 JSON API,如 docs 中所述。 :

Including the ‘status’ key will set the Response’s status code. If not specified it will default to 500.

错误内容:

{"message": "Internal Server Error"}

当我搜索它时,我找到了 that可以定义一个包含每个错误的字典并将其传递给 Api 对象。

errors = {
'INVALID_FIELD': {
'message': "Missing or invalid field",
'status': 400
}
}

app = Flask(__name__)
api = flask_restful.Api(app, errors=errors)

但是,使用具有以下设置的 Postman 测试我的端点时,返回相同的 500 错误消息。我认为我在我的实现中遗漏了一些东西,以便返回我的自定义错误消息。

http://127.0.0.1:5000/?word=to

我想根据 JSON API 规范返回正确的自定义错误消息,如下所示:

{
"error": {
"message": "Missing or invalid field",
"code": 400
}
}

最佳答案

在有错误的字典中,您使用关键字 INVALID_FIELD。但是您不能自己选择此值。如果您查看 werkzeug 文档 https://werkzeug-docs-cn.readthedocs.io/zh_CN/latest/exceptions.html你会看到每个异常都是一个类。

因此,您应该使用 BadRequest,而不是 INVALID_FIELD,这是与错误代码 400 对应的类的名称。

关于python - 将 Flask-Restful API 调整为 JSON API 规范,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53045477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com