
After this lesson, you will be able to:
What do you think these websites have in common?
They’re each:
What else?
Some quick notes about Flask:
How?
We just make a normal Python app.
It looks like:
# Import Flask class from flask library. (Note the upper/lowercase convention.)
from flask import Flask
# Initialize an instance of the Flask class.
# This starts the website!
app = Flask(__name__)
# The default URL ends in / ("my-website.com/").
# Could be instead "my-website.com/about" or anything - more on this later.
@app.route('/')
# Function that returns the page: Display "Hello, World!"
def index():
return 'Hello, World!'
# Run the app when the program starts!
if __name__ == '__main__':
app.run(debug=True)We’ll run the Flask app like any other app.
pip install flaskCreate a file called my_website.py.
Start with:
Let’s add:
# Initialize an instance of the Flask class.
# This starts the website!
app = Flask(__name__)
# The default URL ends in / ("my-website.com/").
@app.route('/')
# Function that returns the page: Display "Hello, World!"
def index():
return 'Hello, World!'
# Run the app when the program starts!
if __name__ == '__main__':
app.run(debug=True)Run the app like normal:
python my_website.py
Go to:
http://localhost:5000/
You made a web app!
Let’s change the string:
It’s just Python — we can write any code.
return essentially just takes strings.Conversely:
app and index are just naming conventions.
def index(): could be def monkey():.app could be guitar.
But, naming variables sensibly is important!
from flask import Flask
guitar = Flask(__name__)
@guitar.route('/')
def monkey():
return 'Hello, World!'
if __name__ == '__main__':
guitar.run(debug=True)Let’s back up. Where did Flask come from?
Flask is built on two libraries:
Looks like this:
# Import Flask class from flask library.
from flask import Flask
# Initialize an instance of the Flask class.
app = Flask(__name__)
# The default URL ends in / ("my-website.com/").
@app.route('/')
# Function that returns the page: Display "Hello, World!"
def index():
return 'Hello, World!'
# Run the app when the program starts!
if __name__ == '__main__':
app.run(debug=True)