Intro to Flask Part 1
Baby's First Flask App
Create app folder
mkdir hello-flask
Create a virtual environment
python -m venv venv
Activate the virtual environment
source venv/bin/activate
Install Flask
pip install flask
Create an app.py
file and add this:
from flask import Flask
app = Flask(__name__)
Start the server
flask run
This starts a server on port 5000 and… does nothing.
GET Routes
To respond to GET
requests from a client:
@app.route('/')
def index():
print('Index route / hit')
Web servers are long-running processes. If you make any changes to the code, you'll need to stop the server with Control-c
and then start it again with flask run
.
Once you're restarted the server, visit localhost:5000
in your web browser, you should see the text "Index route / hit" in your terminal but nothing in your web browser.
To send a response back to the browser, you can return something:
@app.route('/')
def index():
print('Index route / hit')
return 'Home Page'
Restart the server and reload localhost:5000. You should now see the text Home Page
in the web browser.
Automatically Restarting the Server
Restarting the server manually any time you want to test changes to the code is tedious. Using the --debug
flag, you can automate this process and streamline your workflow.
flask --debug run
Add Another Route
@app.route('/hello)
def hello():
return 'Hello World'
Visit localhost:5000/hello
in your web browser.
Last updated
Was this helpful?