Home > Software design >  Hello World Flask Project in VS 2022 showing default Flask page only
Hello World Flask Project in VS 2022 showing default Flask page only

Time:07-20

I am trying to get Flask hello World code working using VS 2022. Code works, but landing page that opens up is Flask default page instead of printing hello world on screen.

This is my code:

from flask import Flask
app = Flask(__name__)


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

@app.route('/')
def hello():
    """Renders a sample page."""
    return "Hello World!"

Here is what comes up:

Default image that shows up

What I am expecting is hello World printed on browser tab.

This is the tutorial that I have followed for Setup- https://docs.microsoft.com/en-us/visualstudio/python/learn-flask-visual-studio-step-01-project-solution?view=vs-2022

This is what my solution explorer looks like:

Solution explorer

I initially had return in place of print. That did not work. Tried it again and I still get same result. Tried changing / to /home also. Still same result. If i leave just import statement, it still opens same page. It seems my app.run is not getting called at all.

Edit: another information- In Views.py, i get message that PovertyClass could not be resolved. that is the name of my project.

CodePudding user response:

move app.run() to the end of your script like this:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    """Renders a sample page."""
    return "Hello World!"

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

CodePudding user response:

2 Suggestions to solve your Problem:

  1. change the URL in your browser from localhost:57345 to localhost:57345/ (add /)

  2. add a new dummy route just for testing purposes (you should be able to copy the code i provided below)

@app.route('/home')
def show_home():
    # render home page
    return "This is my home page"

and then call this dummy page by the URL localhost:57345/home

Edit: like QwertYou stated -> change print to return

  • Related