How did a json go to a dictionary?

2

Good afternoon dear stackoverflow friends I have this code in which I get from an api to get bitcoin results in real time I have two questions:

  • How can I make that json save instead of a list to a dictionary with the name values and their value in USD.

  • How can I make the code update every 5 seconds to have change values in real time.

  • Here is the code Thank you!

    import requests, time, threading, csv, os
    
    class Bitcoin_Api():
       def Taking_Values():
            bitcoin = "https://api.coinmarketcap.com/v1/ticker/bitcoin" 
            ethereum = "https://api.coinmarketcap.com/v1/ticker/ethereum" 
            litecoin = "https://api.coinmarketcap.com/v1/ticker/litecoin" 
            bit = requests.get(bitcoin).json()
            ethe = requests.get(ethereum).json()
            lite = requests.get(litecoin).json()
            print(bit)
            return crypto
    
    print (Bitcoin_Api.Taking_Values())
    
        
    asked by Tysaic 09.08.2018 в 03:08
    source

    3 answers

    2

    Several things, I've found reading API documentation :

    • The most recent API is the v2 , you are calling the v1 .
    • In v2 coins are identified by a% co_of numeric% instead of a name. For example, in the case of bitcoin it would be id . This does return a dictionary instead of a list (although the structure of the dictionary it returns is different from that of v1, see the documentation)
    • The list of ids and their correspondences with the names you get from /v2/ticker/1
    • The api v2 will no longer be accessible to the public in December 2018. They urge you to switch to using their professional API, which requires you to register and pay according to the use you make. There is a free plan for low number of queries.

    And in regards to your intention to obtain data in real time, you have limits:

    • No more than 30 requests per minute (since you do 3 of each time, for 3 cryptocurrencies, you can do that 10 times in a minute, that is, every 6 seconds)
    • But ... the data updates only every 5 minutes, so it does not make sense that you make requests more often than that. Surely your payment plan updates more frequently.

    To make a request every 5 minutes, it is enough that you put everything in an infinite loop and that you sleep 5 minutes between iterations.

    The following code implements the functionality that you request, based on the API v2 explained above. I have organized the code in functions and it is quite commented. Ask if you have questions.

    import requests
    import time, datetime
    
    base_url = "https://api.coinmarketcap.com/v2"
    
    def obtener_lista_monedas():
        """
        Devuelve un diccionario en el que las claves son los nombres de las
        monedas y los valores son los correspondientes ids.
    
        Si el servicio no está accesible devuelve None
        """
        r = requests.get("{}/listings".format(base_url))
        if not r.ok:
            print("Error en la petición de la lista: {}".format(r.reason))
            return None
        data = r.json()["data"]
        diccionario = {}
        for moneda in data:
            nombre = moneda["name"].lower()
            id = moneda["id"]
            diccionario[nombre] = id
        return diccionario
    
    def obtener_moneda(id):
        """
        Recibe el id de una moneda cuyo cambio se desea conocer.
    
        Devuelve un diccionario con un solo elemento, siendo la clave
        el nombre de la moneda y el valor su cambio a USD.
    
        Si el servicio no está accesible devuelve un diccionario en
        el que tanto la clave como el valor son None
        """
        r = requests.get("{}/ticker/{}".format(base_url, id))
        if not r.ok:
            print("Error en la petición de la divisa {}: {}".format(id, r.reason))
            return { None: None }
        data = r.json()["data"]
        nombre = data["name"]
        cambio = data["quotes"]["USD"]["price"]
        return { nombre: cambio }
    
    def obtener_monedas(lista_ids):
        """
        Recibe una lista de ids de monedas.
    
        Devuelve un diccionario con tantos elementos como monedas, siendo
        la clave el nombre de la moneda y el valor su cambio a USD.
        """
        resultado = {}
        for id in lista_ids:
            resultado.update(obtener_moneda(id))
        return resultado
    
    
    ## Programa principal
    
    if __name__ == "__main__":
        # Obtener el diccionario para traducir nombres en ids
        todas_monedas = obtener_lista_monedas()
        if not todas_monedas:
            print("No se puede continuar")
            quit()
    
        # Crear la lista de ids de las monedas que nos interesan
        monedas = ["bitcoin", "ethereum", "litecoin"]
        ids = [ todas_monedas[m]  for m in monedas ]
    
        # Cada 5 minutos obtener el cambio y mostrarlo, junto con la hora actual
        while True:
            print("{} -> {}".format(datetime.datetime.now(),
                                    obtener_monedas(ids)))
            time.sleep(5*60)
    

    Example of what you see on screen:

    2018-08-09 11:29:57.047021 -> {'Bitcoin': 6351.59583444, 'Ethereum': 361.646762689, 'Litecoin': 62.2959021488}
    
        
    answered by 09.08.2018 / 11:00
    source
    0

    In your specific case you can do this:

    bit = requests.get(bitcoin).json()[0]
    ethe = requests.get(ethereum).json()[0]
    lite = requests.get(litecoin).json()[0]
    type(bit)
    >>> <class 'dict'>
    

    If you include it in a loop with a:

    time.sleep(5)
    

    I think you would have what you need. A tip, be careful not to start rejecting your connections. When many requests are made in a row, they can take the decision to reject your requests.

        
    answered by 09.08.2018 в 10:44
    0

    If you need to generate a new element (a dictionary for example) from known Json, it may help you create a serializer.

    With a serializer, you can for example validate that a json comes with a certain structure or adapt and take from the json known values and generate a new structure.

    # serializers.py
    from rest_framework import serializers
    
    class MiDataSerializer(serializers.Serializer):
        mi_var1 = serializers.IntegerField(required=True, source='var1')
        mi_var2 = serializers.CharField(default='texto', source='var2')
        mi_var3 = serializers.JSONField(default=None, source='var3')
        mi_var4 = serializers.BooleanField(default=False, source='var4')
    
        # con la linea siguiente puedes obtener una variable con nombre compuesto
        mi_var5 = serializers.CharField(required=True, source='Nombre:raro-ext2:status')
    
        # con la linea siguiente puedes obtener el valor especifico de una variable dentro de otra estructura
        mi_var6 = serializers.CharField(required=False, source='padre.hijo1.hijo2')
    
    
    
    # mi_archivo.py
    from .serializers import MiDataSerializer
    
    ...
    
    data_desde_api = metodo_que_trae_los_datos()
    
    # aqui podrías por ejemplo validar tu data
    if data_desde_api.is_valid():
        pass
    
    # puedes obtener y serializar múltiples registros si la respuesta es un array de objetos
    mi_data = MiDataSerializer(data_desde_api, many=True)
    
    # puedes obtener un sólo registro
    mi_data = MiDataSerializer(data_desde_api)
    
    ...
    

    Suppose that the api returns the next Json

    {
        ...
    
        'var1': 100,
        'var2': 'hola',
        'var4': 1,
        'Nombre:raro-ext2:status': 'a1s2-d34g-g4as-da34',
        'padre': {
            'hijo1': {
                'hijo2': 'valor-123'
            }
        }
    
        ...
    }
    

    Once you have passed through the serializer, you will have your object (dictionary):

    {
        'mi_var1': 100,
        'mi_var2': 'hola',
        'mi_var3': None,
        'mi_var4': 1,
        'mi_var5': 'a1s2-d34g-g4as-da34',
        'mi_var6': 'valor-123'
    }
    

    You can find the documentation here .

    And to execute a code or a detarminated task every X time, you may want to read a little about the use of Rabbit and Celery with python or Django.

        
    answered by 09.08.2018 в 17:23