We’re going to begin with everybody’s favorite - a “hello world” application. This is the simplest possible Flask application you can create.
app.py
. File > Save.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 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)
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.
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
When you’ve successfully made this change, type into chat or unmute to tell us who or what your application said hello to.