0
Follow
0
View

Update global variable in an asychrounouus way in Django

dongxie1 注册会员
2023-01-25 08:00

I would do two things:

  1. I would use

    /v1/exchangerate/USD?invert=true
    

    to get rates for all tickers in one request

    (doc: https://docs.api.io/?python#get-all-current-rates-get)

    and later I would filter needed tickers. And it would works even if I change list of tickers

  2. I would use requests-cache to get results from cache, and make real request only every 15 minutes - so it should give 100 requests a day


Minimal working code

import os
import requests
import requests_cache
from datetime import timedelta

# --- constants ---  # PEP8: `UPPER_CASE_NAMES` for constants

API_KEY = os.getenv('COINAPI_TOKEN')

# --- session: cache and API key ---

s = requests_cache.CachedSession(expire_after=timedelta(minutes=15))
#s.cache.clear()  # manually clear cache

s.headers.update({'X-CoinAPI-Key': API_KEY})

# --- every rate separatelly ---

url = 'https://rest.coinapi.io/v1/exchangerate/{}/USD'

tickers = ["BTC", "ETC", "ETH", "RVN"]

prices = {coin: s.get(url.format(coin)).json()['rate']
            for coin in tickers}

context = {"cryptoPrices": prices}

print(context["cryptoPrices"])

# --- all rates ---

url = 'https://rest.coinapi.io/v1/exchangerate/USD?invert=True'

response = s.get(url)
data = response.json()

# filter data

tickers = ["BTC", "ETH", "ETC", "RVN"]

prices = {}

for item in data['rates']:
    if item['asset_id_quote'] in tickers:
        key = item['asset_id_quote']
        val = item['rate']
        prices[key] = val

context = {"cryptoPrices": prices}

print(context["cryptoPrices"])

About the Author

Question Info

Publish Time
2023-01-25 08:00
Update Time
2023-01-25 08:00