Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么可以';我是否可以从python(使用python的REST的GooglePhotosAPI)上传到GooglePhotos?_Python_Rest_Google Photos Api - Fatal编程技术网

为什么可以';我是否可以从python(使用python的REST的GooglePhotosAPI)上传到GooglePhotos?

为什么可以';我是否可以从python(使用python的REST的GooglePhotosAPI)上传到GooglePhotos?,python,rest,google-photos-api,Python,Rest,Google Photos Api,我按照上的指南使用Python将图像上传到Google Photos,但我遇到了一个错误:我几乎可以发誓它第一次就成功了,但我不能确定: “发生异常:ConnectionError HTTPSConnectionPool(host='photoslibrary',port=443):url:/googleapis.com/v1/uploads超过了最大重试次数(由NewConnectionError引起(':未能建立新连接:[Errno 11001]getaddrinfo Failed')) 文

我按照上的指南使用Python将图像上传到Google Photos,但我遇到了一个错误:我几乎可以发誓它第一次就成功了,但我不能确定:

发生异常:ConnectionError HTTPSConnectionPool(host='photoslibrary',port=443):url:/googleapis.com/v1/uploads超过了最大重试次数(由NewConnectionError引起(':未能建立新连接:[Errno 11001]getaddrinfo Failed')) 文件“…MAIN.py”,第49行,在 response=requests.post(上传url,数据=img,标题=headers)”

我正在执行的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()
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
。。。包含CreateService(…)的googlescript.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()
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\u url,data=img,headers=headers)”失败,但出现该异常

我正在仔细检查代码,但我找不到问题出在哪里

事先非常感谢


罗杰,行动!这是一个很小的打字错误:

https://photoslibrary/googleapis.com/v1/uploads

应该是


现在我可以确认它工作了…

操作!这是一个很小的打字错误:

https://photoslibrary/googleapis.com/v1/uploads

应该是

现在我可以确认它的工作