【发布时间】:2020-09-14 22:10:37
【问题描述】:
我正在按照https://www.youtube.com/watch?v=wwAwG-SEaRM 的指南使用 Python 将图像上传到 Google 相册,但我遇到了这个错误:我几乎可以发誓它第一次工作,但我不能确定:
"发生异常: ConnectionError
HTTPSConnectionPool(host='photoslibrary', port=443): url: /googleapis.com/v1/uploads 超过最大重试次数(由 NewConnectionError('
我正在执行的 python 中的代码来自 MAIN.py:
import os
import requests
import pandas as pd
import pickle
import requests
from googlescript import Create_Service
dir_path = os.path.dirname(os.path.realpath(__file__))
API_NAME = 'photoslibrary'
API_VERSION = 'v1'
CLIENT_SECRET_FILE = dir_path + "\\" + "fotomonimaton.json"
print(CLIENT_SECRET_FILE)
SCOPES = ['https://www.googleapis.com/auth/photoslibrary',
'https://www.googleapis.com/auth/photoslibrary.sharing']
service = Create_Service(CLIENT_SECRET_FILE,API_NAME, API_VERSION, SCOPES)
# LIST ALBUMS, WORKS OK
#######################
#print(service.albums().list().execute())
# UPLOAD IMAGE - FAILS
#######################
image_dir = os.path.join(os.getcwd(),'images')
upload_url='https://photoslibrary/googleapis.com/v1/uploads'
token = pickle.load(open('token_photoslibrary_v1.pickle','rb'))
headers= {
'Authorization':'Bearer '+ token.token,
'Content-type':'application/octet-stream',
'X-Goog-Upload-Protocol':'raw',
'X-Goog-Upload-File-Name': "totoro name.jpg"
}
filename = 'totoro.jpg'
image_file = os.path.join(image_dir,filename)
img = open(image_file,'rb').read()
##############
# FAILS HERE #
##############
response = requests.post(upload_url, data=img, headers = headers)
# it does not even reach this line, as it fails before
# Upload the image
request_body ={
'newMediaItems':
[
{
'description': filename,
'simpleMediaItem':
{
'uploadToken': response.content.decode('utf-8')
}
}
]
}
upload_response = service.mediaItems().batchCreate(body=request_body).execute()
... 包含 CreateService(...) 的 googlescript.py 是这样的:
import pickle
import os
import datetime
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import Flow, InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
def Create_Service(client_secret_file, api_name, api_version, *scopes):
print(client_secret_file, api_name, api_version, scopes, sep='-')
CLIENT_SECRET_FILE = client_secret_file
API_SERVICE_NAME = api_name
API_VERSION = api_version
SCOPES = [scope for scope in scopes[0]]
cred = None
pickle_file = f'token_{API_SERVICE_NAME}_{API_VERSION}.pickle'
if os.path.exists(pickle_file):
with open(pickle_file, 'rb') as token:
cred = pickle.load(token)
if not cred or not cred.valid:
if cred and cred.expired and cred.refresh_token:
cred.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRET_FILE, SCOPES)
cred = flow.run_local_server()
with open(pickle_file, 'wb') as token:
pickle.dump(cred, token)
try:
service = build(API_SERVICE_NAME, API_VERSION, credentials=cred)
print(API_SERVICE_NAME, 'service created successfully')
return service
except Exception as e:
print(e)
return None
def convert_to_RFC_datetime(year=1900, month=1, day=1, hour=0, minute=0):
dt = datetime.datetime(year, month, day, hour, minute, 0).isoformat() + 'Z'
return dt
代码成功初始化服务,获取身份验证令牌和图像没有问题,但调用“response = requests.post(upload_url, data=img, headers = headers)”失败,出现该异常。
我正在仔细检查代码,但找不到问题所在...
提前致谢,
罗杰
【问题讨论】:
标签: python rest google-photos-api