学习Flask:Day 2:模板与表单开发

news/2025/2/26 18:28:55

学习目标:前后端混合开发

python"># 添加模板渲染
from flask import render_template

@app.route('/profile')
def profile():
    return render_template('profile.html', 
                         username="开发者",
                         skills=['Vue', 'JavaScript'])

✅ 实践任务

  1. 创建templates目录

  2. 使用Jinja2语法制作包含循环和条件判断的模板

  3. 实现一个注册表单(GET/POST处理)

  4. 使用Bootstrap美化页面

要在 Flask 应用中创建 templates 目录以支持 HTML 模板,你可以按照以下步骤进行:

  • 创建 templates 目录:在你的项目根目录下创建一个名为 templates 的文件夹。
  • 创建 HTML 文件:在 templates 目录中创建 HTML 文件,例如 home.html 和 profile.html。
  • 更新 Flask 路由:修改 Flask 路由以渲染这些模板。

以下是一个示例,展示了如何实现这些步骤:

1. 创建 templates 目录和 HTML 文件

在项目根目录下创建 templates 文件夹,并在其中创建以下两个文件:

  • home.html
  • profile.html

home.html 内容:

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
    <h1>欢迎来到首页!</h1>
</body>
</html>

profile.html 内容:

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>用户资料</title>
</head>
<body>
    <h1>这是用户资料页面。</h1>
</body>
</html>

2. 更新 Flask 路由

接下来,更新 app.py 文件以渲染这些模板:

python"># app.py
from flask import Flask, jsonify, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html')

@app.route('/profile')
def profile():
    return render_template('profile.html')

@app.route('/api')
def api():
    return jsonify({"message": "这是API端点。"})

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

说明:

  • 使用 render_template 函数来渲染 HTML 模板。
  • 当访问首页时,Flask 将返回 home.html 的内容;访问用户资料页面时,将返回 profile.html 的内容。

运行应用:

确保你的项目结构如下:

python">/your_project_directory
    ├── app.py
    └── templates
        ├── home.html
        └── profile.html

然后在终端中运行 python app.py,并在浏览器中访问相应的路由来查看效果。

使用 Jinja2 语法,你可以在模板中实现循环和条件判断。以下是如何在 Flask 应用中使用 Jinja2 创建包含循环和条件判断的模板的示例。

1. 更新 home.html 模板

我们将更新 home.html 模板,以展示一个包含循环和条件判断的示例。假设我们有一个用户列表,并根据用户的状态显示不同的信息。

更新后的 home.html 内容:

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
    <h1>欢迎来到首页!</h1>
    
    <h2>用户列表</h2>
    <ul>
        {% for user in users %}
            <li>
                {{ user.name }} - 
                {% if user.active %}
                    <span style="color: green;">活跃</span>
                {% else %}
                    <span style="color: red;">不活跃</span>
                {% endif %}
            </li>
        {% endfor %}
    </ul>
</body>
</html>

2. 更新 app.py 文件

接下来,我们需要在 app.py 中传递一个用户列表到模板中:

python"># app.py
from flask import Flask, jsonify, render_template

app = Flask(__name__)

@app.route('/')
def home():
    users = [
        {"name": "张三", "active": True},
        {"name": "李四", "active": False},
        {"name": "王五", "active": True}
    ]
    return render_template('home.html', users=users)

@app.route('/profile')
def profile():
    return render_template('profile.html')

@app.route('/api')
def api():
    return jsonify({"message": "这是API端点。"})

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

说明:

  • 在 home.html 中,使用 {% for user in users %} 语法来循环遍历用户列表。
  • 使用 {% if user.active %} 语法来判断用户是否活跃,并根据条件显示不同的文本。
  • 在 app.py 中,我们创建了一个用户列表,并将其传递给模板。

运行应用:

确保你的项目结构仍然正确,然后在终端中运行 python app.py。访问首页时,你将看到用户列表及其状态的显示。

要实现一个注册表单并处理 GET 和 POST 请求,你可以按照以下步骤进行:

1. 创建注册表单模板

首先,在 templates 目录中创建一个新的 HTML 文件,例如 register.html,用于显示注册表单。

register.html 内容:

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>注册</title>
</head>
<body>
    <h1>注册表单</h1>
    <form method="POST" action="/register">
        <label for="username">用户名:</label>
        <input type="text" id="username" name="username" required>
        <br>
        <label for="password">密码:</label>
        <input type="password" id="password" name="password" required>
        <br>
        <button type="submit">注册</button>
    </form>
</body>
</html>

2. 更新 app.py 文件

接下来,更新 app.py 文件以处理注册表单的 GET 和 POST 请求。

python"># app.py
from flask import Flask, jsonify, render_template, request, redirect, url_for

app = Flask(__name__)

@app.route('/')
def home():
    users = [
        {"name": "张三", "active": True},
        {"name": "李四", "active": False},
        {"name": "王五", "active": True}
    ]
    return render_template('home.html', users=users)

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        # 在这里可以添加用户注册逻辑,例如保存到数据库
        print(f"注册用户: {username}, 密码: {password}")  # 仅用于示例
        return redirect(url_for('home'))  # 注册后重定向到首页
    return render_template('register.html')

@app.route('/profile')
def profile():
    return render_template('profile.html')

@app.route('/api')
def api():
    return jsonify({"message": "这是API端点。"})

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

说明:

  • 在 register.html 中,创建了一个简单的注册表单,包含用户名和密码字段,使用 POST 方法提交。
  • 在 app.py 中,添加了 /register 路由,处理 GET 和 POST 请求:
  • 当请求方法为 POST 时,获取表单数据并打印(在实际应用中,你可以将其保存到数据库)。
  • 注册成功后,使用 redirect 和 url_for 重定向到首页。
  • 当请求方法为 GET 时,渲染注册表单。

