Skip to content

firstapp

pkirlin edited this page Oct 10, 2016 · 15 revisions

Our first Flask application

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

  • Make a new folder somewhere to hold all your Flask applications. Call it flask-apps.
  • In that folder, make a sub-folder called first.
  • Start up Spyder and create a new file called sample.py.
  • 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.

  • Open a command line (Terminal on Mac, Anaconda Prompt on Windows).

  • 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:

    • On Windows, type the following:
set FLASK_APP=sample.py
set FLASK_DEBUG=1
flask run
  • On Mac, type:
export FLASK_APP=sample.py
export FLASK_DEBUG=1
flask run
  • Your flask app starts running. To see what it does, open a web browser and navigate to http://localhost:5000. You should see your new application!

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.

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 your local computer and linking it to the Flask app specified. When you visit the localhost:5000 URL, your browser contacts the webserver running on your own computer (always known as localhost) 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 Spyder 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, visit http://localhost:5000/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_DEBUG) 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