1

I was wondering what the correct way is to save a number in Django SQLite coming from a Kraken API, when there is an Array of Array of strings or integers (https://docs.kraken.com/rest/#operation/getOHLCData).

my views.py

from rest_framework import generics
from .serializers import KrakenSerializer
from krakenohlc.models import Krak
import requests

class KrakenList(generics.RetrieveAPIView):
    serializer_class = KrakenSerializer
    queryset = Krak.objects.all()

    def get_object(request):
        url = 'https://api.kraken.com/0/public/OHLC?pair=XBTEUR'
        response = requests.get(url)
        data = response.json()

        for i in data['result'].values():  
            kraken_data = Krak(
                time_0=(i[0][0]),
            )
            kraken_data.save()

my models.py

from django.db import models
class Krak(models.Model):
    time_0 = models.IntegerField(blank=True, null=True)

    def __str__(self):
        return self.time_0

This is the error that i get in the browser: enter image description here

The SQLite response is actually saving the API number in the database: enter image description here

I researched and tried thoroughly many similar cases here, but none had the example of an API response with this error message.

David
  • 97
  • 7

1 Answers1

1

I think the issue is the with the last item in the "result" array of arrays - "last". It seems like it's just a number. I guess you need some type checking in the algorithm. enter image description here

Suggestion for code modification:

for i in data['result'].values():
  # Skips "last" attribute
  if isinstance(i, int):
    continue
  kraken_data = Krak(
    time_0=(i[0][0]),
  )
  kraken_data.save()
vinkomlacic
  • 1,822
  • 1
  • 9
  • 19
  • This comment is helpful but did not solve the problem. As i am testing this call just with the first index time_0=i[0][0], in fact the last item is not generating an error yet. Any other thoughts? – David Feb 28 '22 at 22:52
  • The indexes are irrelevant. Code `time_0=i[0]` would not also execute because `i` at some point is `1616662920` (in the example) and you cannot subscript that. I will edit the answer – vinkomlacic Feb 28 '22 at 23:02
  • I would like to ask for help in case you or someone has any suggestion for a solution to this problem. – David Mar 01 '22 at 07:07
  • Have you tried the suggestion in the answer? What happened? – vinkomlacic Mar 01 '22 at 12:47
  • I applied your solution and it worked perfectly now. This is solved, thanks. – David Mar 01 '22 at 14:11