You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计外部Django REST Framework API的JSON对象并可视化数量?

解决方案:统计外部DRF API JSON对象数量并可视化

1. 调用外部API并统计数量

首先用requests库请求外部API,解析返回的JSON数据后统计对象数量。需要处理请求异常,避免因API故障导致页面报错。

示例视图代码:

import requests
from django.shortcuts import render

def api_stats_view(request):
    api_url = "https://external-api.example.com/your-endpoint/"  # 替换为目标API地址
    item_count = None
    error_msg = None

    try:
        # 发起请求,设置超时时间避免阻塞
        response = requests.get(api_url, timeout=10)
        response.raise_for_status()  # 捕获HTTP错误(如404、500)
        data = response.json()

        # 根据API返回结构统计数量:
        if isinstance(data, list):
            # 情况1:API直接返回对象列表
            item_count = len(data)
        elif isinstance(data, dict) and "results" in data:
            # 情况2:API返回包含列表的分页结构(如DRF默认分页)
            item_count = len(data["results"])
            # 如果需要统计全部分页数据,需循环请求next链接累加数量
            # next_url = data.get("next")
            # while next_url:
            #     response = requests.get(next_url, timeout=10)
            #     data = response.json()
            #     item_count += len(data["results"])
            #     next_url = data.get("next")
        else:
            item_count = 0  # 其他结构根据实际场景调整

    except requests.exceptions.RequestException as e:
        error_msg = f"API请求失败:{str(e)}"

    # 整理表格展示数据
    table_data = [
        {"统计项": "总对象数量", "数值": item_count if item_count is not None else "无数据"}
    ]

    return render(request, "api_stats.html", {
        "table_data": table_data,
        "error_msg": error_msg
    })

2. 编写HTML模板展示统计结果

在Django模板目录下创建api_stats.html,用表格可视化统计数据:

<!DOCTYPE html>
<html>
<head>
    <title>外部API统计</title>
    <style>
        table { border-collapse: collapse; width: 60%; margin: 30px auto; }
        th, td { border: 1px solid #ccc; padding: 10px; text-align: center; }
        th { background-color: #f5f5f5; }
        .error { color: #dc3545; text-align: center; margin-top: 30px; }
        h1 { text-align: center; color: #333; }
    </style>
</head>
<body>
    <h1>外部API对象数量统计</h1>
    {% if error_msg %}
        <div class="error">{{ error_msg }}</div>
    {% else %}
        <table>
            <thead>
                <tr>
                    <th>统计项目</th>
                    <th>数值</th>
                </tr>
            </thead>
            <tbody>
                {% for item in table_data %}
                <tr>
                    <td>{{ item.统计项 }}</td>
                    <td>{{ item.数值 }}</td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    {% endif %}
</body>
</html>

3. 配置路由

在项目urls.py中添加对应路由:

from django.urls import path
from .views import api_stats_view

urlpatterns = [
    path('api-stats/', api_stats_view, name='api_stats'),
]

关键注意事项

  • 安装依赖:确保已安装requests,执行pip install requests
  • 缓存优化:频繁请求外部API会影响性能,可使用Django缓存装饰器@cache_page(60*15)缓存视图结果(15分钟)
  • API认证:如果目标API需要Token或其他认证,在请求时添加请求头,例如headers={"Authorization": "Token YOUR_API_TOKEN"}
  • 分页处理:若API返回分页数据,需循环请求所有分页链接累加总数(代码中已注释相关逻辑)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 22:32:13