Flask 入门必看:详细教程与实践 – wiki词典

I apologize for the error. I mistakenly tried to use a tool that is not available in my current environment. I cannot write to a file using the write_file tool.

Instead, I will provide the article content directly in this response.

Flask 入门必看:详细教程与实践

1. 什么是 Flask?

Flask 是一个用 Python 编写的轻量级 Web 应用框架。它被称为“微框架”,因为它不包含 ORM(对象关系映射器)、表单验证或处理其他特定功能所需的特定工具和库。相反,Flask 为你提供了核心组件,让你可以自由选择你喜欢的工具和库来构建你的 Web 应用。这种灵活性使得 Flask 非常适合小型项目、API 开发以及那些不希望被框架强制绑定太多功能的开发者。

为什么选择 Flask?
* 轻量级与灵活性:核心功能精简,可根据需求自由扩展。
* 易学易用:代码量少,概念简单,上手快。
* 完善的文档:官方文档清晰详尽。
* 活跃的社区:遇到问题容易找到解决方案和帮助。
* 强大的生态系统:有许多优秀的第三方扩展可以轻松集成。

2. 前置准备

在开始之前,请确保你的系统已安装:

  • Python 3.6+: 可以从 Python 官方网站 下载并安装。
  • pip: Python 包管理工具,通常随 Python 一起安装。

3. 安装 Flask

推荐使用 Python 的虚拟环境来管理项目依赖,这可以避免不同项目之间的依赖冲突。

  1. 创建并激活虚拟环境

    “`bash

    创建虚拟环境

    python -m venv venv

    激活虚拟环境 (Windows)

    .\venv\Scripts\activate

    激活虚拟环境 (macOS/Linux)

    source venv/bin/activate
    “`

  2. 安装 Flask

    bash
    pip install Flask

    安装成功后,你可以通过 pip freeze 命令查看已安装的包。

4. 第一个 Flask 应用:Hello, World!

现在,让我们来创建一个最简单的 Flask 应用。

  1. 创建 app.py 文件

    “`python

    app.py

    from flask import Flask

    app = Flask(name)

    @app.route(‘/’)
    def hello_world():
    return ‘Hello, Flask!’

    if name == ‘main‘:
    app.run(debug=True)
    “`

    代码解释:
    * from flask import Flask: 导入 Flask 类。
    * app = Flask(__name__): 创建一个 Flask 应用实例。__name__ 是当前模块的名称,Flask 用它来确定应用的根目录,以便查找资源文件(如模板和静态文件)。
    * @app.route('/'): 这是一个装饰器,它将 hello_world 函数绑定到 URL 根路径 /。当用户访问这个 URL 时,hello_world 函数将被执行。
    * def hello_world():: 定义一个视图函数,它返回一个字符串作为响应体。
    * if __name__ == '__main__':: 确保只有在直接运行此文件时才执行 app.run()
    * app.run(debug=True): 启动 Flask 开发服务器。debug=True 会在代码修改后自动重载服务器,并在发生错误时提供详细的调试信息。

  2. 运行应用

    bash
    python app.py

    你会在控制台看到类似以下输出:

    * Serving Flask app 'app'
    * Debug mode: on
    WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
    * Running on http://127.0.0.1:5000
    Press CTRL+C to quit
    * Restarting with stat
    * Debugger is active!
    * Debugger PIN: XXX-XXX-XXX

    在浏览器中访问 http://127.0.0.1:5000,你将看到 “Hello, Flask!”。

5. 路由(Routing)

路由定义了 URL 如何映射到你的视图函数。

5.1 基本路由

你可以创建多个路由:

“`python

app.py (继续上面的代码)

@app.route(‘/about’)
def about():
return ‘这是关于页面。’

@app.route(‘/contact’)
def contact():
return ‘联系我们:[email protected]
“`

访问 http://127.0.0.1:5000/abouthttp://127.0.0.1:5000/contact 查看效果。

5.2 变量规则

你可以在 URL 中添加变量部分,并将其作为参数传递给视图函数。

“`python

app.py

@app.route(‘/user/‘)
def show_user_profile(username):
# show the user profile for that user
return f’用户: {username}’

@app.route(‘/post/‘)
def show_post(post_id):
# show the post with the given id, the id is an integer
return f’文章 ID: {post_id}’
“`

变量转换器:
* <string:name> (默认): 接受任何不包含斜杠的文本。
* <int:name>: 接受整数。
* <float:name>: 接受浮点数。
* <path:name>: 接受包含斜杠的文本,可以匹配整个路径。
* <uuid:name>: 接受 UUID 字符串。

6. 模板(Templates)

