Youtube视频持续时间到Django模型

时间:2015-03-09 11:02:34

标签: python django video youtube

从youtube视频获取信息并保存到数据库的最简单方法是什么?

例如,我想从youtube视频中获取持续时间

我的模特:

class Video(models.Model):

    video_id = models.CharField(max_length=150)
    title = models.CharField(max_length=150)
    slug = AutoSlugField(populate_from="title")
    description = models.TextField(blank=True)
    #duration = models.CharField(max_length=10 , default=video_duration)
    views = models.PositiveIntegerField(default=0)
    likes = models.PositiveIntegerField(default=0)
    category = models.ForeignKey("VideoCategory")
    tags = models.ManyToManyField("Tag")
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    """
    My idea:

    def get_video_duration():

        xml = "http://gdata.youtube.com/feeds/api/videos/" + video_id
        open xml
        parse
        s = take duration from xml in seconds

        import datetime

        video_duration = str(datetime.timedelta(seconds=s)) in h:m:s

    """


    def __str__(self):

        return self.title

有人能帮助我吗?

提前谢谢

编辑:

感谢您的回答,所以我尝试了使用json的方法,但是我得到了错误video_duration没有定义

class Video(models.Model):

video_id = models.CharField(max_length=150)
title = models.CharField(max_length=150)
slug = AutoSlugField(populate_from="title")
description = models.TextField(blank=True)
duration = models.CharField(max_length=10, default=video_duration)
views = models.PositiveIntegerField(default=0)
likes = models.PositiveIntegerField(default=0)
category = models.ForeignKey("VideoCategory")
tags = models.ManyToManyField("Tag")
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)

def video_duration():

    h = httplib2.Http()
    url = "http://gdata.youtube.com/feeds/api/videos/%sv=2&alt=json" % video_id
    respose = h.request(url)
    res = json.loads(respose[1])
    video_duration = res['entry']['media$group'][
        'media$content'][0]['duration']
    return video_duration

1 个答案:

答案 0 :(得分:0)

从youtube获取视频的持续时间非常简单。您只需要分析api调用的响应。 我是用httplib2做的。

最好使用json而不是xml

请求网址中的

videoID是youtube视频的ID

  import httplib2
  import json

  h = httplib2.Http()
  respose = h.request("http://gdata.youtube.com/feeds/api/videos/videoID?v=2&alt=json")
  res = json.loads(respose[1])
  duration = res['entry']['media$group']['media$content'][0]['duration']