Flask蓝图404

4

我在尝试访问 Flask 蓝图中定义的路由时遇到了 404 错误,但我不知道原因。有人能看出我的问题在哪吗?(我对 Flask 和 Python 都很新,所以可能是一些基本问题)

我的蓝图 (test.py):

from flask import Blueprint, jsonify, request
from werkzeug.local import LocalProxy

test_blueprint = Blueprint(
    'test_blueprint', __name__, url_prefix='/test')


@test_blueprint.route('/test', methods=['GET'])
def get_all_tests():

    return jsonify([{
        "id": "1",
        "name": "Foo"
    }, {
        "id": "2",
        "name": "Bar"
    }, {
        "id": "3",
        "name": "Baz"
    }]), 200

My app.py:

from test import test_blueprint

from flask import abort, Flask
from os import environ


def create_app():

    app = Flask(__name__)

    app.config.from_object('config.settings')
    app.template_folder = app.config.get('TEMPLATE_FOLDER', 'templates')
    app.url_map.strict_slashes = False

    app.register_blueprint(test_blueprint)

    return app

点击 http://127.0.0.1:5000/test 的结果是:
(venv) mymachine:api myusername$ python run.py
 * Restarting with stat
Starting server at 127.0.0.1 listening on port 5000 in DEBUG mode
 * Debugger is active!
 * Debugger PIN: 123-456-789
127.0.0.1 - - [2018-06-03 17:02:56] "GET /test HTTP/1.1" 404 342 0.012197

app.pytest.py在同一个目录下,供您参考。


额外信息: 由于您可以看到上面我是以文件名run.py开始的,这里提供该文件作为完整性的补充:

from flask_failsafe import failsafe
from gevent import monkey
from gevent.pywsgi import WSGIServer
from werkzeug.debug import DebuggedApplication
from werkzeug.serving import run_with_reloader

@failsafe
def failsafe_app():
    from app import create_app
    return create_app()


app = failsafe_app()


@run_with_reloader
def run():

    app.debug = app.config['DEBUG']

    print('Starting server at %s listening on port %s %s' %
          (app.config['HOST'], app.config['PORT'], 'in DEBUG mode'
           if app.config['DEBUG'] else ''))

    if app.config['DEBUG']:
        http_server = WSGIServer((app.config['HOST'], app.config['PORT']),
                                 DebuggedApplication(app))
    else:
        if app.config['REQUEST_LOGGING']:
            http_server = WSGIServer((app.config['HOST'], app.config['PORT']),
                                     app)
        else:
            http_server = WSGIServer(
                (app.config['HOST'], app.config['PORT']), app, log=None)

    http_server.serve_forever()

2
你定义了一个 url_prefix='/test',所以 URL 应该是 http://127.0.0.1:5000/test/test - PRMoureu
真糟糕,我知道它会非常简单。谢谢。如果您回答这个问题,我可以接受您的修复。@PRMoureu - rg88
2个回答

8
当您使用url_prefix定义蓝图时,该蓝图的每个规则都会将此前缀与给定路由连接起来。
在您的示例中,访问视图get_all_tests的URL应为http://127.0.0.1:5000/test/test

-1

您的端口号在URL中的位置不正确。

应该是http://127.0.0.1:5000/test

如果按照您的方式,您将会使用标准端口80,并寻找URL /test:5000


1
啊...那只是我输入问题时的笔误,抱歉。我已经更正为我实际使用的内容了。 - rg88

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