Flask + flask-restful出现奇怪错误

4 投票
2 回答
1860 浏览
提问于 2025-04-20 20:59

我在几个项目中用过Flask,但在创建RESTful 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
}

run.py

from my_project import app

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

my_project/_ init _.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/_ init _.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 2.7和flask-restful 0.2.12(在Ubuntu Precise上通过pip安装的)。

2 个回答

-1

我之前也遇到过类似的问题,主要是跟网址末尾的斜杠有关。比如,我定义了一个接口是 api.com/endpoint,但我却发送请求到 api.com/endpoint/,结果就出现了404错误。

解决这个问题的方法是配置Flask应用,让它对网址末尾的斜杠不那么严格。可以通过设置 app.url_map.strict_slashes = False 来实现。

2

这个方法对我有效:

在你的环境中添加 ERROR_404_HELP=False

app.config['ERROR_404_HELP'] = False

撰写回答