YouTube API视频上传错误:parseError / w python

时间:2013-10-10 16:04:08

标签: python youtube youtube-api

Google的YouTube数据API的示例代码是一块垃圾。它太复杂了,并且与oauth重定向流有关,我无法使用它。尝试使用requests点进行原始操作并且不要太过分。

我完全按照instructions(据我所知),使用以下代码:

import json
import os
import sys
import urllib

import requests

payload_file = None
payload = None

print 'Loading Config'

# Get the directory path of this file.  When using any relative file paths make
# sure they are relative to current_dir so that the script can be run from any CWD.
current_dir = os.path.dirname(os.path.abspath(__file__))

# Reads in the config.json file then parses it
config = json.loads(open(os.path.join(current_dir, '..', 'config.json')).read())

print 'Parsing Payload'

for i in range(len(sys.argv)):

    if sys.argv[i] == "--json" and (i + 1) < len(sys.argv):
        payload = json.loads(sys.argv[i + 1])

    elif sys.argv[i] == "-payload" and (i + 1) < len(sys.argv):
        payload_file = sys.argv[i + 1]
        with open(payload_file,'r') as f:
            payload = json.loads(f.read())
        break


print 'Configuring youtube with token {0}'.format(payload['token'])



print 'Downloading video...'

# See how big it is
f = urllib.urlopen(payload['url'])
content_length = int(f.headers["Content-Length"])

# Download it
# urllib.urlretrieve(payload['url'], "video.mp4")

metadata = {
    'snippet' : {
        'title': payload['title'],
        "categoryId": 22
    },
    'status' : {
        "privacyStatus": "public",
        "embeddable": True,
        "license": "youtube"
    }
}

if 'tags' in payload:
    metadata['snippet']['tags'] = payload['tags']

if 'description' in payload:
    metadata['snippet']['description'] = payload['description']


headers = {
    'Authorization' : 'Bearer {0}'.format(payload['token']),
    'Content-Type' : 'application/json; charset=UTF-8',
    'Content-Length' : json.dumps(metadata).__len__(),
    'X-Upload-Content-Length' : content_length,
    'X-Upload-Content-Type' : 'video/*',
}

print 'Attempting to upload video'

print headers

# upload video file
r = requests.post('https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=snippet,status', data=metadata, headers=headers);

print "RESPONSE!"
print r.text

# files = {
#     'file': video_file,
# }
# r = requests.post('https://www.googleapis.com/upload/youtube/v3/videos', data={ "video" : video }, headers=headers);

显然它没有完成,但它在元数据上传请求中死亡,输出如下:

Loading Config
Parsing Payload
Configuring youtube with token <access-token>
Downloading video...
Attempting to upload video
{'X-Upload-Content-Length': 51998563, 'Content-Length': 578, 'Content-Type': 'application/json; charset=UTF-8', 'X-Upload-Content-Type': 'video/*', 'Authorization': 'Bearer <access-token>'}
RESPONSE!
{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "parseError",
    "message": "Parse Error"
   }
  ],
  "code": 400,
  "message": "Parse Error"
 }
}

此错误甚至未列在"Errors" docs

我的代码出了什么问题?

2 个答案:

答案 0 :(得分:2)

这是python中的一个例子。它假设你已经完成了oauth部分。

import requests
from os import fstat
import json

fi = open('myvideo.mp4')

base_headers = {
    'Authorization': '%s %s' % (auth_data['token_type'],
                                auth_data['access_token']),
    'content-type': 'application/json'
}

initial_headers = base_headers.copy()
initial_headers.update({
    'x-upload-content-length': fstat(fi.fileno()).st_size,
    'x-upload-content-type': 'video/mp4'
})
initial_resp = requests.post(
    'https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=snippet,status,contentDetails',
    headers=initial_headers,
    data=json.dumps({
        'snippet': {
            'title': 'my title',
        },
        'status': {
            'privacyStatus': 'unlisted',
            'embeddable': True
        }
    })
)
upload_url = initial_resp.headers['location']
resp = requests.put(
    upload_url,
    headers=base_headers,
    data=fi
)
fi.close()

答案 1 :(得分:0)

以上内容非常棒,只需添加:您还可以从响应中获取youtube id(以备将来使用):

cont = json.loads(resp.content)
youtube_id = cont['id']