Skip to content

firstapp

Phil Kirlin edited this page Oct 8, 2019 · 15 revisions

Our first Flask application

In this first application, we will make sure Flask is working correctly.

  • In the linux shell, make a new folder to hold our flask applications. Type these commands:

    cd (to return to your home directory)

    mkdir flask-apps (to make a new directory called flask-apps)

    cd flask-apps (to change into that directory)

  • Now we will make our first application! type:

    mkdir first (a directory to hold our first application)

    cd first (to change into that directory)

  • In the code editor, create a file sample.py. Save it inside of first inside of flask-apps.

  • Inside this file, put the following code:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
  return 'Hello, world!'
  • Let's go through this line by line.

    • We import the Flask object from the flask package.
    • We create a new instance of the Flask object. The constructor takes a string that represents the name of the application; in this case we use the special Python variable __name__ which always contains the filename that is running. We store the instance in the app variable.
    • We create a new route using the @app.route syntax. This special syntax is called a decorator in Python. This route decorator associates a URL (in this case, the root of the site, /) with a Python function that will be run whenever that URL is accessed. Any function connected via the route decorator must return a string with HTML code. In this case, the HTML code has no tags, so it's very simple.
  • Save the Python file to the first directory inside of flask-apps.

Running the application

  • Back in the linux shell, issue the fol
  • Navigate to the folder where our app lives, which is [something]/flask-apps/first. You will type something like cd Desktop/flask-apps/first.
  • Type flask. This runs the Flask program and will give you instructions on how to run the application. Type these commands
export FLASK_APP=sample.py
export FLASK_ENV=development
flask run
  • Your flask app starts running. To see what it does, find the Web Preview button in the upper-right corner: . Click it and choose Change Port. Enter the number 5000 for the port. Click "Change and Preview."

Stopping a Flask app

When you want to stop a Flask app, go back to the command line (where you started the application) and press Control-C.

To restart the application, type flask run again. You do not need to retype the export commands unless you close and reopen the command prompt.

Error about Address already in use

This error happens if you already have flask running and you try to run it again.

To fix this, type pkill -9 flask.

How does this all work?

  • A regular Python program is typically run from start to finish once. If you want to run it again, you must execute it a second time.
  • A flask application works differently, because it is designed to run a website, which doesn't really have a "start" or an "end," unless you count when you start the webserver and when you stop it. Instead, a Flask app is designed around a collection of routes. Each route is connected both to a website URL and a Python function. When you type flask run, you are starting up a basic webserver on the linux machinen and linking it to the Flask app specified. When you visit the web preview URL, your browser contacts the webserver running on the linux machine on port 5000 (normally web requests run on port 80, but for testing purposes, the default Flask uses is 5000). Websites always default to a URL of /, so that's the route that the Flask app looks for, and the associated Python function is run, and the string "Hello world!" comes back.
  • Websites are designed to be used by multiple people simultaneously. Every time someone requests one of your routes, it runs that Python function. The result of this is that there might be many of your Python functions all running simultaneously, or even multiple copies of the same function running simultaneously!

Adding a second route

  • Go back to the code editor and add a second route to your program:
  • At the top of your program import the time package by adding import time.
  • At the end of your program, add the following:
@app.route('/time')
def get_time():
  now = time.gmtime()
  timestring = time.strftime("%Y-%m-%d %H:%M:%S", now)
  beginning = "<html><body><h1>The time is: "
  ending = "</h1></body></html>"
  return beginning + timestring + ending
  • Save your file. Back in the command line, you should notice that Flask detected that the Python file changed, and so it reloaded it.
  • Back in the browser, change the URL to add /time after the appspot.com part (and get rid of the authuser=0 part) of the URL. So it will look like http://blahblahblah.appspot.com/time. You should see the current time.
  • The time is static in the browser, it doesn't change unless you reload the page. Remember, when you load the page, Flask runs the get_time() function to get the current time, and returns it.
  • This example illustrates how you can use HTML code as well in Flask.

Debugging

When you have a bug in your app, it doesn't crash the same way a regular Python program does, because Flask tries to keep the webserver running at all costs. If you have turned debugging on (with the FLASK_ENV) setting, then errors will appear in the web browser.

Try this:

  • Make an intentional syntax error in your code. For instance, in the time route, try removing a plus sign on the return line.
  • Save the Python file, then reload the time webpage. You should see the error at the top of the webpage.

Test yourself

Add a third route to your webpage that when loaded, will create a webpage with the numbers 1 through 10 using a for loop. Remember, you can't do this with print()! Furthermore, you can't call return more than once, so you'll need to use string concatenation.

Use the main wiki page to navigate, not the list of pages directly above, because those are out of order.

Clone this wiki locally