Skip to content

firstapp

Phil Kirlin edited this page Mar 24, 2024 · 15 revisions

Our first Flask application

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

from flask import Flask

### Make the flask app
app = Flask(__name__)

### Routes
@app.route("/")
def index():
  return "Hello, world!"  # Whatever is returned from the function is sent to the browser and displayed.

### Start flask
if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8080, debug=True)
  • 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. The purpose of a Flask route (and its decorator) is to associate a URL (in this case, the root of the website, /) with a Python function that will be run whenever that URL is accessed. Any Python function connected via a route must return a string with HTML code. In this case, the HTML code has no tags, so it's very simple.

Why is the name of the route function called index?

This is because in web design, the basic webpage that shows up when you first load a website (like www.google.com or www.rhodes.edu) is (for historical reasons) often named index.html because it once displayed an "index" of all the webpages on the server. Nowadays, however, a true index rarely shows up when you load a website. Because this route shows up when you first load our new website, we will also call it "index" (and give it the function name index()).

Running the Flask app

  • Whenever you press the green run button, Flask will run. The web server will stay active until you press "stop."
  • It will reload itself automatically when you change the Python code, though sometimes it will reload too soon (while you're still typing) and will crash because the Python syntax is incorrect. In that case, just click the green button again.

Stopping a Flask app

When you want to stop a Flask app, click the "Stop" button.

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 web server 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 click "Run", you are starting up a basic web server on a linux machine inside replit.com and linking it to the Flask app specified. When you visit the URL, your browser contacts the web server running on the linux machine. 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, add the following imports:
import random
from datetime import datetime
import pytz
  • In the "routes" section of your program, add the following:
@app.route("/time")
def time():
    now = datetime.now().astimezone(pytz.timezone("US/Central"))
    timestring = now.strftime("%Y-%m-%d %H:%M:%S")  # format the time as a easy-to-read string
    beginning = "<html><body><b>The current time is: "
    ending = "</b></body></html>"
    return beginning + timestring + ending
  • Re-run the flask app if it doesn't restart automatically or has crashed.
  • Back in the browser, change the URL from / to /time. That is, in the web browser section of replit where you see the "Hello world" webpage, there should be a URL (address) bar that begins with {...}.replit.dev and then a window that only has a / in it. Change the '/' to '/time' and reload the page. You should see the current time.
    • If you want, you can click the green {...} part to load the webpage in a separate tab outside of the replit window.
  • 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 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 in the console at the bottom.

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.

Hint: You must return a single string containing the numbers 1 through 10.

You may go on when you have three working routes: the "hello world" route, the time route, and the counting 1 to 10 route.

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

Clone this wiki locally