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
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 #
from flask import Flask # Flask class
app = Flask(__name__) # instantiates a Flask application at the app variable
@app.route("/")
def hello():
return "Hello World!"
Route decorator (@app
) - handles backend complexity for routing.
"/"
bit here defines the route.
Chunk beneath that represents what actually happens.
Adding extra routes is as simple as adding:
@app.route("/about")
def about():
return "Ahoy!" # this would cause an about page to appear with the text "Ahoy!"
Multiple routes can invoke the same function, just stack the routes.
All URL paths must start with a /
.
Dynamic #
Routes can be specified with variables:
@app.route('/orders/<user_id>/<int:order_id>')
def orders(user_id, order_id):
return f'Order {order_id} for {user_id}.'
Content #
HTML can be embedded:
@app.route('/')
def home():
return '<h1>Hello, World!</h1>'
Note that the html is within the ticks.
This can also be mult-lined:
@app.route('/')
def home():
return '''
<h1>Hello, World!</h1>
'''
Running Locally #
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 to 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