Flask视图函数:从返回HTML到动态数据

在Flask中,视图函数是处理用户请求并返回响应的核心组件。它就像一个“桥梁”,连接用户的访问和页面内容的生成。从最简单的“Hello World”到动态展示数据,视图函数的能力非常灵活。下面我们一步步探索视图函数的用法。

一、视图函数的“初体验”:返回简单内容

当用户访问某个URL时,Flask会自动调用对应的视图函数。最简单的视图函数可以直接返回字符串,Flask会自动将其转换为HTML响应。

from flask import Flask

app = Flask(__name__)  # 创建Flask应用实例

# 定义根路由(访问http://localhost:5000/时触发)
@app.route('/')
def index():
    return "Hello, Flask!"  # 返回字符串,Flask自动转为HTML

if __name__ == '__main__':
    app.run(debug=True)  # 启动应用,debug=True开启调试模式

运行代码后,访问根目录会看到“Hello, Flask!”的文字,这就是视图函数返回的结果。

二、返回静态HTML:用模板渲染页面

直接返回字符串适合简单内容,但复杂HTML(如包含标题、列表等)更适合用模板管理。Flask通过render_template函数加载HTML模板文件,需要在项目中创建templates文件夹存放模板。

步骤1:创建模板文件
在项目根目录下新建templates文件夹,创建index.html

<!-- templates/index.html -->
<!DOCTYPE html>
<html>
<head>
    <title>我的第一个页面</title>
</head>
<body>
    <h1>欢迎来到Flask世界!</h1>
    <p>这是一个静态HTML页面。</p>
</body>
</html>

步骤2:视图函数渲染模板
修改视图函数,用render_template加载模板:

from flask import Flask, render_template  # 导入render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')  # 加载templates文件夹中的index.html

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

此时访问根目录,页面会显示模板中的静态HTML内容。

三、动态数据:让页面“活”起来

模板不仅能显示静态内容,还能通过视图函数传递动态数据。Flask结合Jinja2模板引擎支持变量、循环、条件判断等功能,让页面内容随数据变化。

1. 模板变量:从视图函数传递数据

视图函数可以通过参数向模板传递动态内容,模板中用{{ 变量名 }}渲染。

示例:显示当前时间
修改视图函数,获取当前时间并传递给模板:

from datetime import datetime  # 导入时间模块

@app.route('/time')
def show_time():
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")  # 格式化时间
    return render_template('time.html', current_time=current_time)  # 传递变量

模板文件(templates/time.html)

<!DOCTYPE html>
<html>
<head>
    <title>当前时间</title>
</head>
<body>
    <h1>当前时间:{{ current_time }}</h1>  <!-- 渲染变量 -->
</body>
</html>

访问/time会显示实时更新的时间。

2. 循环与条件:动态展示列表数据

通过Jinja2的{% for %}{% if %}标签,可以动态生成列表或条件内容。

示例:动态文章列表
视图函数提供文章数据,模板用循环展示:

@app.route('/articles')
def articles():
    # 模拟文章数据(列表包含多个字典)
    article_list = [
        {'id': 1, 'title': 'Flask入门教程', 'author': '小明'},
        {'id': 2, 'title': 'Python基础', 'author': '小红'},
        {'id': 3, 'title': '数据分析实战', 'author': '小明'}
    ]
    return render_template('articles.html', articles=article_list)  # 传递列表

模板文件(templates/articles.html)

<!DOCTYPE html>
<html>
<head>
    <title>文章列表</title>
</head>
<body>
    <h1>我的文章</h1>
    <ul>
        {% for article in articles %}  <!-- 循环遍历文章列表 -->
            <li>
                <h3>{{ article.title }}</h3>  <!-- 渲染文章标题 -->
                <p>作者:{{ article.author }}</p>
            </li>
        {% endfor %}
    </ul>
</body>
</html>

访问/articles会看到动态生成的文章列表,每条文章内容随数据变化。

3. URL参数:根据用户输入动态响应

视图函数可以通过路由参数接收用户输入的URL内容,实现个性化响应。

示例:用户个人页面
路由中定义参数<user_id>,视图函数接收参数并返回内容:

@app.route('/profile/<user_id>')  # URL中的<user_id>为动态参数
def profile(user_id):
    return f"用户ID:{user_id},这是用户的个人主页"

访问/profile/123会显示“用户ID:123,这是用户的个人主页”。

4. 请求参数:处理用户表单输入

通过request对象获取用户通过URL参数或表单提交的数据,实现搜索、筛选等功能。

示例:搜索功能
获取URL参数中的关键词,动态返回搜索结果:

from flask import request  # 导入request模块

@app.route('/search')
def search():
    keyword = request.args.get('keyword', default='')  # 获取URL参数中的keyword
    return f"搜索结果:找到与“{keyword}”相关的内容..."

访问/search?keyword=Flask会显示“搜索结果:找到与“Flask”相关的内容…”。

四、综合示例:动态博客列表

结合前面的知识点,我们做一个简单的博客列表页面,支持按作者搜索和动态展示文章。

项目结构

myblog/
├── app.py
└── templates/
    └── blog.html

app.py代码

from flask import Flask, render_template, request

app = Flask(__name__)

# 模拟文章数据
articles = [
    {'id': 1, 'title': 'Flask基础', 'author': '小明', 'date': '2023-01-01'},
    {'id': 2, 'title': 'Python爬虫', 'author': '小红', 'date': '2023-01-02'},
    {'id': 3, 'title': 'Flask进阶', 'author': '小明', 'date': '2023-01-03'}
]

@app.route('/blog')
def blog():
    # 获取URL参数中的作者(默认为空)
    author = request.args.get('author', default='')
    # 根据作者筛选文章
    filtered_articles = [a for a in articles if a['author'] == author] if author else articles
    return render_template('blog.html', articles=filtered_articles, author=author)

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

模板文件(templates/blog.html)

<!DOCTYPE html>
<html>
<head>
    <title>博客列表</title>
</head>
<body>
    <h1>博客列表</h1>
    <!-- 搜索表单 -->
    <form method="get" action="/blog">
        <input type="text" name="author" placeholder="输入作者名搜索" value="{{ author }}">
        <input type="submit" value="搜索">
    </form>
    <!-- 文章列表 -->
    <ul>
        {% for article in articles %}
            <li>
                <h3>{{ article.title }}</h3>
                <p>作者:{{ article.author }} | 日期:{{ article.date }}</p>
            </li>
        {% endfor %}
    </ul>
</body>
</html>

访问/blog可看到所有文章,输入作者名(如“小明”)点击搜索,会动态筛选出对应作者的文章。

总结

视图函数是Flask的核心,通过它可以实现从简单静态页面到复杂动态数据的展示。关键能力包括:
1. 返回内容:字符串(自动转HTML)或模板渲染;
2. 动态数据:通过Jinja2模板变量、循环、条件展示内容;
3. 参数处理:URL参数和请求参数实现个性化响应。

掌握视图函数后,你可以快速构建交互性强的Web应用,后续学习数据库、用户认证等功能时,视图函数仍是核心基础。

小夜