我在 Django 中有一个函数,它使用 youtube API 根据用户通过用户创建视频对象表单提供的 web_url 返回 video_id、标题和缩略图 url。我这样做的原因是为了方便用户将 youtube 视频上传到我的应用程序。
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,
}
然后我有一个信号函数,它在创建视频对象时触发 get_video_info 函数,然后使用该函数的返回值更新视频字段。
@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()
我的问题是,当我尝试为视频对象更新时创建类似的信号时,我得到了一个无限递归循环。任何关于如何解决这个问题的想法将不胜感激,谢谢!
这是我之前试过的信号:
@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()
@receiver(post_save, sender=Video)
def update_video_info(sender, instance, created, update_fields, **kwargs):
if not created and 'web_url' in update_fields:
print('update signal called')
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(update_fields=['video_id', 'thumbnail_url', 'title'])
您可以使用 save() 方法的 update_fields 参数来指定哪些字段已更改并且应该需要更新。