samedi 1 juin 2019

If statement to fix list index out of range error

I'm setting up a Django views that calls an API and save the data into my database but I keep getting a listindex out of range error everytime the loop hit the last item in the response.

This is what the Traceback looks like:

Internal Server Error: /form/
Traceback (most recent call last):
  File "C:\Users\locq\desktop\coding\uvergo_search\venv\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
    response = get_response(request)
  File "C:\Users\locq\desktop\coding\uvergo_search\venv\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\locq\desktop\coding\uvergo_search\venv\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\locq\Desktop\Coding\UVERGO_SEARCH\venv\src\search\views.py", line 126, in api_data
    descriptiontxt = resp_2_data['contentListHtml'][0]['html'][0:2040] + ' ...'
IndexError: list index out of range

As we can see above, the error is pointing toward line 126:

descriptiontxt = resp_2_data['contentListHtml'][0]['html'][0:2040] + ' ...'

So I'm trying to fix this by adding an If statement to the line in the following Django view:

def api_data(request):
    if request.GET.get('mybtn'):  # to improve, == 'something':
        resp_1 = requests.get(
            "https://www.headout.com/api/public/v1/product/listing/list-by/city?language=fr&cityCode=PARIS&limit=5000&currencyCode=CAD",
            headers={
                "Headout-Auth": HEADOUT_PRODUCTION_API_KEY
            })
        resp_1_data = resp_1.json()
        base_url_2 = "https://www.headout.com/api/public/v1/product/get/"

        translator = Translator()

        for item in resp_1_data['items']:
            print('parsing, translating and saving item {}'.format(item['id']))
            # concat ID to the URL string
            url = '{}{}'.format(base_url_2, item['id'] + '?language=fr')

            # make the HTTP request
            resp_2 = requests.get(
                url,
                headers={
                    "Headout-Auth": HEADOUT_PRODUCTION_API_KEY
                })
            resp_2_data = resp_2.json()

            descriptiontxt = resp_2_data['contentListHtml'][0]['html'][0:2040] + ' ...'

            #Parse
            soup = BeautifulSoup(descriptiontxt, 'lxml')
            parsed = soup.find('p').text

            #Translate
            translation = translator.translate(parsed, dest='fr')

            titlename = item['name']
            titlefr = translator.translate(titlename, dest='fr')

            destinationname = item['city']['name']
            destinationfr = translator.translate(destinationname, dest='fr')

            Product.objects.get_or_create(
                title=titlefr.text,
                destination=destinationfr.text,
                description=translation.text,
                link=item['canonicalUrl'],
                image=item['image']['url']
            )

            time.sleep(2)

    return render(request, "form.html")

But I'm not sure what would be the best way to do it.

Please help!

Aucun commentaire:

Enregistrer un commentaire