Coursera 笔记

Module 02 · Web App Deployment using Flask

CRUD Operations using Additional Features in Flask在 Flask 中使用附加功能进行 CRUD 操作

Coursera ↗

Estimated time needed: 15 minutes
预计所需时间:15 分钟

Overview 概述

Create, Read, Update, and Delete (CRUD) are basic functions that any application with a database must perform. To effectively implement the CRUD operations, you will need to manage different HTTP methods, such as GET and POST requests. A GET request is generally used to retrieve or read data and is often used to display a form. A POST request is commonly used to send data to create or update data. An example of a POST request is form submission.
创建、读取、更新和删除(CRUD)是任何具有数据库的应用程序都必须执行的基本功能。为了有效实现CRUD 操作,您需要管理不同的 HTTP 方法,例如 GET 和 POST 请求。 GET 请求通常用于检索或读取数据,并常用于显示表单。 POST 请求通常用于发送数据以创建或更新数据。POST 请求的一个例子是表单提交。

This reading aims to introduce you to additional features of Flask, focusing on the CRUD functions. You will also learn how these functions are interrelated and how they utilize the different HTML files, dynamic routes, and various HTTP methods.
本阅读旨在介绍 Flask 的附加功能,重点关注CRUD功能。您还将学习这些功能是如何相互关联的,以及它们如何利用不同的 HTML 文件、动态路由和各种 HTTP 方法。

Objectives 目标

In this reading, you will:
在这个阅读中,你将:

  • Access form data to capture user inputs with flask.request.form in POST requests
    通过 flask.request.form 在 POST 请求中访问表单数据以捕获用户输入
  • Control user navigation: using the Flask's redirect function
    控制用户导航:使用 Flask 的 redirect 函数
  • Generate URLs dynamically using url_for to create adaptable URLs in your Flask application
    使用 url_for 动态生成 URL,在 Flask 应用中创建可适应的 URL
  • Manage different HTTP request types to design flexible routes that respond to various HTTP request types
    管理不同的 HTTP 请求类型,以设计灵活的路线,以响应各种 HTTP 请求类型
  • Implement CRUD operations for data management in a Flask app
    在 Flask 应用中实现 CRUD 操作以进行数据管理

Note: Each section includes relevant code examples and explanations to enhance your understanding of the crucial Flask features.
注意:每个部分都包含相关的代码示例和解释,以增强您对 Flask 关键特性的理解。

Accessing Form Data with flask.request.form 使用 flask.request.form 访问表单数据

You can use flask.request.form to access form data that a user has submitted via a POST request. For instance, this feature can be used if you have a login form with username and password fields.
您可以使用 flask.request.form 访问用户通过 POST 请求提交的表单数据。例如,如果您有一个包含用户名和密码字段的登录表单,可以使用此功能。

In your HTML file, you might have a form like this:
在您的 HTML 文件中,您可能有一个如下所示的表单:

<form method="POST" action="/login">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="Submit">
</form>

The Python code to access the username and password will be as follows:
访问用户名和密码的 Python 代码如下:

from flask import request

@app.route('/login', methods=['POST'])
def login():
    username = request.form['username']
    password = request.form['password']
    # process login here

Redirecting to a URL with flask.redirect 使用 flask.redirect 重定向到 URL

Flask provides a function called flask.redirect to guide users to a different webpages (or endpoints). The flask.redirect function can be useful in several scenarios. For example, you can use the flask.redirect function to redirect a user to a login page when they try to access a restricted admin page.
Flask 提供了一个名为 flask.redirect 的函数,用于引导用户跳转到不同的网页(或端点)。flask.redirect 函数在多种场景中非常有用。例如,您可以使用 flask.redirect 函数在用户尝试访问受限的管理页面时将其重定向到登录页面。

Python code:  Python 代码:

from flask import redirect

@app.route('/admin')
def admin():
    return redirect('/login')

Generating Dynamic URLs with flask.url_for 使用 flask.url_for 生成动态 URL

The flask.url_for function dynamically generates URLs for a given endpoint. Dynamically generating URLs can be particularly useful when the URL for a route is altered. The flask.url_for function automatically updates the URL throughout your templates or code, minimizing manual work. For example, consider the scenario where a user is trying to access the admin page and must be redirected to the login page. In this scenario, url_for('login') will retrieve the URL for the login page from the existing routes.
flask.url_for 函数动态生成给定端点的 URL。动态生成 URL 在路由的 URL 发生更改时特别有用。 flask.url_for 函数会自动在整个模板或代码中更新 URL,从而减少手动工作。例如,考虑用户尝试访问管理页面并被重定向到登录页面的场景。在这种情况下, url_for('login') 将从现有的路由中检索登录页面的 URL。

Python code:  Python 代码:

from flask import url_for

@app.route('/admin')
def admin():
    return redirect(url_for('login'))

@app.route('/login')
def login():
    return "<Login Page>"

Handling different HTTP request types 处理不同的 HTTP 请求类型

Flask allows you to define routes to manage different types of HTTP requests. You can define the route with both the access methods, GET and POST, and in the function description, define the use cases for both methods.
Flask 允许您定义路由来管理不同类型的 HTTP 请求。您可以同时使用访问方法定义路由,GET 和 POST,并在函数描述中定义这两种方法的用例。

Python code:  Python 代码:

@app.route('/data', methods=['GET', 'POST'])
def data():
    if request.method == 'POST':
        # process POST request
    if request.method == 'GET':
        # process GET request

In the HTML file, you will add a form that allows both GET and POST requests:
在 HTML 文件中,您将添加一个表单,该表单允许处理 GET 和 POST 请求:

<!-- For POST -->
<form method="POST" action="/data">
<!-- Your input fields here -->
<input type="submit" value="Submit">
</form>

<!-- For GET -->
<a href="/data">Fetch data</a>

In the last example, the /data route accepts both GET and POST requests. The type of the request can be checked using flask.request.method.
在最后一个示例中, /data 路由可以接受 GET 和 POST 请求。可以通过 flask.request.method 检查请求类型。

CRUD operations CRUD 操作

The CRUD operations represent the four basic functions that you require to interact with any persistent storage, such as a database. In web development, the CRUD operations often correspond to HTTP methods.
CRUD操作代表您需要与任何持久化存储(如数据库)交互的四个基本功能。在 Web 开发中,CRUD 操作通常对应于 HTTP 方法。

Create operation 创建操作

Creating data often involves presenting a form to the user to gather the information that you want to store in the database as a new record. In Flask, this data is accessed using flask.request.form.
创建数据通常涉及向用户展示一个表单,以收集您希望存储在数据库中的新记录信息。在 Flask 中,通过 flask.request.form 访问这些数据。

HTML form for creating data:
用于创建数据的 HTML 表单:

<form method="POST" action="/create">
<input type="text" name="name">
<input type="submit" value="Create">
</form>

Python code:  Python 代码:

@app.route('/create', methods=['GET', 'POST'])
def create():
    if request.method == 'POST':
        # Access form data
        name = request.form['name']
        # Create a new record with the name
        record = create_new_record(name)  # Assuming you have this function defined
        # Redirect user to the new record
        return redirect(url_for('read', id=record.id))
    # Render the form for GET request
    return render_template('create.html')

Read operation 读操作

Reading data involves accessing the data and presenting it to the user. To access specific entries, the request needs to go with specific IDs. Therefore, you will need to pass the ID as an argument to the function. The following example shows that the ID can be accessed from the route.
读取数据涉及访问数据并向用户展示。要访问特定条目,请求需要附带特定的 ID。因此,您需要将 ID 作为参数传递给函数。以下示例展示了 ID 可以从路由中获取。

Python code:  Python 代码:

@app.route('/read/<int:id>', methods=['GET'])
def read(id):
    # Get the record by id
    record = get_record(id)  # Assuming you have this function defined
    # Render a template with the record
    return render_template('read.html', record=record)

Update operation 更新操作

Updating data requires the process of accessing specific entries, like the Read operation, and involves giving new data to the concerned parameter, like the Create operation. Therefore, the route should access the ID and contain both access methods.
更新数据需要访问特定条目的过程,例如读取操作,并涉及向相关参数提供新数据,例如创建操作。因此,路径应访问 ID 并包含这两种访问方法。

Sample HTML form for updating data:
更新数据的示例 HTML 表单:

<form method="POST" action="/update/{{record.id}}">
<input type="text" name="name" value="{{record.name}}">
<input type="submit" value="Update">
</form>

Python code:  Python 代码:

@app.route('/update/<int:id>', methods=['GET', 'POST'])
def update(id):
    if request.method == 'POST':
        # Access form data
        name = request.form['name']
        # Update the record with the new name
        update_record(id, name)  # Assuming you have this function defined
        # Redirect user to the updated record
        return redirect(url_for('read', id=id))

    # Render the form for GET request with current data
    record = get_record(id)  # Assuming you have this function defined
    return render_template('update.html', record=record)

Delete operation 删除操作

Deleting data involves removing a record based on its ID. The Delete operation will typically require the ID to be passed, as reported by the HTML page, in the form of an argument to the function.
删除数据涉及根据其 ID 删除记录。删除操作通常需要将 ID 作为参数传递给函数,正如 HTML 页面所报告的那样。

Sample HTML form for deleting data:
删除数据的示例 HTML 表单:

<form method="POST" action="/delete/{{record.id}}">
<input type="submit" value="Delete">
</form>

Python code:  Python 代码:

@app.route('/delete/<int:id>', methods=['POST'])
def delete(id):
    # Delete the record
    delete_record(id)  # Assuming you have this function defined
    # Redirect user to the homepage
    return redirect(url_for('home'))

Author(s) 作者

Vicky Kuo

Additional Contributor 额外贡献者

Abhishek Gagneja  阿比什克·甘格贾

Changelog 变更日志

Date  日期 Version  版本 Changed by  被更改 Change Description  修改描述
2023-07-24 2.0 Steve Hord QA pass with edits
经修改通过质量检验
2023-07-20 1.0 Vicky Kuo Initial version created  初始版本创建

© IBM Corporation 2023. All rights reserved. © IBM Corporation 2023。版权所有。