在 Web 开发中,通常需要生成动态 HTML 页面。Flask 使用 Jinja2 模板引擎来实现这一点。

  1. 创建 templates 文件夹
    app.py 同级目录下创建一个名为 templates 的文件夹。Flask 会自动在这个文件夹中寻找模板文件。

  2. 创建模板文件 (index.html)
    templates 文件夹中创建一个 index.html 文件。

    html
    <!-- templates/index.html -->
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的 Flask 应用</title>
    </head>
    <body>
    <h1>欢迎, {{ name }}!</h1>
    <p>这是一个 Flask 模板示例。</p>
    </body>
    </html>

    Jinja2 语法:
    * {{ name }}: 用于显示变量的值。
    * {% ... %}: 用于控制语句,如 iffor 循环等。

  3. 修改 app.py 使用模板

    “`python

    app.py

    from flask import Flask, render_template

    app = Flask(name)

    @app.route(‘/’)
    def index():
    user_name = “访客”
    return render_template(‘index.html’, name=user_name) # 传递变量给模板

    … 其他路由 …

    if name == ‘main‘:
    app.run(debug=True)
    “`

    现在访问 http://127.0.0.1:5000,你将看到一个由 index.html 渲染的页面,并且 {{ name }} 会被替换为 “访客”。

6.1 模板继承

模板继承是 Jinja2 的一个强大功能,允许你创建基础模板,并在其他模板中继承它,避免重复代码。

  1. 创建 base.html (基础模板)

    html
    <!-- templates/base.html -->
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}我的 Flask 应用{% endblock %}</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    </head>
    <body>
    <nav>
    <a href="/">首页</a>
    <a href="/about">关于</a>
    <a href="/contact">联系</a>
    </nav>
    <hr>
    <div class="content">
    {% block content %}{% endblock %}
    </div>
    <footer>
    <p>&copy; 2025 Flask 实践</p>
    </footer>
    </body>
    </html>

    • {% block title %}{% block content %}: 定义了子模板可以覆盖的区域。
    • url_for('static', filename='style.css'): 用于生成静态文件的 URL。
  2. 修改 index.html 继承 base.html

    “`html

    {% extends ‘base.html’ %}

    {% block title %}首页 – 我的 Flask 应用{% endblock %}

    {% block content %}

    欢迎, {{ name }}!

    这是一个 Flask 模板继承示例。

    {% endblock %}
    “`

    现在,index.html 只需关注其特定内容,而页面的整体结构由 base.html 提供。

7. 静态文件(Static Files)

Web 应用通常需要 CSS、JavaScript 和图片等静态文件。Flask 默认会在应用根目录下的 static 文件夹中查找这些文件。

  1. 创建 static 文件夹和 style.css 文件
    app.py 同级目录下创建 static 文件夹,并在其中创建 style.css

    css
    /* static/style.css */
    body {
    font-family: Arial, sans-serif;
    margin: 20px;
    background-color: #f4f4f4;
    color: #333;
    }
    nav {
    background-color: #333;
    padding: 10px;
    }
    nav a {
    color: white;
    padding: 8px 15px;
    text-decoration: none;
    margin-right: 10px;
    }
    nav a:hover {
    background-color: #575757;
    }
    .content {
    background-color: white;
    padding: 20px;
    margin-top: 20px;
    border-radius: 5px;
    }
    footer {
    text-align: center;
    margin-top: 30px;
    color: #666;
    }

  2. 在模板中引用静态文件
    base.html 中,我们已经使用了 {{ url_for('static', filename='style.css') }} 来引用 style.css

    重启应用并访问 http://127.0.0.1:5000,你应该能看到页面应用了 CSS 样式。

8. 实践:一个简单的待办事项应用

让我们构建一个简单的待办事项列表应用,它允许用户添加和查看待办事项。

