I have a function in Django that uses the youtube API to return the video_id, title and thumbnail_url based on the web_url that is provided by the user through the user create Video object form. The reason I did this was to make it easy for users to upload youtube videos to my app.
def get_video_info(pk): print('get_video_info called') video = Video.objects.get(id=pk) web_url = video.web_url # Parse the video ID from the URL parsed_url = urlparse(web_url) query_params = parse_qs(parsed_url.query) video_id = query_params["v"][0] # Create a YouTube Data API client api_key = settings.YOUTUBE_API_KEY youtube = build('youtube', 'v3', developerKey=api_key) # Call the YouTube API to get the video details video_response = youtube.videos().list( part='id, snippet', id=video_id, maxResults=1 ).execute() # Extract the video details from the API response video_snippet = video_response['items'][0]['snippet'] thumbnail_url = video_snippet['thumbnails']['medium']['url'] title = video_snippet['title'] return {'video_id': video_id,'thumbnail_url': thumbnail_url,'title': title, }I then have a signal function that triggers the get_video_info function when a Video object is created and then updates the Video fields with the return values of the function.
@receiver(post_save, sender=Video)def create_video_info(sender, instance, created, **kwargs): print('create signal called') if created: # if the instance is being created video_id, thumbnail_url, title = get_video_info(instance.pk).values() instance.video_id = video_id instance.thumbnail_url = thumbnail_url instance.title = title instance.save()my problem is that when i tried to create a similar signal for when the video object is being updated I was getting an infinite recursion loop. Any ideas on how to solve this issue would be much appreciated, thanks!
This is the previous signal i tried:
@receiver([post_save, post_delete], sender=Video)def update_video_info(sender, instance, **kwargs): print('update signal called') if hasattr(instance, 'pk') and instance.pk: video_id, thumbnail_url, title = get_video_info(instance.pk).values() instance.video_id = video_id instance.thumbnail_url = thumbnail_url instance.title = title instance.save()