首页 > 解决方案 > 使用 For 循环将照片上传到 Google 相册

问题描述

我正在使用 Google Photos API 将超过 200 万张图片上传到我的 Google 帐户。目标是编写一个 for 循环来遍历目录中的所有图像并将它们上传到谷歌照片。for 循环在一段时间内可以正常工作,但最终会停止工作。这是代码:

    i=0
    k=0
    tokens = []
    upload_url = 'https://photoslibrary.googleapis.com/v1/uploads'
    service = Service(API_SERVICE_NAME, VERSION, SCOPES, SECRET_ID=cred)

    for file in files:
        if file.endswith(".JPG" ) or file.endswith(".jpg" ):            
            i = i + 1               
            token = pickle.load(open('token_photoslibrary_v1.pickle', 'rb'))                    
            image_path = os.path.join(image_dir, file)
            # response = upload_images(image_path, file, token)
            headers = {
                'Authorization': 'Bearer ' + token.token,
                'Content-type': 'application/octet-stream',
                'X-Goog-Upload-Protocol': 'raw',
                'X-Goog-File-Name': file,
                'X-Goog-Upload-File-Name': view+file
            }
            img = open(image_path, 'rb').read()
            response = requests.post(upload_url, data=img, headers=headers)    
            tokens.append(response.content.decode('utf-8'))  
            
        if i%50==0 and i>0: #call every 50
            k = k + 1  
            print(f'{k} batch is uploading')
            new_media_items = [{'simpleMediaItem': {'uploadToken': tok}} for tok in tokens]
            request_body = {
                'newMediaItems': new_media_items
            }
            upload_response = service.mediaItems().batchCreate(body=request_body).execute()    
            tokens = []

错误是:

<HttpError 400 when requesting https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate?alt=json returned "Request must contain a valid upload token.". Details: "Request must contain a valid upload token.">

我的帐户已激活 Google One,我有 2T 空间。

标签: pythongoogle-cloud-platformgoogle-apigoogle-photos

解决方案


推荐阅读