簡體   English   中英

如何在Django框架內以HTML導入或調用PY代碼

[英]How to import or call PY code in HTML within django framework

我編寫了一個py文件,該文件使用兩個API檢索有關當前加密趨勢的數據。 我試圖導入或調用HTML文件中檢索到的數據,但確實顯示在我的Web應用程序中。

我嘗試使用{{%%}}來調用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文件中調用此數據,以便可以在Web應用程序上顯示它。

這實際上取決於您擁有的Web應用程序。

最簡單的方法是按照Griehle的建議,使用燒瓶。 這是一個非常簡單的框架。

我還建議您在函數中移動此代碼,並遍歷實際獲得的結果數,而不是硬編碼的迭代數。

我給你一些開始。 將其放在一個類中,該類返回一個用數據填充的字典(也可以是一個普通函數)

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中,但在view函數之外,實例化您的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)

在此實現中,僅每60秒調用一次coingecko API

編輯:以相同的方式顯示它,您可以執行以下操作:

{% 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%

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM