我正在尝试使用新的Google Photos API上传照片(jpg图片)。 我可以获取uploadToken,但是当我尝试创建媒体项目时,出现以下错误:
{
"newMediaItemResults": [
{
"uploadToken": "CAIS+QIAkor2Yr4JcvYMMx..... ",
"status": {
"code": 3,
"message": "NOT_IMAGE: There was an error while trying to create this media item."
}
}
]
}
这是我的代码的片段:
import sys
import json
import requests
pic = 'image.jpg'
fname = 'read_write_token_creds.json'
with open(fname) as f:
data = json.load(f)
tok = data['access_token']
# Step 1 get an upload token
URL = 'https://photoslibrary.googleapis.com/v1/uploads'
headers = {
'Content-type': 'application/octet-stream',
'X-Goog-Upload-File-Name': pic,
'X-Goog-Upload-Protocol': 'raw',
'Authorization': 'Bearer ' + tok,
}
files = {'file': open(pic, 'rb')}
r = requests.post(URL, headers=headers, files=files)
upload_token = r.text
# Step 2
album_id = 'AG.....7u'
URL = 'https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate'
header = {
'Content-type': 'application/json',
'Authorization': 'Bearer ' + tok
}
payload = {
'albumId': album_id,
'newMediaItems': [
{
'description': 'Desc.',
'simpleMediaItem': { 'uploadToken': upload_token }
}
]
}
r = requests.post(URL, headers=header, data=json.dumps(payload))
当我从请求模块查看r.text时,我收到错误消息,该错误消息位于他的消息顶部。
答案 0 :(得分:1)
这对我有用。
如何验证用户身份,请参见此处https://developers.google.com/photos/library/guides/upload-media
def upload(service, file):
f = open(file, 'rb').read();
url = 'https://photoslibrary.googleapis.com/v1/uploads'
headers = {
'Authorization': "Bearer " + service._http.request.credentials.access_token,
'Content-Type': 'application/octet-stream',
'X-Goog-Upload-File-Name': file,
'X-Goog-Upload-Protocol': "raw",
}
r = requests.post(url, data=f, headers=headers)
print '\nUpload token: %s' % r.content
return r.content
def createItem(service, upload_token, albumId):
url = 'https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate'
body = {
'newMediaItems' : [
{
"description": "test upload",
"simpleMediaItem": {
"uploadToken": upload_token
}
}
]
}
if albumId is not None:
body['albumId'] = albumId;
bodySerialized = json.dumps(body);
headers = {
'Authorization': "Bearer " + service._http.request.credentials.access_token,
'Content-Type': 'application/json',
}
r = requests.post(url, data=bodySerialized, headers=headers)
print '\nCreate item response: %s' % r.content
return r.content;
//authenticate user and build service
upload_token = upload(service, './path_to_image.png')
response = createItem(service,upload_token, album['id'])