You need to enable JavaScript to run this app. Flask无数据库场景下如何实现第三方API返回数据的分页功能
优惠活动
大模型
产品
解决方案
定价
更多

Flask无数据库场景下如何实现第三方API返回数据的分页功能

实现方案

你调用的Pixabay开放API本身原生支持分页参数,无需适配数据库分页能力,仅需将API返回的分页元数据透传至前端模板,动态渲染分页控件即可,修改如下:

1. 视图函数修改

from flask import Flask, render_template, request
import requests
import math

app = Flask(__name__)

api = '12589634-45tg33ww8633f1cdfrre3345'
url = 'https://pixabay.com/api/'

@app.route("/", methods=['POST', 'GET'])
def homePage():
    per_page = 18
    # Pixabay API页码从1开始,默认值改为1
    page = request.args.get('page', 1, type=int)
    query = request.args.get('s', 'cats')
    
    payload = {'key': api, 'q': query, 'per_page': per_page, 'page': page}
    # 增加异常捕获避免API调用失败报错
    try:
        response = requests.get(url, params=payload, timeout=10)
        data = response.json()
        images = data.get('hits', [])
        total_hits = data.get('totalHits', 0)
        # 计算总页数
        total_pages = math.ceil(total_hits / per_page)
    except:
        images = []
        total_pages = 1

    # 将分页相关参数传给模板
    return render_template('home_page.html', 
                          images=images,
                          current_page=page,
                          total_pages=total_pages,
                          query=query)

2. 模板修改

{% extends 'base.html' %}

{% block content %}
    <div class="columns is-multiline is-mobile">
        {% for image in images %}
        <div class="column is-full-mobile is-half-tablet is-one-third-desktop">
            <div class="card">
                <div class="card-image">
                    <figure class="image is-4by3">
                        <img src="{{image.webformatURL}}" alt="{{image.tags}}">
                    </figure>
                </div>
                <div class="card-content">
                    <div class="media">
                        <div class="media-left">
                            <figure class="image is-48x48">
                                {% if image.userImageURL %}
                                <img src="{{image.userImageURL}}" alt="{{image.user}}">
                                {% else %}
                                <img src="{{url_for('static', filename='images/avatar/avatar.png')}}" alt="no user image">
                                {% endif %}
                            </figure>
                        </div>
                        <div class="media-content">
                            <p class="title is-5">Uploaded by</p>
                            <p class="subtitle is-6">@{{image.user}}</p>
                        </div>
                    </div>
                    <div class="content">
                        <p class="title is-6">Likes: {{image.likes}}</p>
                        <p class="title is-6">Type: {{image.type}}</p>
                        <p class="title is-6">Views: {{image.views}}</p>
                        <a href="{{image.largeImageURL}}" class="button is-dark is-fullwidth" target="_blank"
                            rel="noopener nofollow">View
                            full</a>
                    </div>
                </div>
            </div>
        </div>
        {% else %}
        <div class="column is-full">
            <p class="has-text-centered">暂无匹配结果</p>
        </div>
        {% endfor %}
    </div>
    <!-- 仅总页数大于1时显示分页控件 -->
    {% if total_pages > 1 %}
    <nav class="pagination" role="navigation" aria-label="pagination">
        <a class="pagination-previous" 
           {% if current_page <= 1 %}disabled{% endif %}
           href="{{ url_for('homePage', page=current_page-1, s=query) }}">
            Previous
        </a>
        <a class="pagination-next"
           {% if current_page >= total_pages %}disabled{% endif %}
           href="{{ url_for('homePage', page=current_page+1, s=query) }}">
            Next page
        </a>
        <ul class="pagination-list">
            <!-- 显示当前页前后2个页码,避免页码过多 -->
            {% set start_page = [1, current_page - 2]|max %}
            {% set end_page = [total_pages, current_page + 2]|min %}
            {% for p in range(start_page, end_page + 1) %}
            <li>
                <a class="pagination-link {% if p == current_page %}is-current{% endif %}" 
                   aria-label="Page {{p}}"
                   {% if p == current_page %}aria-current="page"{% endif %}
                   href="{{ url_for('homePage', page=p, s=query) }}">
                    {{p}}
                </a>
            </li>
            {% endfor %}
        </ul>
    </nav>
    {% endif %}
{% endblock content %}

注意事项

  • 原代码中页码默认值设为0不符合Pixabay API规范,已修正为1
  • 新增了API调用异常捕获逻辑,避免服务出错
  • 分页跳转时保留了搜索参数s,切换页码不会丢失搜索条件
  • 新增了无结果时的提示文案

内容的提问来源于stack exchange,提问作者Isidro Gonzalez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 02:18:03