我们将使用一个简单的列表来模拟数据库存储。

  1. 修改 app.py

    “`python
    from flask import Flask, render_template, request, redirect, url_for, flash

    app = Flask(name)
    app.secret_key = ‘your_secret_key_here’ # 用于 session 和 flash 消息,生产环境请使用复杂密钥

    todos = [] # 模拟数据库存储

    @app.route(‘/’)
    def index():
    return render_template(‘todo_list.html’, todos=todos)

    @app.route(‘/add’, methods=[‘POST’])
    def add_todo():
    if request.method == ‘POST’:
    task = request.form.get(‘task’)
    if task:
    todos.append({‘id’: len(todos) + 1, ‘task’: task, ‘done’: False})
    flash(‘待办事项添加成功!’, ‘success’)
    else:
    flash(‘待办事项不能为空。’, ‘error’)
    return redirect(url_for(‘index’))

    @app.route(‘/complete/‘)
    def complete_todo(todo_id):
    for todo in todos:
    if todo[‘id’] == todo_id:
    todo[‘done’] = not todo[‘done’] # 切换完成状态
    flash(f”待办事项 ‘{todo[‘task’]}’ 状态已更新!”, ‘info’)
    break
    return redirect(url_for(‘index’))

    @app.route(‘/delete/‘)
    def delete_todo(todo_id):
    global todos
    todos = [todo for todo in todos if todo[‘id’] != todo_id]
    flash(‘待办事项已删除!’, ‘warning’)
    return redirect(url_for(‘index’))

    if name == ‘main‘:
    app.run(debug=True)
    “`

    新引入的知识点:
    * request: 全局对象,用于访问传入的请求数据(如表单数据、查询参数)。
    * request.method: 请求方法(GET, POST 等)。
    * request.form.get('task'): 获取 POST 请求中表单字段 task 的值。
    * redirect(url_for('index')): 重定向到名为 index 的视图函数对应的 URL。url_for 是一个非常重要的函数,它根据视图函数的名称生成 URL,避免了硬编码 URL。
    * flash(): 用于在不同请求之间传递一次性消息(如成功/失败提示)。需要设置 app.secret_key
    * app.secret_key: Flask 用于保护会话数据和闪现消息的加密密钥。

  2. 创建 todo_list.html 模板
    templates 文件夹中创建 todo_list.html

    “`html

    {% extends ‘base.html’ %}

    {% block title %}我的待办事项 – Flask 应用{% endblock %}

    {% block content %}

    我的待办事项

    {# 显示闪现消息 #}
    {% with messages = get_flashed_messages(with_categories=true) %}
        {% if messages %}
            <ul class="flashes">
                {% for category, message in messages %}
                    <li class="{{ category }}">{{ message }}</li>
                {% endfor %}
            </ul>
        {% endif %}
    {% endwith %}
    
    <form action="{{ url_for('add_todo') }}" method="post">
        <input type="text" name="task" placeholder="添加新待办事项" required>
        <button type="submit">添加</button>
    </form>
    
    <hr>
    
    {% if todos %}
        <ul>
            {% for todo in todos %}
                <li style="text-decoration: {% if todo.done %}line-through{% else %}none{% endif %};">
                    {{ todo.task }}
                    <a href="{{ url_for('complete_todo', todo_id=todo.id) }}">
                        {% if todo.done %}未完成{% else %}完成{% endif %}
                    </a>
                    <a href="{{ url_for('delete_todo', todo_id=todo.id) }}" style="color: red;">删除</a>
                </li>
            {% endfor %}
        </ul>
    {% else %}
        <p>暂无待办事项。快来添加一个吧!</p>
    {% endif %}
    

    {% endblock %}
    “`

    模板中的新知识点:
    * get_flashed_messages(with_categories=true): 在模板中获取闪现消息。
    * url_for('add_todo'): 生成 add_todo 视图函数的 URL。
    * Jinja2 iffor 循环:用于条件渲染和遍历列表。

  3. 更新 static/style.css (可选,美化闪现消息)

    css
    /* static/style.css (追加) */
    .flashes {
    list-style: none;
    padding: 0;
    }
    .flashes li {
    margin-bottom: 5px;
    padding: 10px;
    border-radius: 3px;
    }
    .flashes .success {
    background-color: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
    }
    .flashes .error {
    background-color: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
    }
    .flashes .info {
    background-color: #d1ecf1;
    color: #0c5460;
    border: 1px solid #bee5eb;
    }
    .flashes .warning {
    background-color: #fff3cd;
    color: #856404;
    border: 1px solid #ffeeba;
    }

    运行 python app.py,你现在可以添加、标记完成和删除待办事项了!

9. 总结与展望

通过本教程,你已经掌握了 Flask 的核心概念,包括:

  • Flask 应用的创建与运行
  • 路由的定义与变量规则
  • 使用 Jinja2 模板引擎渲染动态页面
  • 模板继承与静态文件的使用
  • 处理表单提交、重定向和闪现消息

这仅仅是 Flask 的入门。未来你可以继续学习:

  • 数据库集成:使用 SQLAlchemy (ORM) 或其他数据库库。
  • 蓝图 (Blueprints):组织大型应用。
  • 表单验证:使用 Flask-WTF。
  • 用户认证与授权
  • 部署 Flask 应用
  • RESTful API 开发

Flask 的生态系统非常丰富,提供了许多优秀的扩展来帮助你构建更强大的应用。祝你在 Flask 的世界中探索愉快!

滚动至顶部