5

我正在尝试使用新的 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))

当我从 requests 模块查看 r.text 时,我收到了消息顶部给出的错误消息。

4

1 回答 1

4

这对我有用。

如何对用户进行身份验证,请参见此处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'])
于 2018-08-25T22:23:57.013 回答