Lecture 25

Using Flask

MCS 275 Spring 2024
Emily Dumas

View as:   Presentation   ·   PDF-exportable  ·   Printable

Lecture 32: Using Flask

Reminders and announcements:

  • Remember Flask is installed with
    python3 -m pip install Flask
  • Project 4 will be posted today
  • Homework 11 available

Today's goals

Create the database

Write code to query the database and get a list of tasks

Make the task list HTML template

DB schema

Single table tasks with columns:

  • taskid - integer primary key
  • description - string
  • owner - string
  • status - integer: 0=waiting, 1=in progress, 2=complete
  • shared - integer: 0=not shared, 1=shared
  • created_ts - "created timestamp" as time.time()
  • updated_ts - "updated timestamp" as time.time()

Generating task list view

Route /tasks/ddumas/ results in:

  • SELECT query to get ddumas owned tasks
  • SELECT query to get shared tasks of other users
  • Rearrange/format query data for use in template
  • Render a page template to format the data as in mockup

Note part of the URL is an argument. The pattern is /tasks/<username>/

Actions

Buttons on the task list view need to perform actions.

We'll make them links to certain URLs.

Using Flask, we'll make it so requesting those URLs performs the intended action.

Query parameters

A URL can include key-value pairs called query parameters, e.g.


        https://example.com/find_section?course=MCS275&instructor=Dumas
    

Many ascii characters appear verbatim but others* become hexadecimal codes like %20 (for a space). So don't try typing a URL with parameters by hand.

Flask decodes the parameters and makes them available as flask.request.values.get(key).

* The precise encoding scheme is specified in RFC3986.

Action URLs

  • /task/3/update?status=1 - Change status
  • /task/3/update?shared=0 - Change privacy / sharing flag
  • /task/3/delete - Delete a task (add this later?)

Question: What should the response to one of these look like?

Redirects

Every HTTP request results in a numerical status.

So far, we've seen 404 (NOT FOUND) and 200 (OK, generated by Flask when we return HTML).

There are also codes that instruct the browser to load another resource, e.g. 302 (FOUND).

return flask.redirect("destination") will make this happen.

References

Revision history

  • 2023-04-07 Finalization of the 2023 lecture this was based on
  • 2024-03-29 Initial publication