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

如何将CoinMarketCap API调用结果渲染到HTML页面进行展示

实现API数据传递到HTML页面的修改方案

1. 调整main.py的cryptoLookup函数,增加返回逻辑

原函数仅将结果打印到控制台,需要改为返回数据供视图层调用:

from requests import Request, Session
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
import json

def cryptoLookup(coin):
    url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/info'
    parameters = {
        'slug': coin
    }
    headers = {
        'Accepts': 'application/json',
        'X-CMC_PRO_API_KEY': '你的实际API密钥', # 此处填写你申请的CMC接口密钥
    }

    session = Session()
    session.headers.update(headers)

    try:
        response = session.get(url, params=parameters)
        data = json.loads(response.text)
        # 新增返回数据
        return data
    except (ConnectionError, Timeout, TooManyRedirects) as e:
        # 异常时返回错误信息
        return {"error": f"接口请求失败:{str(e)}"}

2. 修改views.py视图函数,将数据注入模板上下文

在视图中接收cryptoLookup返回的结果,通过render方法的第三个参数传递给HTML模板:

def coin(request):
    coin_data = None
    if request.method == 'POST':
        coin = request.POST.get('coin-lookup')
        coin_data = cryptoLookup(coin)
    # 将数据放入上下文传递给模板
    return render(request, 'app/coin.html', {"coin_data": coin_data})

3. 编写coin.html模板,渲染返回数据

使用Django模板语法读取上下文传递的coin_data,根据接口返回的字段展示对应信息,示例代码如下:

<!DOCTYPE html>
<html>
<head>
    <title>加密货币查询结果</title>
</head>
<body>
    <h1>查询结果</h1>
    {% if coin_data %}
        {% if coin_data.error %}
            <p style="color: red;">{{ coin_data.error }}</p>
        {% elif coin_data.status.error_code != 0 %}
            <p style="color: red;">接口返回错误:{{ coin_data.status.error_message }}</p>
        {% else %}
            {% for coin_id, info in coin_data.data.items %}
                <div style="border: 1px solid #ccc; padding: 15px; margin: 10px 0;">
                    <h2>{{ info.name }} ({{ info.symbol }})</h2>
                    <p><strong>官网:</strong>{% if info.urls.website %}{{ info.urls.website.0 }}{% else %}无{% endif %}</p>
                    <p><strong>描述:</strong>{{ info.description|default:"无描述信息" }}</p>
                    <p><strong>发行日期:</strong>{{ info.date_launched|default:"未公开" }}</p>
                </div>
            {% endfor %}
        {% endif %}
    {% else %}
        <p>请先在首页输入加密货币名称进行查询</p>
    {% endif %}
    <a href="{% url 'home' %}">返回查询页</a>
</body>
</html>

注:接口返回字段可根据实际需求调整展示内容,以上仅为基础示例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 14:48:02