【问题标题】:How to import or call PY code in HTML within django framework如何在 django 框架中导入或调用 HTML 中的 PY 代码
【发布时间】:2025-12-03 13:05:02
【问题描述】:

我编写了一个 py 文件,它使用两个 API 来检索有关当前加密趋势的数据。我正在尝试在我的 Web 应用程序中显示的 HTML 文件中导入或调用检索到的数据。

我尝试使用 {{% %}} 调用 py 文件,但不确定我是否做对了。

import requests

url_usd = 'https://api.coingecko.com/api/v3/coins/markets?                    
vs_currency=usd&order=market_cap_desc&per_page=250&page=1' \
         '&sparkline=false&price_change_percentage=24h'

url_gbp = 'https://api.coingecko.com/api/v3/coins/markets? 
vs_currency=gbp&order=market_cap_desc&per_page=250&page=1' \
      '&sparkline=false&price_change_percentage=24h '

requests1 = requests.get(url_usd)
results1 = requests1.json()

requests2 = requests.get(url_gbp)
results2 = requests2.json()

for i in range(0, 250):
    coin_id = results1[i]['id']
    coin_name = results1[i]['name']
    changes = results1[i]['price_change_percentage_24h']
    usd = results1[i]['current_price']
    gbp = results2[i]['current_price']

    print("Coin ID: " + coin_id)
    print("Coin name: " + coin_name)
    print("Price per coin in USD: " + "$" + "{:.2f}".format(float(usd)))
    print("Price per coin in GBP: " + "£" + "{:.2f}".format(float(gbp)))
    print("Percentage price change: " + "{:.2f}".format(changes) + "%")
    print()

输出:

Coin ID: bitcoin
Coin name: Bitcoin
Price per coin in USD: $3461.54
Price per coin in GBP: £2645.04
Percentage price change: 0.82%

Coin ID: ripple
Coin name: XRP
Price per coin in USD: $0.31
Price per coin in GBP: £0.23
Percentage price change: -0.60%

接下来的 250 个硬币以此类推

我现在想从一个 html 文件中调用这些数据,以便它可以显示在网络应用程序上。

【问题讨论】:

标签: python django python-3.x html


【解决方案1】:

我会给你一些开始的东西;把它放在一个类中,它返回一个填充了数据的字典(也可以是一个普通函数)

import requests

class CryptoData:
    def __init__(self):
        self.usd_url = "https://api.coingecko.com/api/v3/coins/markets?" \
                       "vs_currency=usd&order=market_cap_desc&per_page=250&page=1" \
                       "&sparkline=false&price_change_percentage=24h"
        self.gbp_url = "https://api.coingecko.com/api/v3/coins/markets?" \
                       "vs_currency=gbp&order=market_cap_desc&per_page=250&page=1" \
                       "&sparkline=false&price_change_percentage=24h"


    def get_crypto_data_dict(self, get_it=False):
        crypto_dict = dict()
        requests1 = requests.get(self.usd_url)
        results1 = requests1.json()

        requests2 = requests.get(self.gbp_url)
        results2 = requests2.json()



        for i in range(0, 250):
            crypto_dict[results1[i]['id']] = {
                'coin_name': results1[i]['name'],
                'changes': results1[i]['price_change_percentage_24h'],
                'usd': results1[i]['current_price'],
                'gbp': results2[i]['current_price']
            }


        return crypto_dict

然后在视图中:

def crypt_view(request):
    crypto_data = CryptoData()

    context = {
        'crypto_data': crypto_data.get_crypto_data_dict()
    }

    return render(request, 'crypto/crypto.html', context=context)

然后在crypto.html中(这只是一个例子):

<ul>
     {% for crypto_datum, crypto_value in crypto_data.items %}
        <li>{{ crypto_datum }}
            <ul>

                {% for info, value in crypto_value.items %}
                    <li>{{ info }}: {{ value }}</li>
                {% endfor %}


            </ul>

        </li>
     {% endfor %}

</ul>

这有一个问题,每当有人触摸该网页时,您都会自动向 coingecko 发送一个获取请求。这可能是速率限制的问题

所以你可以在views.py中实例化你的CryptoData,但在你的视图函数之外。

因此,可以将数据更新限制为每 60 秒的更好实现是这样的:

import requests, time
from django.shortcuts import render

class CryptoData:
    def __init__(self):
        self.usd_url = "https://api.coingecko.com/api/v3/coins/markets?" \
                       "vs_currency=usd&order=market_cap_desc&per_page=250&page=1" \
                       "&sparkline=false&price_change_percentage=24h"
        self.gbp_url = "https://api.coingecko.com/api/v3/coins/markets?" \
                       "vs_currency=gbp&order=market_cap_desc&per_page=250&page=1" \
                       "&sparkline=false&price_change_percentage=24h"

        self.previous_request = None
        self.crypto_dict = dict()


    def get_crypto_data_dict(self, seconds_to_wait=60):

        if not self.previous_request or self.previous_request+seconds_to_wait < time.time():
            print("requested", self.previous_request, time.time())
            self.previous_request = time.time()
            crypto_dict = dict()
            requests1 = requests.get(self.usd_url)
            results1 = requests1.json()

            requests2 = requests.get(self.gbp_url)
            results2 = requests2.json()

            for i in range(0, 250):
                self.crypto_dict[results1[i]['id']] = {
                    'coin_name': results1[i]['name'],
                    'changes': results1[i]['price_change_percentage_24h'],
                    'usd': results1[i]['current_price'],
                    'gbp': results2[i]['current_price']
                }

        return self.crypto_dict


crypto_data = CryptoData()

def crypt_view(request):

    context = {
        'crypto_data': crypto_data.get_crypto_data_dict()
    }

    return render(request, 'crypto/crypto.html', context=context)

使用此实现,coingecko api 仅每 60 秒调用一次

编辑:以同样的方式显示它,你可以这样做:

{% for crypto_datum, crypto_values in crypto_data.items %}
    <div>
    <p>Coin ID: {{ crypto_datum }}<br>
        Coin Name: {{ crypto_datum|capfirst }}<br>
        Price per coin in USD: ${{ crypto_values.usd|floatformat:2 }}<br>
        Price Per coin in GBP: £{{ crypto_values.gbp|floatformat:2 }}<br>
        Percentage price change: {{ crypto_values.changes|floatformat:2 }}%
    </p>
    </div>
{% endfor %}

这看起来像这样:

Coin ID: bitcoin
Coin Name: Bitcoin
Price per coin in USD: $3466.24
Price Per coin in GBP: £2657.72
Percentage price change: 0.16%

Coin ID: ripple
Coin Name: Ripple
Price per coin in USD: $0.30
Price Per coin in GBP: £0.23
Percentage price change: -0.85%

Coin ID: ethereum
Coin Name: Ethereum
Price per coin in USD: $107.27
Price Per coin in GBP: £82.25
Percentage price change: -0.11%

【讨论】:

  • 谢谢你,但你能告诉我如何格式化数据以便像以前一样显示吗?例如,为了显示价格,我添加了“每枚硬币的美元价格:”+“$”+“{:.2f}”.format(float 这是为了显示 $ 和 £ 符号
【解决方案2】:

这实际上取决于您拥有的网络应用程序。

按照 Griehle 的建议,最简单的方法是使用烧瓶。这是一个非常简单的框架。

我还建议您将此代码移动到一个函数中并迭代您实际获得的结果数量,而不是硬编码的迭代次数。

【讨论】: