Feeds:
文章
留言

Archive for 九月 24th, 2012

最近工作上要瞭解 Youtube SDK 如何上傳影片

找到一個 Python 範例 youtbue-upload

我的環境

使用 python setup.py install 可分別安裝 python-gdata 和 youtube-upload

youtube_upload 安裝路徑 C:\Python27\Lib\site-packages\youtube_upload

測試

python youtube_upload.py –email=你的gmail帳號 –password=你的密碼 –title="test" –description="test desc" –category=Music  d:\ring.avi

登入

youtube = Youtube(DEVELOPER_KEY)
youtube.login(email, password)

上述程式實際上是 YouTubeService class 的封裝, 實際上就是

service = gdata.youtube.service.YouTubeService()
service.developer_key = DEVELOPER_KEY
service.client_id = ‘tokland-youtube_upload’
service.source = ‘tokland-youtube_upload’
service.ssl = False
service.email = email
service.password = password
service.ProgrammaticLogin(None, None)

取得 token ~ 一切的關鍵

media_group = gdata.media.Group(
title=gdata.media.Title(text=’test‘),
description=gdata.media.Description(description_type=’plain’, text=‘test desc‘),
keywords=gdata.media.Keywords(text=None),
category=gdata.media.Category(
text=’Music‘,
label=’Music‘,
scheme=’http://gdata.youtube.com/schemas/2007/categories.cat’),
private=None,
player=None)

video_entry = gdata.youtube.YouTubeVideoEntry(media=media_group, geo=None, extension_elements=None)

post_url, token = service.GetFormUploadToken(video_entry)

上傳檔案(gdata)

實際  YouTubeService  運作就是

entry = service.InsertVideoEntry(video_entry, ‘d:\\ring.avi’)
url = entry.GetHtmlLink().href.replace(“&feature=youtube_gdata", “")
print url

上傳檔案(curl)

c = pycurl.Curl()
c.setopt(c.URL, post_url + “?nexturl=http://code.google.com/p/youtube-upload")
c.setopt(c.HTTPPOST, [(‘token’, token),(‘file’,(pycurl.FORM_FILE, ‘d:\\ring.mp3’))])
c.setopt(pycurl.SSL_VERIFYPEER, 0)
c.setopt(pycurl.SSL_VERIFYHOST, 0)
body_container = StringIO.StringIO()
headers_container = StringIO.StringIO()
c.setopt(c.WRITEFUNCTION, body_container.write)
c.setopt(c.HEADERFUNCTION, headers_container.write)
c.perform()
http_code = c.getinfo(pycurl.HTTP_CODE)
c.close()
headers = dict([s.strip() for s in line.split(“:", 1)] for line in
headers_container.getvalue().splitlines() if “:" in line)
body = body_container.getvalue()
params = dict(s.split(“=", 1) for s in headers[“Location"].split(“?", 1)[1].split(“&"))
video_id = params[“id"]
url = “http://www.youtube.com/watch?v=%s" % video_id

Read Full Post »