Flask

Today, we'll work with our first major middleware, namely Flask.

Goal

By the end of today, you will be able to use the Flask module to do development of web applications in your Tempest account.

Plan

  1. Admin
  2. Python Catchup:
  3. Flask
  4. Routing
  5. Ports and Flask on Tempest
  6. Your Questions
  7. Examples
  8. Flask and PyMySQL (next time)

Python Scripts

We'll conclude the work we did last time, scripts that modify the database.

Flask

In development mode, Flask creates a long-running process that accepts web requests (on a configurable port), figures out which function to call based on the incoming URL, and prints the return value of that function as the response.

In short, it's a web server, except that:

Ports and Flask on Tempest

If we are all running our Flask apps on Tempest, we can't all use port 5000 or 8080 or whatever. Each of you needs a different port. So, to do this, I suggest using your UID. To determine your UID, use the id command:

New CentOS 7 [cs304guest@tempest testg]$ id
uid=8299(cs304guest) gid=8300(cs304guest) groups=8300(cs304guest) ...

Thus, we'll change the active part of your app from this (seen in thousands of online tutorials and such):

if __name__ == '__main__':
    app.debug = True
    app.run()

to this:

if __name__ == '__main__':
    import os
    uid = os.getuid()
    app.debug = True
    app.run('0.0.0.0',uid)

The '0.0.0.0' means to have the app listen on the external interface of the machine (tempest). The default is to listen on the internal interface, which means only connections from within Tempest itself. An external interface accepts connections from other machines, including your browser.

Your questions

I'll address your quiz questions.

First Example

Here's the code for our first example, example1.py:

I'll demonstrate how to run it.

First Exercise

  1. copy the ~cs304/pub/downloads/flask1/ folder to your 304 folder.
  2. That will create a directory for today. It will be a sibling of the virtual env we created last time.
  3. activate your virtualenv
  4. use pip to install flask
  5. cd to your flask1 folder
  6. Run the first example:
    python example1.py
  7. Did that work?
  8. Go to your browser and go to http://cs.wellesley.edu:port/
  9. Try different URLs by typing in the location bar of the browser. Try them more than once!
  10. Look in the terminal window where the app is running. You'll see a log of the requests. Error messages might get printed there as well.

Automatic Reloading

A very cool feature of development mode is that the web app monitors the example1.py file and will reload itself if the file changes. Try it!

  1. Edit the file to change the program a little.
  2. Change the name in the file from my name to yours
  3. Save the result
  4. Check the terminal that is running the web app and notice the message about reloading.
  5. Refresh the browser window. (Get in the habit of using shift+reload.)

Errors

Try putting an error in the code, just to see what happens.

When I first did the example, I omitted the n= in the .format() method. Try that.

In development mode, run-time errors will get printed to the console. You can also put print statements in there.

Certain kinds of errors can be debugged in the browser window, using a security key.

Exiting

When you're done using your Flask application, just kill it:

  1. Go to the terminal window that it's running in
  2. type control c (C-c)
  3. refresh the browser window, and you'll see that it's gone.

Routing

Routing Example

Let's look at the second example, example2.py:

I'll demo in the guest account.

  1. Start it, as before
  2. What is the main URL?
  3. Go to a web browser and try the main URL.

Obviously, these functions can easy share code, as they do with the lucky() function.

Nevertheless, your main app file should focus on routing, not on supporting functionality. You can define modules and import them to do the heavy lifting. That keeps your controller file concise (and they tend to get long).

Variable Rules

Sometimes, our URLs can be patterns that can then be parsed and involved in the computation. Flask makes this easy.

Code from example3.py:

Try adding a few cities to the last example and test them in the browser.

Exercise

Copy the example3.py app to exercise.py and implement a route to compute the GCD of two integers given in the URL.

Python's math module has a GCD function.

For example, the GCD(15,20) is 5.

Killing Python Processes

Sometimes you forget to kill Flask before you logout or something. Later, you try to run Flask, and you can't open your port because your other process already has it open. How can you find that other process and kill it? You can find open network programs using the netstat command. You can then kill the process with the kill command.

Here's an example:

$ netstat -ntlp | grep 1942
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
tcp        0      0 0.0.0.0:1942            0.0.0.0:*               LISTEN      13173/python
$ kill 13173
$ netstat -ntlp | grep 1942
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)

Summary