One place for hosting & domains

      How To Use Many-to-Many Database Relationships with Flask and SQLite


      The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      Flask is a framework for building web applications using the Python language, and SQLite is a database engine that you can use with Python to store application data. In this tutorial, you’ll modify an application built using Flask and SQLite by adding a many-to-many relationship to it.

      Although you can follow this tutorial independently, it is also a continuation of the How To Modify Items in a One-to-Many Database Relationships with Flask and SQLite tutorial in which we managed a multi-table database with a one-to-many relationship using a to-do application example. The application allows users to add new to-do items, categorize items under different lists, and modify items.

      A many-to-many database relationship is a relationship between two tables where a record in each table can reference several records in the other table. For example, in a blog, a table for posts can have a many-to-many relationship with a table for storing authors. Each post can reference many authors, and each author can reference many posts. Each post can have many authors, and each author can write many posts. Therefore, there is a many-to-many relationship between posts and authors. For another example, in a social media application, each post may have many hashtags, and each hashtag may have many posts.

      By the end of the tutorial, your application will have a new feature for assigning to-do items to different users. We will refer to the users that get assigned to-dos with the word assignees. For example, you can have a household to-do item for Cleaning the kitchen, which you can assign to both Sammy and Jo—each to-do can have many assignees (that is, Sammy and Jo). Also each user can have many to-dos assigned to them (that is, Sammy can be assigned multiple to-do items), this is a many-to-many relationship between to-do items and assignees.

      At the end of this tutorial, the application will include an Assigned to tag with the names of the assignees listed.

      Todo Application

      Prerequisites

      Before you start following this guide, you will need:

      Step 1 — Setting Up the Web Application

      In this step, you will set up the to-do application ready for modification. You will also review the database schema to understand the structure of the database. If you followed the tutorial in the prerequisites section and still have the code and the virtual environment on your local machine, you can skip this step.

      To demonstrate adding a many-to-many relationship to a Flask web application, you will use the previous tutorial’s application code, which is a to-do management web application built using Flask, SQLite, and the Bootstrap framework. With this application users can create new to-dos, modify and delete existing to-dos, and mark to-dos as complete.

      Clone the repository and rename it from flask-todo-2 to flask_todo with the following command:

      • git clone https://github.com/do-community/flask-todo-2 flask_todo

      Navigate to flask_todo:

      Then create a new virtual environment:

      Activate the environment:

      Install Flask:

      Then, initialize the database using the init_db.py program:

      Next, set the following environment variables:

      • export FLASK_APP=app
      • export FLASK_ENV=development

      FLASK_APP indicates the application you are currently developing, which is app.py in this case. FLASK_ENV specifies the mode—set it to development for development mode; this will allow you to debug the application. (Remember not to use this mode in a production environment.)

      Then run the development server:

      If you go to your browser, you’ll have the application running at the following URL: http://127.0.0.1:5000/.

      To stop the development server, use CTRL + C.

      Next, you will go through the database schema to understand the current relationships between tables. If you are familiar with the contents of the schema.sql file, you can skip to the next step.

      Open the schema.sql file:

      The file contents are as follows:

      flask_todo/schema.sql

      DROP TABLE IF EXISTS lists;
      DROP TABLE IF EXISTS items;
      
      CREATE TABLE lists (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
          title TEXT NOT NULL
      );
      
      CREATE TABLE items (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          list_id INTEGER NOT NULL,
          created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
          content TEXT NOT NULL,
          done INTEGER NOT NULL DEFAULT 0,
          FOREIGN KEY (list_id) REFERENCES lists (id)
      );
      

      In the schema.sql file, you have two tables: lists for storing lists (such as Home or Study), and items for storing to-do items (such as Do the dishes or Learn Flask).

      The lists table has the following columns:

      • id: The ID of the list.
      • created: The list’s creation date.
      • title: The list’s title.

      The items table has the following columns:

      • id: The ID of the item.
      • list_id: The ID of the list the item belongs to.
      • created: The item’s creation date.
      • content: The item’s content.
      • done: The item’s state, the value 0 indicates the item has not been done yet, while 1 indicates item completion.

      In the items table you have a foreign key constraint, in which the list_id column references the id column of the lists parent table. This is a one-to-many relationship between items and lists, indicating that a list can have multiple items, and items belong to a single list:

      FOREIGN KEY (list_id) REFERENCES lists (id)
      

      In the next step, you will use a many-to-many relationship to create a link between two tables.

      Step 2 — Adding an Assignees Table

      In this step, you will review how to implement a many-to-many relationship and joins table. Then you’ll add a new table for storing assignees.

      A many-to-many relationship links two tables where each item in a table has many related items in the other table.

      Let’s say you have a simple table for to-do items as follows:

      Items
      +----+-------------------+
      | id | content           |
      +----+-------------------+
      | 1  | Buy eggs          |
      | 2  | Fix lighting      |
      | 3  | Paint the bedroom |
      +----+-------------------+
      

      And a table for assignees like so:

      assignees
      +----+------+
      | id | name |
      +----+------+
      | 1  | Sammy|
      | 2  | Jo   |
      +----+------+
      

      Let’s say you want to assign the to-do Fix lighting to both Sammy and Jo, you could do this by adding a new row in the items table like so:

      items
      +----+-------------------+-----------+
      | id | content           | assignees |
      +----+-------------------+-----------+
      | 1  | Buy eggs          |           |
      | 2  | Fix lighting      | 1, 2      |
      | 3  | Paint the bedroom |           |
      +----+-------------------+-----------+
      

      This is the wrong approach because each column should only have one value; if you have multiple values, basic operations such as adding and updating data become cumbersome and slow. Instead, there should be a third table that references primary keys of related tables—this table is often called a join table, and it stores IDs of each item from each table.

      Here is an example of a join table that links between items and assignees:

      item_assignees
      +----+---------+-------------+
      | id | item_id | assignee_id |
      +----+---------+-------------+
      | 1  | 2       | 1           |
      | 2  | 2       | 2           |
      +----+---------+-------------+
      

      In the first row, the item with the ID 2 (that is, Fix lighting) relates to the assignee with the ID 1 (Sammy). In the second row, the same item also relates to the assignee with the ID 2 (Jo). This means that the to-do item is assigned to both Sammy and Jo. Similarly, you can assign each assignee to multiple items.

      Now, you will modify the to-do application’s database to add a table for storing assignees.

      First, open schema.sql to add a new table named assignees:

      Add a line to delete the assignees table if it already exists. This is to avoid potential future issues when reinitiating the database, such as an already existing assignees table with different columns, which might break the code unexpectedly if it does not follow the same schema. You also add the SQL code for the table:

      flask_todo/schema.sql

      DROP TABLE IF EXISTS assignees;
      DROP TABLE IF EXISTS lists;
      DROP TABLE IF EXISTS items;
      
      CREATE TABLE lists (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
          title TEXT NOT NULL
      );
      
      CREATE TABLE items (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          list_id INTEGER NOT NULL,
          created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
          content TEXT NOT NULL,
          done INTEGER NOT NULL DEFAULT 0,
          FOREIGN KEY (list_id) REFERENCES lists (id)
      );
      
      CREATE TABLE assignees (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          name TEXT NOT NULL
      );
      

      Save and close the file.

      This new assignees table has the following columns:

      • id: The ID of the assignee.
      • name: The name of the assignee.

      Edit the init_db.py program to add a few assignees to the database. You use this program to initialize the database:

      Modify the file to look as follows:

      flask_todo/init_db.py

      import sqlite3
      
      connection = sqlite3.connect('database.db')
      
      with open('schema.sql') as f:
          connection.executescript(f.read())
      
      cur = connection.cursor()
      
      cur.execute("INSERT INTO lists (title) VALUES (?)", ('Work',))
      cur.execute("INSERT INTO lists (title) VALUES (?)", ('Home',))
      cur.execute("INSERT INTO lists (title) VALUES (?)", ('Study',))
      
      cur.execute("INSERT INTO items (list_id, content) VALUES (?, ?)",
                  (1, 'Morning meeting')
                  )
      
      cur.execute("INSERT INTO items (list_id, content) VALUES (?, ?)",
                  (2, 'Buy fruit')
                  )
      
      cur.execute("INSERT INTO items (list_id, content) VALUES (?, ?)",
                  (2, 'Cook dinner')
                  )
      
      cur.execute("INSERT INTO items (list_id, content) VALUES (?, ?)",
                  (3, 'Learn Flask')
                  )
      
      cur.execute("INSERT INTO items (list_id, content) VALUES (?, ?)",
                  (3, 'Learn SQLite')
                  )
      
      cur.execute("INSERT INTO assignees (name) VALUES (?)", ('Sammy',))
      cur.execute("INSERT INTO assignees (name) VALUES (?)", ('Jo',))
      cur.execute("INSERT INTO assignees (name) VALUES (?)", ('Charlie',))
      cur.execute("INSERT INTO assignees (name) VALUES (?)", ('Ashley',))
      
      connection.commit()
      connection.close()
      

      Save and close the file.

      In the highlighted lines, you use the cursor object to execute an INSERT SQL statement to insert four names into the assignees table. You use the ? placeholder in the execute() method and pass a tuple containing the name of the assignee to safely insert data into the database. Then you commit the transaction with connection.commit() and close the connection using connection.close().

      This will add four assignees to the database, with the names Sammy, Jo, Charlie, and Ashley.

      Run the init_db.py program to reinitialize the database:

      You now have a table for storing assignees in the database. Next you will add a join table to create a many-to-many relationship between items and assignees.

      Step 3 — Adding a Many-to-Many Join Table

      In this step, you will use a join table to link to-do items with assignees. First you’ll edit your database schema file to add the new join table, edit the database initialization program to add a few assignments, then use a demonstration program to display the assignees of each to-do.

      Open schema.sql to add a new table:

      Because the table joins items and assignees, you will call it item_assignees. Add a line to delete the table if it already exists, then add the SQL code for the table itself:

      flask_todo/schema.sql

      DROP TABLE IF EXISTS assignees;
      DROP TABLE IF EXISTS lists;
      DROP TABLE IF EXISTS items;
      DROP TABLE IF EXISTS item_assignees;
      
      
      CREATE TABLE lists (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
          title TEXT NOT NULL
      );
      
      CREATE TABLE items (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          list_id INTEGER NOT NULL,
          created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
          content TEXT NOT NULL,
          done INTEGER NOT NULL DEFAULT 0,
          FOREIGN KEY (list_id) REFERENCES lists (id)
      );
      
      CREATE TABLE assignees (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          name TEXT NOT NULL
      );
      
      CREATE TABLE item_assignees (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          item_id INTEGER,
          assignee_id INTEGER,
          FOREIGN KEY(item_id) REFERENCES items(id),
          FOREIGN KEY(assignee_id) REFERENCES assignees(id)
      );
      

      Save and close the file.

      This new item_assignees table has the following columns:

      • id: The ID of the entry that establishes a relationship between to-dos and assignees; each row represents a relationship.
      • item_id: The ID of the to-do item that will be assigned to the assignee with the corresponding assignee_id.
      • assignee_id: The ID of the assignee who will get assigned the item with the corresponding item_id.

      The item_assignees table also has two foreign key constraints: one that links the item_id column with the id column of the items table, and another one linking between the assignee_id column with the id column of the assignees table.

      Open init_db.py to add a few assignments:

      Modify the file to look as follows:

      flask_todo/init_db.py

      import sqlite3
      
      connection = sqlite3.connect('database.db')
      
      
      with open('schema.sql') as f:
          connection.executescript(f.read())
      
      cur = connection.cursor()
      
      cur.execute("INSERT INTO lists (title) VALUES (?)", ('Work',))
      cur.execute("INSERT INTO lists (title) VALUES (?)", ('Home',))
      cur.execute("INSERT INTO lists (title) VALUES (?)", ('Study',))
      
      cur.execute("INSERT INTO items (list_id, content) VALUES (?, ?)",
                  (1, 'Morning meeting')
                  )
      
      cur.execute("INSERT INTO items (list_id, content) VALUES (?, ?)",
                  (2, 'Buy fruit')
                  )
      
      cur.execute("INSERT INTO items (list_id, content) VALUES (?, ?)",
                  (2, 'Cook dinner')
                  )
      
      cur.execute("INSERT INTO items (list_id, content) VALUES (?, ?)",
                  (3, 'Learn Flask')
                  )
      
      cur.execute("INSERT INTO items (list_id, content) VALUES (?, ?)",
                  (3, 'Learn SQLite')
                  )
      
      cur.execute("INSERT INTO assignees (name) VALUES (?)", ('Sammy',))
      cur.execute("INSERT INTO assignees (name) VALUES (?)", ('Jo',))
      cur.execute("INSERT INTO assignees (name) VALUES (?)", ('Charlie',))
      cur.execute("INSERT INTO assignees (name) VALUES (?)", ('Ashley',))
      
      # Assign "Morning meeting" to "Sammy"
      cur.execute("INSERT INTO item_assignees (item_id, assignee_id) VALUES (?, ?)",
                  (1, 1))
      
      # Assign "Morning meeting" to "Jo"
      cur.execute("INSERT INTO item_assignees (item_id, assignee_id) VALUES (?, ?)",
                  (1, 2))
      
      # Assign "Morning meeting" to "Ashley"
      cur.execute("INSERT INTO item_assignees (item_id, assignee_id) VALUES (?, ?)",
                  (1, 4))
      
      # Assign "Buy fruit" to "Sammy"
      cur.execute("INSERT INTO item_assignees (item_id, assignee_id) VALUES (?, ?)",
                  (2, 1))
      
      connection.commit()
      connection.close()
      

      In the highlighted code, you assign to-do items to assignees by inserting into the item_assignees join table. You insert the item_id of the to-do item you want to assign to the assignee with the ID corresponding to the assignee_id value. In the first highlighted line, you assign the to-do item Morning meeting, which has an ID of 1, to the assignee Sammy, who has an ID of 1. The rest of the lines follow the same pattern. Once again, you use the ? placeholders to safely pass the values you want to insert in a tuple to the cur.execute() method.

      Save and close the file.

      Run the init_db.py program to reinitialize the database:

      Run the list_example.py program that displays the to-do items you have on the database:

      Here is the output:

      Output

      Home Buy fruit | id: 2 | done: 0 Cook dinner | id: 3 | done: 0 Study Learn Flask | id: 4 | done: 0 Learn SQLite | id: 5 | done: 0 Work Morning meeting | id: 1 | done: 0

      This displays the to-do items under the lists they belong to. You have each item’s content, its ID, and whether it’s completed or not (0 means the item is not completed yet, and 1 means it’s completed). You now need to display the assignees of each to-do.

      Open list_example.py to modify it to display item assignees:

      Modify the file to look as follows:

      flask_todo/list_example.py

      from itertools import groupby
      from app import get_db_connection
      
      conn = get_db_connection()
      todos = conn.execute('SELECT i.id, i.done, i.content, l.title 
                            FROM items i JOIN lists l 
                            ON i.list_id = l.id ORDER BY l.title;').fetchall()
      
      lists = {}
      
      for k, g in groupby(todos, key=lambda t: t['title']):
          # Create an empty list for items
          items = []
          # Go through each to-do item row in the groupby() grouper object
          for item in g:
              # Get the assignees of the current to-do item
              assignees = conn.execute('SELECT a.id, a.name FROM assignees a 
                                        JOIN item_assignees i_a 
                                        ON a.id = i_a.assignee_id 
                                        WHERE i_a.item_id = ?',
                                        (item['id'],)).fetchall()
              # Convert the item row into a dictionary to add assignees
              item = dict(item)
              item['assignees'] = assignees
      
              items.append(item)
      
          # Build the list of dictionaries
          # the list's name (ex: Home/Study/Work) as the key
      
          # and a list of dictionaries of to-do items
          # belonging to that list as the value
          lists[k] = list(items)
      
      
      for list_, items in lists.items():
          print(list_)
          for item in items:
              assignee_names=", ".join(a['name'] for a in item['assignees'])
      
              print('    ', item['content'], '| id:',
                    item['id'], '| done:', item['done'],
                    '| assignees:', assignee_names)
      
      

      Save and close the file.

      You use the groupby() function to group to-do items by the title of the list they belong to. (See Step 2 of How To Use One-to-Many Database Relationships with Flask and SQLite for more information.) While going through the grouping process, you create an empty list called items, which will hold all of the to-do item data, such as the item’s ID, content, and assignees. Next, in the for item in g loop, you go through each to-do item, get the assignees of the item, and save it in the assignees variable.

      The assignees variable holds the result of a SELECT SQL query. This query gets the assignee’s id (a.id) and the assignee’s name (a.name) from the assignees table (which is aliased to a to shorten the query). The query joings the id and name with the item_assignees join table (aliased to i_a) on the condition a.id = i_a.assignee_id where the i_a.item_id value equals that of the current item’s ID (item['id']). Then you use the fetchall() method to get the results as a list.

      With the line item = dict(item), you convert the item into a dictionary because a regular sqlite3.Row object does not support assignment, which you will need to add assignees to the item. Next, with the line item['assignees'] = assignees, you add a new key 'assignees' to the item dictionary to access the item’s assignees directly from the item’s dictionary. Then you append the modified item to the items list. You build the list of dictionaries that will hold all of the data; each dictionary key is the to-do list’s title, and its value is a list of all the items that belong to it.

      To print the results, you use the for list_, items in lists.items() loop to go through each to-do list title and the to-do items that belong to it, you print the list’s title (list_), then loop through the to-do items of the list. You added a variable named assignee_names, the value of which uses the join() method to join between the items of the generator expression a['name'] for a in item['assignees'], which extracts the assignee’s name (a['name']), from the data of each assignee in the item['assignees'] list. This joined list of assignee names, you then print with the rest of the to-do item’s data in the print() function.

      Run the list_example.py program:

      Here is the output (with assignees highlighted):

      Output

      Home Buy fruit | id: 2 | done: 0 | assignees: Sammy Cook dinner | id: 3 | done: 0 | assignees: Study Learn Flask | id: 4 | done: 0 | assignees: Learn SQLite | id: 5 | done: 0 | assignees: Work Morning meeting | id: 1 | done: 0 | assignees: Sammy, Jo, Ashley

      You can now display the assignees of each to-do item with the rest of the data.

      You have now displayed the assignee names of each to-do item. Next, you will use this to display the names below each to-do item in the web application’s index page.

      Step 4 — Displaying Assignees in the Index Page

      In this step, you’ll modify the index page of the to-do management application to show the assignees of each to-do item. You will first edit the app.py file, which contains the code for the Flask application, then edit the index.html template file to display the assignees below each to-do item on the index page.

      First, open app.py to edit the index() view function:

      Modify the function to look as follows:

      flask_todo/app.py

      @app.route('/')
      def index():
          conn = get_db_connection()
          todos = conn.execute('SELECT i.id, i.done, i.content, l.title 
                                FROM items i JOIN lists l 
                                ON i.list_id = l.id ORDER BY l.title;').fetchall()
      
          lists = {}
      
          for k, g in groupby(todos, key=lambda t: t['title']):
              # Create an empty list for items
              items = []
              # Go through each to-do item row in the groupby() grouper object
              for item in g:
                  # Get the assignees of the current to-do item
                  assignees = conn.execute('SELECT a.id, a.name FROM assignees a 
                                          JOIN item_assignees i_a 
                                          ON a.id = i_a.assignee_id 
                                          WHERE i_a.item_id = ?',
                                          (item['id'],)).fetchall()
                  # Convert the item row into a dictionary to add assignees
                  item = dict(item)
                  item['assignees'] = assignees
      
                  items.append(item)
      
              # Build the list of dictionaries
              # the list's name (ex: Home/Study/Work) as the key
      
              # and a list of dictionaries of to-do items
              # belonging to that list as the value
              lists[k] = list(items)
      
          conn.close()
          return render_template('index.html', lists=lists)
      

      Save and close the file.

      This is the same code you used in the list_example.py demonstration program in Step 3. With this, the lists variable will contain all the data you need, including assignee data, which you will use to access assignee names in the index.html template file.

      Open the index.html file to add assignee names following each item:

      • nano templates/index.html

      Modify the file to look as follows:

      flask_todo/templates/index.html

      {% extends 'base.html' %}
      
      {% block content %}
          <h1>{% block title %} Welcome to FlaskTodo {% endblock %}</h1>
          {% for list, items in lists.items() %}
              <div class="card" style="width: 18rem; margin-bottom: 50px;">
                  <div class="card-header">
                      <h3>{{ list }}</h3>
                  </div>
                  <ul class="list-group list-group-flush">
                      {% for item in items %}
                          <li class="list-group-item"
                          {% if item['done'] %}
                          style="text-decoration: line-through;"
                          {% endif %}
                          >{{ item['content'] }}
                          {% if not item ['done'] %}
                              {% set URL = 'do' %}
                              {% set BUTTON = 'Do' %}
                          {% else %}
                              {% set URL = 'undo' %}
                              {% set BUTTON = 'Undo' %}
                          {% endif %}
                          <div class="row">
                              <div class="col-12 col-md-3">
                                  <form action="{{ url_for(URL, id=item['id']) }}"
                                      method="POST">
                                      <input type="submit" value="{{ BUTTON }}"
                                          class="btn btn-success btn-sm">
                                  </form>
                              </div>
      
                              <div class="col-12 col-md-3">
                                  <a class="btn btn-warning btn-sm"
                                  href="https://www.digitalocean.com/community/tutorials/{{ url_for("edit', id=item['id']) }}">Edit</a>
                              </div>
      
                              <div class="col-12 col-md-3">
                                  <form action="https://www.digitalocean.com/community/tutorials/{{ url_for("delete', id=item['id']) }}"
                                      method="POST">
                                      <input type="submit" value="Delete"
                                          class="btn btn-danger btn-sm">
                                  </form>
                              </div>
                          </div>
      
                          <hr>
                          {% if item['assignees'] %}
                              <span style="color: #6a6a6a">Assigned to</span>
                              {% for assignee in item['assignees'] %}
                                  <span class="badge badge-primary">
                                      {{ assignee['name'] }}
                                  </span>
                              {% endfor %}
                          {% endif %}
      
                          </li>
                      {% endfor %}
                  </ul>
              </div>
          {% endfor %}
      {% endblock %}
      

      Save and close the file.

      With this modification, you added a line break below each item using the <hr> tag. If the item has any assignees (which you know via the statement if item['assignees']), you display a gray Assigned to text and loop through the item assignees (that is, the item['assignees'] list), and display the assignee name (assignee['name']) in a badge.

      Finally, run the development server:

      Then visit the index page: http://127.0.0.1:5000/.

      Each to-do item can now have many assignees, and you can assign each assignee multiple to-dos. The index page displays all of the items and the assignees of each item.

      Todo Application

      You can access the final code from this repository.

      Conclusion

      In this tutorial, you have learned what a many-to-many relationship is, how to use it in a Flask and SQLite web application, how to join between tables, and how to group relational data in Python.

      You now have a complete to-do application in which users can create new to-do items, mark an item as complete, edit or delete existing items, and create new lists. And each item can be assigned to different assignees.

      To learn more about web development with Python and Flask see these Flask tutorials.



      Source link

      How To Modify Items in a One-to-Many Database Relationships with Flask and SQLite


      The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      Flask is a framework for building web applications using the Python language, and SQLite is a database engine that can be used with Python to store application data. In this tutorial, you’ll modify items in an application built using Flask and SQLite with a One-to-Many relationship.

      This tutorial is a continuation of How To Use One-to-Many Database Relationships with Flask and SQLite. After having followed it, you’ve successfully created a Flask application to manage to-do items, organize items in lists, and add new items to the database. In this tutorial, you will add the functionality to mark to-do items as complete, to edit and delete items, and to add new lists to the database. By the end of the tutorial, your application will include edit and delete buttons and strikethroughs for completed to-dos.

      Todo Application

      Prerequisites

      Before you start following this guide, you will need:

      Step 1 — Setting Up the Web Application

      In this step, you will set up the to-do application to be ready for modification. If you followed the tutorial in the prerequisites section and still have the code and the virtual environment in your local machine, you can skip this step.

      First use Git to clone the repository of the previous tutorial’s code:

      • git clone https://github.com/do-community/flask-todo

      Navigate to flask-todo:

      Then create a new virtual environment:

      Activate the environment:

      Install Flask:

      Then, initialize the database using the init_db.py program:

      Next, set the following environment variables:

      • export FLASK_APP=app
      • export FLASK_ENV=development

      FLASK_APP indicates the application you are currently developing, which is app.py in this case. FLASK_ENV specifies the mode—set it to development for development mode, this will allow you to debug the application. (Remember not to use this mode in a production environment.)

      Then run the development server:

      If you go to your browser, you’ll have the application running on the following URL at http://127.0.0.1:5000/.

      To close the development server, use the CTRL + C key combination.

      Next, you will modify the application to add the ability to mark items as complete.

      Step 2 — Marking To-Do Items as Complete

      In this step, you’ll add a button to mark each to-do item as complete.

      To be able to mark items as complete, you’ll add a new column to the items table in your database to have a marker for each item so you know whether it is completed or not, then you will create a new route in your app.py file to change the value of this column depending on the user’s action.

      As a reminder the columns in the items table are currently the following:

      • id: The ID of the item.
      • list_id: The ID of the list the item belongs to.
      • created: The item’s creation date.
      • content: The item’s content.

      First, open schema.sql to modify the items table:

      Add a new column named done to the items table:

      flask_todo/schema.sql

      DROP TABLE IF EXISTS lists;
      DROP TABLE IF EXISTS items;
      
      CREATE TABLE lists (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
          title TEXT NOT NULL
      );
      
      CREATE TABLE items (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          list_id INTEGER NOT NULL,
          created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
          content TEXT NOT NULL,
          done INTEGER NOT NULL DEFAULT 0,
          FOREIGN KEY (list_id) REFERENCES lists (id)
      );
      

      Save and close the file.

      This new column will hold the integer values 0 or 1; the value 0 represents the Boolean value false and 1 represents the value true. The default is 0, which means any new items you add will automatically be unfinished until the user marks the item as complete, in which case the value of the done column will change to 1.

      Then, initialize the database again using the init_db.py program to apply the modifications you have performed on schema.sql:

      Next, open app.py for modification:

      You’ll fetch the id of the item and the value of the done column in the index() function, which fetches the lists and items from the database and sends them to the index.html file for display. The necessary changes to the SQL statement are highlighted in the following file:

      flask_todo/app.py

      @app.route('/')
      def index():
          conn = get_db_connection()
          todos = conn.execute('SELECT i.id, i.done, i.content, l.title 
                                FROM items i JOIN lists l 
                                ON i.list_id = l.id ORDER BY l.title;').fetchall()
      
          lists = {}
      
          for k, g in groupby(todos, key=lambda t: t['title']):
              lists[k] = list(g)
      
          conn.close()
          return render_template('index.html', lists=lists)
      

      Save and close the file.

      With this modification, you get the IDs of the to-do items using i.id and the values of the done column using i.done.

      To understand this change, open list_example.py, which is a small, example program you can use to understand the contents of the database:

      Perform the same modification to the SQL statement as before, then change the last print() function to display the item ID and the value of done:

      flask_todo/list_example.py

      from itertools import groupby
      from app import get_db_connection
      
      conn = get_db_connection()
      
      todos = conn.execute('SELECT i.id, i.done, i.content, l.title 
                            FROM items i JOIN lists l 
                            ON i.list_id = l.id ORDER BY l.title;').fetchall()
      
      lists = {}
      
      for k, g in groupby(todos, key=lambda t: t['title']):
          lists[k] = list(g)
      
      for list_, items in lists.items():
          print(list_)
          for item in items:
              print('    ', item['content'], '| id:',
                    item['id'], '| done:', item['done'])
      

      Save and exit the file.

      Run the example program:

      Here is the output:

      Output

      Home Buy fruit | id: 2 | done: 0 Cook dinner | id: 3 | done: 0 Study Learn Flask | id: 4 | done: 0 Learn SQLite | id: 5 | done: 0 Work Morning meeting | id: 1 | done: 0

      None of the items has been marked as completed so the value of done for each item is 0, which means false. To allow users to change this value and mark items as completed, you will add a new route to the app.py file.

      Open app.py:

      Add a route /do/ at the end of the file:

      flask_todo/app.py

      . . .
      @app.route('/<int:id>/do/', methods=('POST',))
      def do(id):
          conn = get_db_connection()
          conn.execute('UPDATE items SET done = 1 WHERE id = ?', (id,))
          conn.commit()
          conn.close()
          return redirect(url_for('index'))
      

      This new route accepts only POST requests. The do() view function takes an id argument—this is the ID of the item you want to mark as completed. Inside the function, you open a database connection, then you use an UPDATE SQL statement to set the value of the done column to 1 for the item to be marked as completed.

      You use the ? placeholder in the execute() method and pass a tuple containing the ID to safely insert data into the database. Then you commit the transaction and close the connection and redirect to the index page.

      After adding a route to mark items as completed, you need another route to undo this action and return the item to a non-completed status. Add the following route at the end of the file:

      flask_todo/app.py

      . . .
      @app.route('/<int:id>/undo/', methods=('POST',))
      def undo(id):
          conn = get_db_connection()
          conn.execute('UPDATE items SET done = 0 WHERE id = ?', (id,))
          conn.commit()
          conn.close()
          return redirect(url_for('index'))
      

      This route is similar to the /do/ route, and the undo() view function is exactly the same as the do() function except that you set the value of done to 0 instead of 1.

      Save and close the app.py file.

      You now need a button to mark to-do items as completed or uncompleted depending on the state of the item, open the index.html template file:

      • nano templates/index.html

      Change the contents of the inner for loop inside the <ul> element to look as follows:

      flask_todo/templates/index.html

      {% block content %}
          <h1>{% block title %} Welcome to FlaskTodo {% endblock %}</h1>
          {% for list, items in lists.items() %}
              <div class="card" style="width: 18rem; margin-bottom: 50px;">
                  <div class="card-header">
                      <h3>{{ list }}</h3>
                  </div>
                  <ul class="list-group list-group-flush">
                      {% for item in items %}
                          <li class="list-group-item"
                          {% if item['done'] %}
                          style="text-decoration: line-through;"
                          {% endif %}
                          >{{ item['content'] }}
                          {% if not item ['done'] %}
                              {% set URL = 'do' %}
                              {% set BUTTON = 'Do' %}
                          {% else %}
                              {% set URL = 'undo' %}
                              {% set BUTTON = 'Undo' %}
                          {% endif %}
      
      
      
                        <div class="row">
                              <div class="col-12 col-md-3">
                                  <form action="{{ url_for(URL, id=item['id']) }}"
                                      method="POST">
                                      <input type="submit" value="{{ BUTTON }}"
                                          class="btn btn-success btn-sm">
                                  </form>
                              </div>
                          </div>
                          </li>
                      {% endfor %}
                  </ul>
              </div>
          {% endfor %}
      {% endblock %}
      

      In this for loop, you use a line-through CSS value for the text-decoration property if the item is marked as completed, which you know from the value of item['done']. You then use the Jinja syntax set to declare two variables, URL and BUTTON. If the item is not marked as completed the button will have the value Do and the URL will direct to the /do/ route, and if the item was marked as completed, the button will have a value of Undo and will point to /undo/. After, you use both these variables in an input form that submits the proper request depending on the state of the item.

      Run the server:

      You can now mark items as completed on the index page http://127.0.0.1:5000/. Next you will add the ability to edit to-do items.

      Step 3 — Editing To-Do Items

      In this step, you will add a new page for editing items so you can modify the contents of each item and assign items to different lists.

      You will add a new /edit/ route to the app.py file, which will render a new edit.html page in which a user can modify existing items. You will also update the index.html file to add an Edit button to each item.

      First, open the app.py file:

      Then add the following route at the end of the file:

      flask_todo/app.py

      . . .
      @app.route('/<int:id>/edit/', methods=('GET', 'POST'))
      def edit(id):
          conn = get_db_connection()
      
          todo = conn.execute('SELECT i.id, i.list_id, i.done, i.content, l.title 
                               FROM items i JOIN lists l 
                               ON i.list_id = l.id WHERE i.id = ?', (id,)).fetchone()
      
          lists = conn.execute('SELECT title FROM lists;').fetchall()
      
          if request.method == 'POST':
              content = request.form['content']
              list_title = request.form['list']
      
              if not content:
                  flash('Content is required!')
                  return redirect(url_for('edit', id=id))
      
              list_id = conn.execute('SELECT id FROM lists WHERE title = (?);',
                                       (list_title,)).fetchone()['id']
      
              conn.execute('UPDATE items SET content = ?, list_id = ?
                            WHERE id = ?',
                           (content, list_id, id))
              conn.commit()
              conn.close()
              return redirect(url_for('index'))
      
          return render_template('edit.html', todo=todo, lists=lists)
      

      In this new view function, you use the id argument to fetch the ID of the to-do item you want to edit, the ID of the list it belongs to, the value of the done column, the content of the item, and the list title using a SQL JOIN. You save this data in the todo variable. Then you get all of the to-do lists from the database and save them in the lists variable.

      If the request is a normal GET request, the condition if request.method == 'POST' does not run, so the application executes the last render_template() function, passing both todo and lists to an edit.html file.

      If however, a form was submitted, the condition request.method == 'POST' becomes true, in which case you extract the content and the list title the user submitted. If no content was submitted, you flash the message Content is required! and redirect to the same edit page. Otherwise, you fetch the ID of the list the user submitted; this allows the user to move a to-do item from one list to another. Then, you use an UPDATE SQL statement to set the content of the to-do item to the new content the user submitted. You do the same for the list ID. Finally, you commit the changes and close the connection, and redirect the user to the index page.

      Save and close the file.

      To use this new route, you need a new template file called edit.html:

      Add the following contents to this new file:

      flask_todo/templates/edit.html

      {% extends 'base.html' %}
      
      {% block content %}
      
      <h1>{% block title %} Edit an Item {% endblock %}</h1>
      
      <form method="post">
          <div class="form-group">
              <label for="content">Content</label>
              <input type="text" name="content"
                     placeholder="Todo content" class="form-control"
                     value="{{ todo['content'] or request.form['content'] }}"></input>
          </div>
      
          <div class="form-group">
              <label for="list">List</label>
              <select class="form-control" name="list">
                  {% for list in lists %}
                      {% if list['title'] == request.form['list'] %}
                          <option value="{{ request.form['list'] }}" selected>
                              {{ request.form['list'] }}
                          </option>
      
                      {% elif list['title'] == todo['title'] %}
                          <option value="{{ todo['title'] }}" selected>
                              {{ todo['title'] }}
                          </option>
      
                      {% else %}
                          <option value="{{ list['title'] }}">
                              {{ list['title'] }}
                          </option>
                      {% endif %}
                  {% endfor %}
              </select>
          </div>
          <div class="form-group">
              <button type="submit" class="btn btn-primary">Submit</button>
          </div>
      </form>
      {% endblock %}
      

      You use the value {{ todo['content'] or request.form['content'] }} for the content input. This signifies that the value will be either the current content of the to-do item or what the user has submitted in a failed attempt to submit the form.

      For the list selection form, you loop through the lists variable, and if the list title is the same as the one stored in the request.form object (from a failed attempt), then set that list title as the selected value. Otherwise if the list title equals the one stored in the todo variable, then set it as the selected value. This is the current list title of the to-do item before any modification; the rest of the options are then displayed without the selected attribute.

      Save and close the file.

      Then, open index.html to add an Edit button:

      • nano templates/index.html

      Change the contents of the div tag with the "row" class to add another column as follows:

      flask_todo/templates/index.html

      . . .
      <div class="row">
          <div class="col-12 col-md-3">
              <form action="{{ url_for(URL, id=item['id']) }}"
                  method="POST">
                  <input type="submit" value="{{ BUTTON }}"
                      class="btn btn-success btn-sm">
              </form>
          </div>
          <div class="col-12 col-md-3">
              <a class="btn btn-warning btn-sm"
              href="https://www.digitalocean.com/community/tutorials/{{ url_for("edit', id=item['id']) }}">Edit</a>
          </div>
      </div>
      

      Save and close the file.

      This is a standard <a> link tag that points to the relevant /edit/ route for each item.

      Run the server if you haven’t already:

      You can now go to the index page http://127.0.0.1:5000/ and experiment with modifying to-do items. In the next step, you will add a button to delete items.

      Step 4 — Deleting To-Do Items

      In this step, you will add the ability to delete specific to-do items.

      You will first need to add a new /delete/ route, open app.py:

      Then add the following route at the end of the file:

      flask_todo/app.py

      . . .
      @app.route('/<int:id>/delete/', methods=('POST',))
      def delete(id):
          conn = get_db_connection()
          conn.execute('DELETE FROM items WHERE id = ?', (id,))
          conn.commit()
          conn.close()
          return redirect(url_for('index'))
      

      Save and close the file.

      The delete() view function accepts an id argument. When a POST request gets sent, you use the DELETE SQL statement to delete the item with the matching id value, then you commit the transaction and close the database connection, and return to the index page.

      Next, open templates/index.html to add a Delete button:

      • nano templates/index.html

      Add the following highlighted div tag below the Edit button:

      flask_todo/templates/index.html

      <div class="row">
          <div class="col-12 col-md-3">
              <form action="{{ url_for(URL, id=item['id']) }}"
                  method="POST">
                  <input type="submit" value="{{ BUTTON }}"
                      class="btn btn-success btn-sm">
              </form>
          </div>
      
          <div class="col-12 col-md-3">
              <a class="btn btn-warning btn-sm"
              href="https://www.digitalocean.com/community/tutorials/{{ url_for("edit', id=item['id']) }}">Edit</a>
          </div>
      
          <div class="col-12 col-md-3">
              <form action="https://www.digitalocean.com/community/tutorials/{{ url_for("delete', id=item['id']) }}"
                  method="POST">
                  <input type="submit" value="Delete"
                      class="btn btn-danger btn-sm">
              </form>
          </div>
      </div>
      

      This new submit button sends a POST request to the /delete/ route for each item.

      Save and close the file.

      Then run the development server:

      Go to the index page and try out the new Delete button—you can now delete any item you want.

      Now that you have added the ability to delete existing to-do items, you will move on to add the ability to add new lists in the next step.

      Step 5 — Adding New Lists

      So far, lists can only be added directly from the database. In this step, you will add the ability to create new lists when the user adds a new item, instead of only choosing between the existing lists. You will incorporate a new option called New List, which when chosen, the user can input the name of the new list they wish to create.

      First, open app.py:

      Then, modify the create() view function by adding the following highlighted lines to the if request.method == 'POST' condition:

      flask_todo/app.py

      . . .
      @app.route('/create/', methods=('GET', 'POST'))
      def create():
          conn = get_db_connection()
      
          if request.method == 'POST':
              content = request.form['content']
              list_title = request.form['list']
      
              new_list = request.form['new_list']
      
              # If a new list title is submitted, add it to the database
              if list_title == 'New List' and new_list:
                  conn.execute('INSERT INTO lists (title) VALUES (?)',
                               (new_list,))
                  conn.commit()
                  # Update list_title to refer to the newly added list
                  list_title = new_list
      
              if not content:
                  flash('Content is required!')
                  return redirect(url_for('index'))
      
              list_id = conn.execute('SELECT id FROM lists WHERE title = (?);',
                                       (list_title,)).fetchone()['id']
              conn.execute('INSERT INTO items (content, list_id) VALUES (?, ?)',
                           (content, list_id))
              conn.commit()
              conn.close()
              return redirect(url_for('index'))
      
          lists = conn.execute('SELECT title FROM lists;').fetchall()
      
          conn.close()
          return render_template('create.html', lists=lists)
      

      Save and close the file.

      Here you save the value of a new form field called new_list in a variable. You will add this field later to the create.html file. Next, in the list_title == 'New List' and new_list condition, you check whether the list_title has the value 'New List', which indicates that the user wishes to create a new list. You also check that the value of the new_list variable is not None, if this condition is met, you use an INSERT INTO SQL statement to add the newly submitted list title to the lists table. You commit the transaction, then you update the value of the list_title variable to match that of the newly added list for later use.

      Next, open create.html to add a new <option> tag to let the user add a new list:

      • nano templates/create.html

      Modify the file by adding the highlighted tags in the following code:

      flask_todo/templates/create.html

          <div class="form-group">
              <label for="list">List</label>
              <select class="form-control" name="list">
                  <option value="New List" selected>New List</option>
                  {% for list in lists %}
                      {% if list['title'] == request.form['list'] %}
                          <option value="{{ request.form['list'] }}" selected>
                              {{ request.form['list'] }}
                          </option>
                      {% else %}
                          <option value="{{ list['title'] }}">
                              {{ list['title'] }}
                          </option>
                      {% endif %}
                  {% endfor %}
              </select>
          </div>
      
          <div class="form-group">
              <label for="new_list">New List</label>
              <input type="text" name="new_list"
                      placeholder="New list name" class="form-control"
                      value="{{ request.form['new_list'] }}"></input>
          </div>
      
          <div class="form-group">
              <button type="submit" class="btn btn-primary">Submit</button>
          </div>
      

      Save and close the file.

      You have added a new <option> tag to refer to the New List option, this will allow the user to specify that they want to create a new list. Then you add another <div> with an input field named new_list, this field is where the user will input the title of the new list they wish to create.

      Finally, run the development server:

      Then visit the index page:

      http://127.0.0.1:5000/
      

      The application will now look as follows:

      Todo Application

      With the new additions to your application, users can now mark to-do items as complete or restore completed items to a non-completion state, edit and delete existing items, and create new lists for different kinds of to-do tasks.

      You can browse the full source code of the application in the DigitalOcean Community Repository.

      Conclusion

      You now have a complete to-do application in which users can create new to-do items, mark an item as complete, and edit or delete existing items, in addition to the ability to create new lists. You have modified a Flask web application, added new features to it, and modified database items specifically in a One-to-Many relationship. You may develop this application further by learning How To Add Authentication to Your App with Flask-Login to add security to your Flask application.



      Source link

      Processing Incoming Request Data in Flask


      In any web app, you’ll have to process incoming request data from users. Flask, like any other web framework, allows you to access the request data easily.

      In this tutorial, we’ll go through how to process incoming data for the most common use cases. The forms of incoming data we’ll cover are: query strings, form data, and JSON objects. To demonstrate these cases, we’ll build a simple example app with three routes that accept either query string data, form data, or JSON data.

      The Request Object

      To access the incoming data in Flask, you have to use the request object. The request object holds all incoming data from the request, which includes the mimetype, referrer, IP address, raw data, HTTP method, and headers, among other things. Although all the information the request object holds can be useful, in this article, we’ll only focus on the data that is normally directly supplied by the caller of our endpoint.

      To gain access to the request object in Flask, you simply import it from the Flask library.

      from flask import request
      

      You then have the ability to use it in any of your view functions.

      Once we get to the section on query strings, you’ll get to see the request object in action.

      The Example App

      To demonstrate the different ways of using request, we’ll start with a simple Flask app. Even though the example app uses a simple organization layout for the view functions and routes, what you learn in this tutorial can be applied to any method of organizing your views like class-based views, blueprints, or an extension like Flask-Via.

      To get started, first we need to install Flask.

      pip install Flask
      

      Then, we can start with the following code.

      #app.py
      
      from flask import Flask, request #import main Flask class and request object
      
      app = Flask(__name__) #create the Flask app
      
      @app.route('/query-example')
      def query_example():
          return 'Todo...'
      
      @app.route('/form-example')
      def formexample():
          return 'Todo...'
      
      @app.route('/json-example')
      def jsonexample():
          return 'Todo...'
      
      if _name == '__main_':
          app.run(debug=True, port=5000) #run app in debug mode on port 5000
      

      Start the app with:

      python app.py
      

      The code supplied sets up three routes with a message telling us ‘Todo…’. The app will start on port 5000, so you can view each route in your browser with the following links:

      http://127.0.0.1:5000/query-example (or localhost:5000/query-example)
      http://127.0.0.1:5000/form-example (or localhost:5000/form-example)
      http://127.0.0.1:5000/json-example (or localhost:5000/json-example)

      For each of the three routes, you’ll see the same thing:

      Query Arguments

      URL arguments that you add to a query string are the simpliest way to pass data to a web app, so let’s start with them.

      A query string looks like the following:

      example.com?arg1=value1&arg2=value2
      

      The query string begins after the question mark (?) and has two key-value pairs separated by an ampersand (&). For each pair, the key is followed by an equals sign (=) and then the value. Even if you’ve never heard of a query string until now, you have definitely seen them all over the web.

      So in that example, the app receives:

      arg1 : value1
      arg2 : value2
      

      Query strings are useful for passing data that doesn’t require the user to take action. You could generate a query string somewhere in your app and append it a URL so when a user makes a request, the data is automatically passed for them. A query string can also be generated by forms that have GET as the method.

      To create our own query string on the query-example route, we’ll start with this simple one:

      http://127.0.0.1:5000/query-example?language=Python

      If you run the app and navigate to that URL, you’ll see that nothing has changed. That’s only because we haven’t handled the query arguments yet.

      To do so, we’ll need to read in the language key by using either request.args.get('language') or request.args['language'].

      By calling request.args.get('language'), our application will continue to run if the language key doesn’t exist in the URL. In that case, the result of the method will be None. If we use request.args['language'], the app will return a 400 error if language key doesn’t exist in the URL. For query strings, I recommend using request.args.get() because of how easy it is for the user to modify the URL. If they remove one of the keys, request.args.get() will prevent the app from failing.

      Let’s read the language key and display it as output. Modify with query-example route the following code.

      @app.route('/query-example')
      def query_example():
          language = request.args.get('language') #if key doesn't exist, returns None
      
          return '''<h1>The language value is: {}</h1>'''.format(language)
      

      Then run the app and navigate to the URL.

      As you can see, the argument from the URL gets assigned to the language variable and then gets returned to the browser. In a real app, you’d probably want to do something with the data other than simply return it.

      To add more query string parameters, we just append ampersands and the new key-value pairs to the end of the URL. So an additional pair would look like this:

      http://127.0.0.1:5000/query-example?language=Python&framework=Flask

      With the new pair being:

      framework : Flask
      

      And if you want more, continue adding ampersands and key-value pairs. Here’s an example:

      http://127.0.0.1:5000/query-example?language=Python&framework=Flask&website=Scotch

      To gain access to those values, we still use either request.args.get() or request.args[]. Let’s use both to demonstrate what happens when there’s a missing key. We’ll assign the value of the results to variables and then display them.

      @app.route('/query-example')
      def query_example():
          language = request.args.get('language') #if key doesn't exist, returns None
          framework = request.args['framework'] #if key doesn't exist, returns a 400, bad request error
          website = request.args.get('website')
      
          return '''<h1>The language value is: {}</h1>
                    <h1>The framework value is: {}</h1>
                    <h1>The website value is: {}'''.format(language, framework, website)
      

      When you run that, you should see:

      If you remove the language from the URL, then you’ll see that the value ends up as None.

      If you remove the framework key, you get an error.

      Now that you undertand query strings, let’s move on to the next type of incoming data.

      Form Data

      Next we have form data. Form data comes from a form that has been sent as a POST request to a route. So instead of seeing the data in the URL (except for cases when the form is submitted with a GET request), the form data will be passed to the app behind the scenes. Even though you can’t easily see the form data that gets passed, your app can still read it.

      To demonstrate this, modify the form-example route to accept both GET and POST requests and to return a simple form.

      @app.route('/form-example', methods=['GET', 'POST']) #allow both GET and POST requests
      def form_example():
          return '''<form method="POST">
                        Language: <input type="text" name="language"><br>
                        Framework: <input type="text" name="framework"><br>
                        <input type="submit" value="Submit"><br>
                    </form>'''
      

      Running the app results in this:

      The most important thing to know about this form is that it performs a POST request to the same route that generated the form. The keys that we’ll read in our app all come from the “name” attributes on our form inputs. In our case, language and framework are the names of the inputs, so we’ll have access to those in our app.

      Inside the view function, we need to check if the request method is GET or POST. If it’s GET, we simply display the form we have. If it’s POST, then we want to process the incoming data.

      To do that, let’s add a simple if statement that checks for a POST request. If the request method isn’t POST, then we know it’s GET, because our route only allows those two types of requests. For GET requests, the form will be generated.

      @app.route('/form-example', methods=['GET', 'POST']) #allow both GET and POST requests
      def form_example():
          if request.method == 'POST': #this block is only entered when the form is submitted
              return 'Submitted form.'
      
          return '''<form method="POST">
                        Language: <input type="text" name="language"><br>
                        Framework: <input type="text" name="framework"><br>
                        <input type="submit" value="Submit"><br>
                    </form>'''
      

      Inside of the block, we’ll read the incoming values with request.args.get('language') and request.form['framework']. Remember that if we have more inputs, then we can read additional data.

      Add the additional code to the form-example route.

      @app.route('/form-example', methods=['GET', 'POST']) #allow both GET and POST requests
      def form_example():
          if request.method == 'POST':  #this block is only entered when the form is submitted
              language = request.form.get('language')
              framework = request.form['framework']
      
              return '''<h1>The language value is: {}</h1>
                        <h1>The framework value is: {}</h1>'''.format(language, framework)
      
          return '''<form method="POST">
                        Language: <input type="text" name="language"><br>
                        Framework: <input type="text" name="framework"><br>
                        <input type="submit" value="Submit"><br>
                    </form>'''
      

      Try running the app and submitting the form.

      Similiar to the query string example before, we can use request.form.get() instead of referencing the key directly with request.form[]. request.form.get() returns None instead of causing a 400 error when the key isn’t found.

      As you can see, handling submitted form data is just as easy as handling query string arguments.

      JSON Data

      Finally, we have JSON data. Like form data, it’s not so easy to see. JSON data is normally constructed by a process that calls our route. An example JSON object looks like this:

      {
          "language" : "Python",
          "framework" : "Flask",
          "website" : "Scotch",
          "version_info" : {
              "python" : 3.4,
              "flask" : 0.12
          },
          "examples" : ["query", "form", "json"],
          "boolean_test" : true
      }
      

      As you can see with JSON, you can pass much more complicated data that you could with query strings or form data. In the example, you see nested JSON objects and an array of items. With Flask, reading all of these values is straightforward.

      First, to send a JSON object, we’ll need a program capable of sending custom requests to URLs. For this, we can use an app called Postman.

      Before we use Postman though, change the method on the route to accept only POST requests.

      @app.route('/json-example', methods=['POST']) #GET requests will be blocked
      def json_example():
          return 'Todo...'
      

      Then in Postman, let’s do a little set up to enable sending POST requests.

      In Postman, add the URL and change the type to POST. On the body tab, change to raw and select JSON (application/json) from the drop down. All this is done so Postman can send JSON data properly and so your Flask app will understand that it’s receiving JSON.

      From there, you can copy the example into the text input. It should look like this:

      To test, just send the request and you should get ‘Todo…’ as the response because we haven’t modified our function yet.

      To read the data, first you must understand how Flask translates JSON data into Python data structures.

      Anything that is an object gets converted to a Python dict. {"key" : "value"} in JSON corresponds to somedict['key'], which returns a value in Python.

      An array in JSON gets converted to a list in Python. Since the syntax is the same, here’s an example list: [1,2,3,4,5]

      Then the values inside of quotes in the JSON object become strings in Python. true and false become True and False in Python. Finally, numbers without quotes around them become numbers in Python.

      Now let’s get on to reading the incoming JSON data.

      First, let’s assign everything from the JSON object into a variable using request.get_json().

      req_data = request.get_json()
      

      request.get_json() converts the JSON object into Python data for us. Let’s assign the incoming request data to variables and return them by making the following changes to our json-example route.

      @app.route('/json-example', methods=['POST']) #GET requests will be blocked
      def json_example():
          req_data = request.get_json()
      
          language = req_data['language']
          framework = req_data['framework']
          python_version = req_data['version_info']['python'] #two keys are needed because of the nested object
          example = req_data['examples'][0] #an index is needed because of the array
          boolean_test = req_data['boolean_test']
      
          return '''
                 The language value is: {}
                 The framework value is: {}
                 The Python version is: {}
                 The item at index 0 in the example list is: {}
                 The boolean value is: {}'''.format(language, framework, python_version, example, boolean_test)
      

      If we run our app and submit the same request using Postman, we will get this:

      Note how you access elements that aren’t at the top level. ['version']['python'] is used because you are entering a nested object. And ['examples'][0] is used to access the 0th index in the examples array.

      If the JSON object sent with the request doesn’t have a key that is accessed in your view function, then the request will fail. If you don’t want it to fail when a key doesn’t exist, you’ll have to check if the key exists before trying to access it. Here’s an example:

      language = None
      if 'language' in req_data:
          language = req_data['language']
      

      Conclusion

      You should now understand how to use the request object in Flask to get the most common forms of input data. To recap, we covered:

      • Query Strings
      • Form Data
      • JSON Data

      With this knowledge, you’ll have no problem with any data that users throw at your app!

      Learn More

      If you like this tutorial and want to learn more about Flask from me, check out my free Intro to Flask video course at my site Pretty Printed, which takes you from knowing nothing about Flask to building a guestbook app. If that course isn’t at your level, then I have other courses on my site that may interest you as well.



      Source link