We’re going to begin with everybody’s favorite - a “hello world” application. This is the simplest possible Flask application you can create.
In VSCode, find the app.py file in the left hand menu, and double click it to open.
You’ll see a lot of code that is commented out, which we’ll work through uncommenting and building on as we go. The only code that is uncommented is below, and forms the basis for our hello world application.
# 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 your program at the terminal with: python app.py, or by clicking
the green play button located at the top right of VSCode.
You should see “Hello world!”
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, port=3000)
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. We’re also telling it to run on port 3000 (corresponding to the 3000 in http://localhost:3000 in the URL).
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. Make sure to save your application before your re-run it (CTRL-s/CMD-s or File>Save).
Now reload the page http://localhost:3000
Note how even though you made a change to your code you didn’t need to stop and restart your application to see the change you made. This is another of the advantages of using a framework like Flask which includes a web server that watches for changes to your application and does automatic code reloading.
When you’ve successfully made this change, type into chat or unmute to tell us who or what your application said hello to.