简体   繁体   中英

flask app gives 404 for non-root route

I want to give flask a try. Using flask 0.12, python 3.4
I've created the project tree similar like in: https://damyanon.net/post/flask-series-structure/

controllers.py code:

from flask import Blueprint
import functools, operator

main = Blueprint('main', __name__)

@main.route('/')
def index():
  return "Main world"

@main.route('/foo')
def foo():
  return "this is foo"

when I run the app, I got 404 for /foo route but '/' is OK

* Serving Flask app "run"
    * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
    127.0.0.1 - - [27/Dec/2017 15:19:21] "GET / HTTP/1.1" 200 -
    127.0.0.1 - - [27/Dec/2017 15:19:25] "GET /foo HTTP/1.1" 404 -

Any clue? Thanks.

edit: As requested, here how I register blueprint in
flask_app/localservice/ init .py. Not sure about application factory . I'm still new with this. I substitute bookshelf with localservice and not use admin

from flask import Flask
from localservice.main.controllers import main
app = Flask(__name__)
app.register_blueprint(main, url_prefix='/')

I was following the same tutorial and the same error occurred for me as well. After being stuck on this for quite a while I finally figured it out.

So looks like there's an error in the tutorial. You can't register using '/'. app.register_blueprint(main, url_prefix='/')

This is the actual github codebase where the tutorial guy wrote the code.

If you look at the code and commit history, he changed url_prefix from '/' to 'main'. Change your url_prefix and the code should work.

If you don't insist on following that tutorial, the code in the Flask Quickstart docs works perfectly fine

from flask import Flask


app = Flask(__name__)


@app.route('/')
def index():
    return "Main world"


@app.route('/foo')
def foo():
    return "this is foo"


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM