Hello World

We’re going to begin with everybody’s favorite - a “hello world” application. This is the simplest possible Flask application you can create.

Create an Application

  1. Open VSCode.
  2. Click on the menu for File > Open folder…
  3. In your file chooser create a new folder/directory named “jumpstart-webdev”
  4. Create a new file. File > New File. Click on “Text Editor”
  5. Save the file as app.py. File > Save.
  6. Copy and paste the following code into your editor in app.py and save it.
# app.py

from flask import Flask, render_template, redirect, url_for, jsonify, request

app = Flask(__name__)

@app.route('/')
def hello():
    return "Hello world!"

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

Run the Application

Run your program at the terminal with: python app.py, or by clicking the green play button located at the top right of VSCode.

Open http://localhost:5000

You should see “Hello world!”

What’s Happening?

Now we’ll step through the code.

from flask import Flask, render_template, redirect, url_for, jsonify, request

You might recognize what we’re doing in this first line - we are importing Flask. But instead of importing the whole flask library, we’re just importing the parts that we’ll need for the workshop.

app = Flask(__name__)

This line instantiates a new instance of Flask, or in other words we’re saying we’d like to create a new Flask application, and storing it in the variable “app”. __name__ is a special variable in Python that tells Flask where the application is located so that Flask can do some setup using that information.

@app.route('/')
def hello():
    return "Hello world!"

These above lines are the main part of the application, and is what is returning the “Hello world!” text for display in the browser. We’ll talk about what routes are and how they work in a following section.

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

You’ll likely come across this if statement if you end up working with Python a lot. These two lines are boilerplate and are basically saying that if we run this script from the command line, run this Flask application. We’re running it in debug mode, which allows some niceties like live-reloading, and more descriptive error messages in the browser.

Make a Change

Now that we’ve covered what is going on, try changing your code to say hello to you or anyone else you’d like instead of the world.

Now reload the page http://localhost:5000