3

我在几个项目中使用过 Flask,但在创建 restul API 时从未使用过 flask-restful 包——所以我想我应该试一试。

但是,我遇到了一个我无法理解的奇怪错误——并且 API 根本不起作用。错误消息说

{
    "message": "Not Found. You have requested this URI [/api/v1.0/items] but did you mean /api/v1.0/items ?", 
    "status": 404
}

运行.py

from my_project import app

if __name__ == '__main__':
    app.run(host=0.0.0.0, debug=app.config['DEBUG'])

我的项目/_初始化_.py

from flask import Flask

app = Flask(__name__)

from my_project.base import blueprint as BaseBluePrint
from my_project.api import blueprint as ApiBluePrint
app.register_blueprint(BaseBluePrint)
app.register_blueprint(ApiBluePrint, url_prefix='/api/v1.0')

my_project/api/_初始化_.py

from flask import Blueprint
from flask.ext import restful

blueprint = Blueprint('api', __name__)
api = restful.Api(blueprint)

class ItemList(restful.Resource):
    def get(self):
        return false


api.add_resource(ItemList, '/items', endpoint='items')

什么会导致这种情况?无论我做什么,错误仍然存​​在。从 Flask看url_map,我可以看到我的路线 - 看起来不错。当远离蓝图并将其全部保存在一个文件中时,它可以工作。Python v2.7 和 flask-restful v0.2.12(从 Ubuntu Precise 上的 pip 安装)。

4

2 回答 2

0

这对我有用:

在您的环境中添加ERROR_404_HELP=False :

app.config['ERROR_404_HELP'] = False
于 2021-09-22T07:34:31.253 回答
-1

我遇到了与斜杠相关的类似问题,例如我定义了 api.com/endpoint 并将请求发送到 api.com/endpoint/ 并且出现 404 错误。

解决方案是通过以下方式配置 Flask 应用程序,使其对斜杠不严格:app.url_map.strict_slashes = False

于 2019-01-25T11:20:49.580 回答