Lecture 35

HTTP and Flask

MCS 275 Spring 2022
David Dumas

Lecture 35: HTTP and Flask

Course bulletins:

  • Please install Flask, e.g. with
    python3 -m pip install Flask
    in preparation for using it in upcoming assignments.
  • If you already saw Flask, HTTP, CSS in MCS 260: Great, but don't get complacent!

Mockups

First, let's check in on page mockups for the work order app.

Reminder: You can always get thest from the sample code repository.

CSS: What to know

  • Selectors
    • by tag name (e.g. div { ... })
    • by class (e.g. p.intro { ... })
  • Attributes
    • font-size
    • font-family
    • color
    • background

File protocol

So far, I've been opening files in the web browser, using URLs with the file protocol.

There's no network communication here. The browser just opens the file using the OS interface.

To make an actual web site or application, we need an HTTP server.

Python's built-in HTTP server

python3 -m http.server

Opens a web server that serves files in the current directory and its subdirectories.

Visit http://localhost:8000/ in a browser (or substitute other port number shown in startup message) to see index.html.

Firewall rules typically prevent incoming connections from the internet (and maybe the local network too). That's good! Or

python3 -m http.server --bind 127.0.0.1

will make sure it only listens for connections from the same machine.

index.html

Most HTTP servers that deliver resources from a filesystem will look for a file called index.html and send it in response to a request that ends in a /.

(i.e. if no filename is given, index.html is used.)

Flask

Flask is a Python web framework. It makes it easy to write Python programs that respond to HTTP requests (e.g. web applications, APIs).

Competitors include:

  • Bottle — minimalist like Flask
  • Django — huge and full-featured

Minimal flask


        from flask import Flask

        app = Flask(__name__)

        @app.route("/positivity/")  # URL (public name for this action)
        def message():              # Logical name for this action
            return """<!doctype html>
            <html>
                <body>
                    You can do it!
                </body>
            </html>
            """

        app.run()
    

Static files

A flask app may not generate all the content it serves; some things (like CSS files or images) may be prepared in advance and used unchanged.

If you create a subdirectory static of the directory where your Flask application runs, you can put such "static" files there.

Refer to files there using URLs like static/image.png.

Templates

You can make an HTML file in which some parts are to be replaced by values of variables.

Surround the parts to be replaced by {{ and }}.

Put these in subdirectory templates and then call flask.render_template to generate the HTML as a return value.

Pass the variables to be given to the template as kwargs.

The full template language is very rich; we'll see more of it later.


        @app.route("/foo")
        def bar():
            # Find "templates/david.html"
            # In it, replace {{ x }} with 12 and {{ y }} with 15
            # then serve the result as the HTML for this route
            return render_template("david.html",x=12,y=15)
    

References

Revision history

  • 2022-04-07 Initial publication