谷歌驱动器API与Python

Ahm*_*gar 8 python google-api google-drive-api google-oauth google-api-python-client

我正在尝试制作一个应用程序,在其中显示我的谷歌驱动器文件夹中的文件和文件夹,因此我转到谷歌API并使用了我在下面的页面上找到的代码

因为我没想到它只是让我登录到我的驱动器然后它返回给我一个错误我正在为其提供照片 这是返回的错误 它说

Message='client_secret' Source=D:\Study\Computer Science\G10\Paython 第二学期\python consol app\python consol app\python_consol_app.py StackTrace:文件“D:\Study\Computer Science\G10\Paython 第二学期\ python consol app\python consol app\python_consol_app.py”,第 48 行,在 main() 中

我设法跳过这个错误并重命名 json 文件,解决了这个错误却发现另一个错误:

消息=授权用户信息的格式不正确,缺少字段 client_secret、client_id、refresh_token。源 = D:\Study\Computer Science\G10\Paython 第二学期\python consol app\python consol app\python_consol_app.py StackTrace:文件“D:\Study\Computer Science\G10\Paython 第二学期\python consol app\python consol app\python_consol_app.py”,第 48 行,在 main() 中

所以我想知道如果我的应用程序可以运行到每个文件夹和子文件夹中,我应该如何解决这样的问题

SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']

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
    
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
   
    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(port=0)
      
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

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

    
    results = service.files().list(
        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()

Run Code Online (Sandbox Code Playgroud)

小智 4

回答

首先要事。您的凭据似乎有问题。我将再次从快速入门下载凭据文件。然后,删除token工作目录中生成的文件。

如果您想更深入,您可以创建一个 GCP 项目,启用Google API 并生成凭据,但如果您不需要,则不需要此方法。

运行 Quickstart 后,您就可以专注于您的任务。要显示云端硬盘中的文件,可以使用Files: list方法,该方法返回当前用户的“我的云端硬盘”中的所有文件和文件夹。要执行特定搜索,您可以使用不同的参数,但最重要的是query. 您可以阅读本指南以获取一些使用示例和进一步的说明。

参考: