Getting Started with Flask #
Install #
Probably best to set this up in a virtual environment.
Let’s assume we’re already there.
pip3 install flask
Test installation from Python. No error? All’s good.
import flask
Setup #
In a working project directory, start with a single file. Let’s call it initial.py
from flask import Flask # Flask class
app = Flask(__name__) # instantiates a Flask application at the app variable
# routes
# route decorator - handles backend complexity for routing
# "/" bit defines the route.
# Chunk beneath that represents what actually happens.
@app.route("/")
def hello():
return "Hello World!"
Routes are the things typed into browsers to navigate around.
Adding extra routes is as simple as adding:
@app.route("/about")
def about():
return "Ahoy!" # this woudl cause an about page to appear with the text "Ahoy!"
Running #
With environment variables #
tl;dr: Decorators add additional functionality to existing functions.
Prior to running (without the name/main chunk below), export variable while within working directory to point at main file:
export FLASK_APP=initial.py
To execute, run flask run
from the command line. This should bring up a simple Hello world!
page.
To show changes without having to reload application, run in debug mode.
export FLASK_DEBUG=1
Without environment variables #
Alternatively (my preferred way), add the following to the bottom of the script the enable the application to run with python initial.py
without having to set environment variables:
if __name__ == '__main__':
app.run(debug=True) # run the app in debug mode