如何在Django框架内以HTML导入或调用PY代码

时间:2019-02-01 18:12:29

标签: python html django python-3.x html5

我编写了一个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文件中调用此数据,以便可以在网络应用程序上显示它。

2 个答案:

答案 0 :(得分:0)

这真的取决于Web应用程序,你有。

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

我也建议您在功能上的结果你真正得到的,不重复的硬编码数的号码移到这个代码和迭代。

答案 1 :(得分:0)

我先给你一些东西。将其放在一个类中,该类将返回一个填充有数据的字典(也可以是一个普通函数)

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,但要在view函数之外。

因此可以将数据更新限制为每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%