运行应用:

确保你的项目结构正确,然后在终端中运行 python app.py。访问 http://127.0.0.1:5000/register 来查看注册表单,填写信息并提交后将重定向到首页。

要使用 Bootstrap 美化你的 Flask 应用页面,你可以按照以下步骤进行:

1. 引入 Bootstrap

在你的 HTML 模板中引入 Bootstrap 的 CSS 和 JS 文件。你可以使用 Bootstrap 的 CDN(内容分发网络)来快速引入。

2. 更新模板

我们将更新 home.html 和 register.html 模板,以使用 Bootstrap 的样式和组件。

更新后的 home.html 内容:
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <h1 class="mt-5">欢迎来到首页!</h1>
        
        <h2>用户列表</h2>
        <ul class="list-group">
            {% for user in users %}
                <li class="list-group-item">
                    {{ user.name }} - 
                    {% if user.active %}
                        <span class="text-success">活跃</span>
                    {% else %}
                        <span class="text-danger">不活跃</span>
                    {% endif %}
                </li>
            {% endfor %}
        </ul>
    </div>
</body>
</html>
更新后的 register.html 内容:
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>注册</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <h1 class="mt-5">注册表单</h1>
        <form method="POST" action="/register">
            <div class="form-group">
                <label for="username">用户名:</label>
                <input type="text" id="username" name="username" class="form-control" required>
            </div>
            <div class="form-group">
                <label for="password">密码:</label>
                <input type="password" id="password" name="password" class="form-control" required>
            </div>
            <button type="submit" class="btn btn-primary">注册</button>
        </form>
    </div>
</body>
</html>

说明:

  • 在每个模板的 <head> 部分引入了 Bootstrap 的 CSS 文件。
  • 使用 Bootstrap 的类来美化页面:
  • 在 home.html 中,使用 container 类来设置页面的边距,使用 list-group 和 list-group-item 类来美化用户列表。
  • 在 register.html 中,使用 form-group 和 form-control 类来美化表单输入框,使用 btn 和 btn-primary 类来美化按钮。

运行应用:

确保你的项目结构正确,然后在终端中运行 python app.py。访问首页和注册页面,你将看到使用 Bootstrap 美化后的页面。


http://www.niftyadmin.cn/n/5869056.html

相关文章

为什么MySQL选择使用B+树作为索引结构

B树是MySQL最常见的索引结构&#xff0c;大部分存储引擎都支持 B 树索引。 相对于其他竞争力强的数据结构&#xff0c;B树都有战胜它们成为大多时候MySQL选择使用索引结构的理由&#xff1a; 第一个强有力的竞争对手是B树&#xff1a; 1. B树每个节点都存储了完整的数据&…

Postman参数介绍

Params 查询参数 Params 请求url信息&#xff0c;会补充请求的url 在 Postman 中处理查询参数&#xff08;Query Parameters&#xff09; 查询参数以键值对形式附加于 URL 末端&#xff0c;用于调整请求结果&#xff0c;在 Postman 中的传递通过用户友好的界面轻松完成。 首…

【滑动窗口算法】-- 长度最小的子数组

文章目录 1. 题目2. 题目解析3. 代码 1. 题目 在线oj 给定一个含有 n 个正整数的数组和一个正整数 target 。 找出该数组中满足其总和大于等于 target 的长度最小的 子数组 [numsl, numsl1, ..., numsr-1, numsr] &#xff0c;并返回其长度。如果不存在符合条件的子数组&…

Java如何解决彻底解决,大数据量excel导出内存溢出问题

一、核心工具选型&#xff1a;流式处理框架 1. 使用EasyExcel&#xff08;推荐&#xff09; 阿里巴巴开源的EasyExcel基于流式读写设计&#xff0c;通过逐行处理数据避免内存堆积。 优势&#xff1a; 内存占用低&#xff0c;支持百万级数据导出&#xff1b; 内置分页写入、自…

办公自动化|xlwings使用公式和函数

1. 介绍 xlwings xlwings 是一个强大的 Python 库&#xff0c;能够用于 Excel 自动化操作。除了基本的数据读写和格式设置&#xff0c;xlwings 还支持写入 Excel 公式、调用内置函数以及创建自定义函数&#xff0c;使得 Python 与 Excel 之间的交互更加灵活。 2. 在单元格中使…

智慧城市与安防监控:PoE交换机在高清视频监控中的优势

安防监控系统&#xff0c;尤其是高清摄像头&#xff08;如IP摄像头、PTZ云台、热成像摄像头&#xff09;在现代安防应用中大量部署&#xff0c;这些设备对电力和数据的传输需求非常高。传统的电源布线方式往往不能满足大规模、高质量设备的需求&#xff0c;而PoE交换机不仅解决…

跳跃游戏两则

跳跃游戏 给你一个非负整数数组 nums &#xff0c;你最初位于数组的 第一个下标 。数组中的每个元素代表你在该位置可以跳跃的最大长度。 判断你是否能够到达最后一个下标&#xff0c;如果可以&#xff0c;返回 true &#xff1b;否则&#xff0c;返回 false 。 思路 这里只…

Linux | RHEL / CentOS 中 YUM history / downgrade 命令回滚操作

注&#xff1a;英文引文&#xff0c;机翻未校。 在 RHEL/CentOS 系统上使用 YUM history 命令回滚升级操作 作者&#xff1a; 2daygeek 译者&#xff1a; LCTT DarkSun 为服务器打补丁是 Linux 系统管理员的一项重要任务&#xff0c;为的是让系统更加稳定&#xff0c;性能更加…