Skip to content

Bluebrint causes 404 not found #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
tbensonwest opened this issue Jul 16, 2019 · 3 comments
Closed

Bluebrint causes 404 not found #2

tbensonwest opened this issue Jul 16, 2019 · 3 comments

Comments

@tbensonwest
Copy link

I ran the code from the command line in the final folder of ch06_routing using flask run but get 404 not found for both the homepage and the about page. This was the same when I followed along. The app worked fine before I added the blueprint.

I have a windows 10 machine with python 3.7.3 and I'm using a virtual environment.

@mikeckennedy
Copy link
Member

Hi. This often happens when running the app doesn't necessarily register the blue print. How are you running it? python app.py or flask run-style? Make sure that the register blueprint calls are actually being called. :)

@tbensonwest
Copy link
Author

Hey Mike

So I've kinda figured out the cause, but unsure of how to resolve entirely.

It seems that when calling flask run from the command line in a venv the executable skips over main entirely.

if __name__ == '__main__':
main()

__name__ == 'app' so main() is not called and therefore the blueprints aren't registered.

Here's the full app.py:

import sys
import flask

app = flask.Flask(__name__)

def main():
    register_blueprints()
    app.run(debug=True)

def register_blueprints():
    from views import home_views
    app.register_blueprint(home_views.blueprint)

if __name__ == '__main__':
    main()

If I remove the conditional and call main() the app works as expected but I get a warning:

c:\temp\work\pypi_org\app.py:9: Warning: Silently ignoring app.run() because the application is run from the flask command line executable. Consider putting app.run() behind an if name == "main" guard to silence this warning.
app.run(debug=True)

Do you know what may be the issue?

@mikeckennedy
Copy link
Member

mikeckennedy commented Jul 29, 2019

Hi. Yes, that's the problem. You're setting up the blueprints in main() but flask run doesn't execute main(). It just imports app, then calls app.run() itself (not a fan really). But if you want this to work both ways, change it to:

import sys
import flask

app = flask.Flask(__name__)

def main():
    app.run(debug=True)

def register_blueprints():
    from views import home_views
    app.register_blueprint(home_views.blueprint)

register_blueprints()
if __name__ == '__main__':
    main()

That'll do what you want and keep flask run working.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants