from .models import GtinProduct from django.db.models import ObjectDoesNotExist import requests import logging LOGGER = logging.getLogger(__name__) def ask_upcitemdb_service(gtin): request = f'https://api.upcitemdb.com/prod/trial/lookup?upc={gtin}' response = requests.get(request) if response.status_code == 200: productJson = response.json() print(f"Got {productJson['total']} result records") if productJson['total'] > 0: product = GtinProduct.objects.create(gtin=gtin, api_request=request, api_response=productJson) if 'title' in productJson['items'][0]: product.name = productJson['items'][0]['title'] if 'brand' in productJson['items'][0]: product.brand = productJson['items'][0]['brand'] LOGGER.debug( f"Creating new product entry for gtin={gtin}:\nrequest={request}\nresponse={response.status_code}:{productJson}") product.save() return product return None def ask_remote_services(gtin): product = ask_upcitemdb_service(gtin) if product is not None: return product return None def get_by_gtin(gtin): try: product = GtinProduct.objects.get(gtin=gtin) except ObjectDoesNotExist: # ask remote services product = ask_remote_services(gtin) return product