Django/Heroku – Handling ObjectDoesNotExist Exception When Pushing Data from API to Django Database

  Kiến thức lập trình

My django application receives data from an API.

It’s very unlikely the API will send incorrect information, but I am trying to cover the possibility the API may send data that would return ObjectDoesNotExist from malicious attempts.

Below is my try at how I could handle the exception, by leaving the data 2 tries. After that, I want it to stop pushing the data.

I left a few print statement to track the tries are being executed. But none of them are getting printed. This makes me think that the data received from the API is considered as valid (because it exists) and its only when the data is pushed to the database that the application realises it does not exist.

Any suggestion on how I could handle this? (I am hoping I am clear)

the function:

def API_data(request):
    userprofile_id = request.GET.get('userprofile_id', '')

    venue_id = request.GET.get('venue_id', '')

    user = UserProfile.objects.get(id=userprofile_id)

    venue = Venue.objects.get(id=venue_id)

    venue_loyalty_point_rule = VenueLoyaltyPointRule.objects.get(venue=venue)

    scans = ItemisedLoyaltyCard.objects.filter(
        user_id=user.id, venue=venue)

    is_point_valid = loyalty_card_validation_rule(
        scans, user, venue, venue_loyalty_point_rule)

    if is_point_valid:
        try_count = 0
        max_retries = 2  # Define the maximum number of retries
        while try_count < max_retries:
            try:
                ItemisedLoyaltyCard.objects.create(
                    user_id=user.id, venue=venue, add_points=venue_loyalty_point_rule.points)
                # If creation succeeds, set data and break the loop
                data = {'points': venue_loyalty_point_rule.points, 'user': user.id, 'venue': venue.name,
                        'success': is_point_valid, 'frequency_rule': venue_loyalty_point_rule.frequency}
                break
            except ObjectDoesNotExist: <!-- This part is not showing getting printed-->
                try_count += 1
                print("Retrying...")
        else:
            # If max retries exceeded, set error message in data
            print("Max retries exceeded. Unable to create loyalty card entry.")
            data = {'error': 'Max retries exceeded. Unable to create loyalty card entry.'}
    else:
        print("Invalid loyalty card validation rule.")
        data = {'error': 'Invalid loyalty card validation rule.'}


    return HttpResponse(json.dumps(data), content_type="application/json")

LEAVE A COMMENT