Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/350.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.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 无法从Google Drive下载id为的文件_Python_Python 3.x_Google Drive Api - Fatal编程技术网

Python 无法从Google Drive下载id为的文件

Python 无法从Google Drive下载id为的文件,python,python-3.x,google-drive-api,Python,Python 3.x,Google Drive Api,我可以成功列出共享给我的文件。但是,当我尝试按id下载现有文件时,会出现“未找到文件”错误。如何按id下载文件 列出文件的脚本 $ pip3 list | grep googl google-api-python-client 1.7.9 google-auth 1.6.3 google-auth-httplib2 0.0.3 google-auth-oauthlib 0.4.0 结果 from __future__ imp

我可以成功列出共享给我的文件。但是,当我尝试按id下载现有文件时,会出现“未找到文件”错误。如何按id下载文件

列出文件的脚本

$ pip3 list | grep googl
google-api-python-client 1.7.9    
google-auth              1.6.3    
google-auth-httplib2     0.0.3    
google-auth-oauthlib     0.4.0  
结果

from __future__ import print_function
import pickle
import os.path
import io
import sys
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']
TOKEN_FILE = 'tockenRead.pickle'

def main():
    """Shows basic usage of the Drive v3 API.
    Prints the names and ids of the first 10 files the user has access to.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists(TOKEN_FILE):
        with open(TOKEN_FILE, 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open(TOKEN_FILE, 'wb') as token:
            pickle.dump(creds, token)

    service = build('drive', 'v3', credentials=creds)

    # Call the Drive v3 API
    results = service.files().list(
        q="mimeType != 'application/vnd.google-apps.folder'",
        pageSize=10,
        fields="nextPageToken, files(id, name)"
    ).execute()
    items = results.get('files', [])

    if not items:
        print('No files found.')
    else:
        print('Files:')
        for item in items:
            print(u'{0} ({1})'.format(item['name'], item['id']))

if __name__ == '__main__':
    main()
用于下载id为1SWYM5Z1ZPCZZZNDULMSBA9WREJ JT hwE的文件的脚本

$ python3 list_files.py 
Files:
20140810_125633.mp4 (1SwYm5Z1zPczZnDulmsbA9wrEJ-JT-hwE)
Getting started (0B3K2QXOGSOFRc3RhcnRlcl9maWxl)
错误

$python3下载\u files.py
请访问此URL以授权此应用程序:https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=619229308650-91gkhdgo7v0jbt6df1phahmq868eb7gd.apps.googleusercontent.com&redirect_uri=http%3A%2F%2LocalHost%3A8080%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.file&state=4mP9kgVJQD4ETOu5JjIRQFBLcyViAG&access_type=offline&code_challenge=YBCZMGZOXDRZYN1DQ9NSJK8WMtLo7Deg_Xix9So和代码挑战法=S256
回溯(最近一次呼叫最后一次):
文件“download_files.py”,第52行,在
main()
文件“download_files.py”,第49行,主目录
下载文件(服务“1SWYM5Z1ZPCZZZNDULMSBA9WREJ JT hwE”)
文件“downloadfiles.py”,第21行,在downloadFile中
状态,done=downloader.next_chunk()
位置包装中的文件“/usr/local/lib/python3.7/site packages/googleapiclient/_helpers.py”,第130行
已包装退货(*args,**kwargs)
文件“/usr/local/lib/python3.7/site packages/googleapiclient/http.py”,第705行,在下一块中
引发HttpError(resp,content,uri=self.\u uri)
GoogleAppClient.errors.HttpError:
这个答案怎么样

发行原因: 当我看到您的脚本时,我注意到下面脚本的范围与上面脚本的范围不同。我想这就是你的问题所在

在上面的脚本中,
https://www.googleapis.com/auth/drive.metadata.readonly使用了
。另一方面,在下面的脚本中,
https://www.googleapis.com/auth/drive.file使用了

说明
https://www.googleapis.com/auth/drive.file
如下所示

查看和管理使用此应用打开或创建的Google Drive文件和文件夹

这意味着当脚本使用
https://www.googleapis.com/auth/drive.file
,您可以使用作用域检索文件。但例如,当手动将文件上载到Google Drive时,
https://www.googleapis.com/auth/drive.file
,即使文件与您共享

为了下载该文件,以下解决方法如何

解决方法1: 您使用
https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/drive.readonly
而不是
https://www.googleapis.com/auth/drive.file

解决方法2: 如果要求您使用
https://www.googleapis.com/auth/drive.file
,它使用
https://www.googleapis.com/auth/drive.file
。这样,就可以按作用域下载文件

注:
  • 更改作用域时,请删除
    tokenWrite.pickle
    文件,再次授权作用域并创建新的
    tokenWrite.pickle
    。这样,就可以使用新的作用域。请注意这一点。
参考:

如果我误解了你的问题,而这不是你想要的方向,我道歉。

我的回答是否向你展示了你想要的结果?你能告诉我这件事吗?这对我的学习也很有用。如果这样做有效,其他与你有相同问题的人也可以将你的问题作为可以解决的问题。如果你对我的回答还有疑问,我道歉。那时候,我可以问一下你目前的情况吗?我想通过学习来解决您的问题。谢谢您的回复。
from __future__ import print_function
import pickle
import os.path
import io
import sys
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/drive.file']
TOKEN_FILE = 'tokenWrite.pickle';

def downloadFile(driveService, fileId):
    request = driveService.files().get_media(fileId=fileId)
    fh = io.BytesIO()
    downloader = MediaIoBaseDownload(fh, request)
    done = False
    while done is False:
        status, done = downloader.next_chunk()
        print ("Download %d%%." % int(status.progress() * 100))

def main():
    """Shows basic usage of the Drive v3 API.
    Prints the names and ids of the first 10 files the user has access to.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists(TOKEN_FILE):
        with open(TOKEN_FILE, 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open(TOKEN_FILE, 'wb') as token:
            pickle.dump(creds, token)

    service = build('drive', 'v3', credentials=creds)

    downloadFile(service, '1SwYm5Z1zPczZnDulmsbA9wrEJ-JT-hwE')

if __name__ == '__main__':
    main()
$ python3 download_files.py 
Please visit this URL to authorize this application: https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=619229308650-91gkhdgo7v0jbt6df1phahmq868eb7gd.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.file&state=4mP9kgVJQD4ETOu5JjIRQFBLcyViAG&access_type=offline&code_challenge=ybCzMgZ2SOXdrpZZYn1dq9nSJk8wMtLo7Deg_Xix9So&code_challenge_method=S256
Traceback (most recent call last):
  File "download_files.py", line 52, in <module>
    main()
  File "download_files.py", line 49, in main
    downloadFile(service, '1SwYm5Z1zPczZnDulmsbA9wrEJ-JT-hwE')
  File "download_files.py", line 21, in downloadFile
    status, done = downloader.next_chunk()
  File "/usr/local/lib/python3.7/site-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/googleapiclient/http.py", line 705, in next_chunk
    raise HttpError(resp, content, uri=self._uri)
googleapiclient.errors.HttpError: <HttpError 404 when requesting https://www.googleapis.com/drive/v3/files/1SwYm5Z1zPczZnDulmsbA9wrEJ-JT-hwE?alt=media returned "File not found: 1SwYm5Z1zPczZnDulmsbA9wrEJ-JT-hwE.">