Reputation: 20977
I get a 404 when trying to access a route defined in a Flask Blueprint and I do not see why. Does anyone see what I am doing wrong (I'm new to Flask and Python in general so it could be something basic)?
My blueprint (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
The result of hitting http://127.0.0.1:5000/test
is:
(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.py
and test.py
are in the same directory, fyi.
Extra Info:
Since you can see above that I am starting this with a file named run.py
here is that file, for completeness:
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()
Upvotes: 4
Views: 7081
Reputation: 13317
When you define the blueprint with an url_prefix
, every rules of this blueprint will concatenate this prefix with the given routes
In your example, the url should be http://127.0.0.1:5000/test/test
to access the view get_all_tests
.
Upvotes: 8
Reputation: 33285
Your port number is in the wrong place in the url.
It should be http://127.0.0.1:5000/test
As you had it, you're hitting the standard port 80, looking for the url /test:5000
.
Upvotes: -1