如何在变量改变值之前保存它的值

2024-10-02 20:30:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在建立一个关于本地加密市场的新网站,希望通过价格的变化来控制当前“要价”的颜色。你知道吗

我使用请求从市场提供的API获取数据集。在django中,我通过一个新字典将数据传递给模板。你知道吗

你知道吗视图.py文件

from django.shortcuts import render
import requests

def index(request):
   url = 'https://koineks.com/ticker'
   r = requests.get(url).json()
   koineks_index = {
    'fiyatBTC' : r['BTC']['ask'],
    'fiyatETH' : r['ETH']['ask'],
    'fiyatXRP' : r['XRP']['ask'],
    'fiyatBCH' : r['BCH']['ask'],
    'fiyatUSDT' : r['USDT']['ask'],
   }
   context = {'koineks_index' : koineks_index}
   return render(request, 'calc/calc.html', context)

html文件

<html>
<body>
        <p>
        BTC buy price: <span style="color:green">{{koineks_index.fiyatBTC}}</span> (₺)
        ETH.buy: <span style="color:green">{{koineks_index.fiyatETH}}</span> (₺)
        XRP.buy: <span style="color:green">{{koineks_index.fiyatXRP}}</span> (₺)
        USDT.buy: <span style="color:green">{{koineks_index.fiyatUSDT}}</span> (₺)
        BCH.buy: <span style="color:green">{{koineks_index.fiyatBCH}}</span> (₺)
        </p>
</body>
</html>

如何在更新价格以用于将更改当前价格的文本颜色的If/else语句之前保存价格。你知道吗

我希望它是绿色的,如果更新的价格更高,红色的,如果更新的价格低于旧的价格。你知道吗

谢谢你的帮助!你知道吗


Tags: 文件djangoimportindex市场style颜色html
2条回答

我要做的是:

  1. 将价格存储在带有时间戳的数据库中(该时间戳将用于知道哪些记录是最新的,也可用于找出“旧”价格)

  2. 将API请求移动到自定义管理命令(该命令还将负责将结果写入数据库),并设置cron作业,以便每隔X个时间段执行此命令(取决于价格变化的速度和您希望的准确性)。这将避免对每个请求都使用API—大多数API都有速率限制,如果在给定的时间内发送太多请求,就会踢你一脚,而且db查询通常比HTTP请求快得多。

  3. 在你看来,提供数据库中的价格。通过检测更改,您可以直接与数据库存储的前一批(具有较旧时间戳的批)进行比较,也可以将当前批时间戳存储在会话中并与这些值进行比较,这取决于对您最有意义的内容(或者您可以将两者混合使用:如果会话中没有时间戳,则使用第一种解决方案,第二个(如果有的话)。

FWIW,将价格保持在本地也可以显示一段时间内的价格演变。。。这可能比一个红/绿旗更能提供信息。你知道吗

以下是解决方案

from django.shortcuts import render
import requests

def index(request):
   url = 'https://koineks.com/ticker'
   r = requests.get(url).json()

   previous_prices = request.session.get('previous_prices', [0, 0, 0, 0, 0])

   koineks_index = {
    'fiyatBTC' : r['BTC']['ask'],
    'fiyatETH' : r['ETH']['ask'],
    'fiyatXRP' : r['XRP']['ask'],
    'fiyatBCH' : r['BCH']['ask'],
    'fiyatUSDT' : r['USDT']['ask'],
   }

   colors = ['green' if x else 'red' for x in map(lambda price: float(koineks_index[price[0]]) >= float(price[1]), zip(koineks_index, previous_prices))]

   request.session['previous_prices'] = [koineks_index[key] for key in koineks_index]

   context = {'koineks_index' : koineks_index, 'colors': colors}

   return render(request, 'price/calc.html', context)

模板

<html>
<body>
        <p>
        BTC buy price: <span style="color:{{colors.0}}">{{koineks_index.fiyatBTC}}</span> (₺)
        ETH.buy: <span style="color:{{colors.1}}">{{koineks_index.fiyatETH}}</span> (₺)
        XRP.buy: <span style="color:{{colors.2}}">{{koineks_index.fiyatXRP}}</span> (₺)
        USDT.buy: <span style="color:{{colors.3}}">{{koineks_index.fiyatUSDT}}</span> (₺)
        BCH.buy: <span style="color:{{colors.4}}">{{koineks_index.fiyatBCH}}</span> (₺)
        </p>
</body>
</html>

相关问题 更多 >