我在Django中有一个函数,它使用youtube API根据用户通过用户创建视频对象表单提供的web_url返回video_id,title和thumbnail_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,
}
然后我有一个信号函数,它在创建Video对象时触发get_video_info函数,然后用函数的返回值更新Video字段。
@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()
我的问题是,当我试图创建一个类似的信号,当视频对象正在更新,我得到了一个无限递归循环。2任何想法,如何解决这个问题将不胜感激,谢谢!
这是我之前尝试的信号:
@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()
1条答案
按热度按时间gev0vcfq1#
您可以使用保存()方法的update_fields参数来指定哪些字段已经更改并且需要更新。