首页 > 解决方案 > 如何使用对 google drive v3 api 调用的请求进行身份验证

问题描述

我正在尝试通过 google drive api v3 在 python 中使用请求。我可以让我的脚本通过服务进行身份验证和运行调用。但我注意到 API V3 的大多数文档都在“参考”选项卡下显示了使用 http 请求的示例。当我尝试使用请求完成呼叫时,我不确定如何将我的 Oath 2.0 身份验证放入以引用 token.pickle。试图将令牌强制为字符串,但没有奏效。整个脚本如下。您可以看到“#delete mp4File”部分是我尝试创建请求并添加身份验证的地方。这是我需要帮助的地方。

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

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

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.pickle'):
        with open('token.pickle', '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(
                'client_secrets.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

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

    # List contents of mp4 folder
    results = service.files().list(
        q="'XXXXXXXXXXXXXXXXXXXX' in parents", pageSize=1).execute()
    items = results.get('files', [])

    if not items:
        print('No files found.')
    else:
        for item in items:
            mp4File=(u'{0}'.format(item['id']))
            mp4Name=(u'{0}'.format(item['name']))
            print (mp4Name + " " + mp4File)

    # Download mp4File
    file_id = mp4File
    request = service.files().get_media(fileId=file_id)
    fh = io.FileIO(mp4Name, 'wb')
    downloader = MediaIoBaseDownload(fh, request)
    done = False
    while done is False:
        status, done = downloader.next_chunk()

    #delete mp4File
    url = "https://www.googleapis.com/drive/v3/files/" + file_id

    headers = {
                'Authorization': 'Bearer ' + str(token)
                }

    response = requests.request("DELETE", url, headers=headers)

    print(response.text.encode('utf8'))



if __name__ == '__main__':
    main()

标签: python-3.xgoogle-drive-api

解决方案


我相信你的目标和你目前的情况如下。

  • 您想使用requestspython 删除 Google Drive 中的文件。
  • service = build('drive', 'v3', credentials=creds)可以用于删除文件。

修改点:

  • 在您的脚本中,访问令牌可以通过creds.token.

当这反映到您的脚本中时,它变成如下。

修改后的脚本:

从:
'Authorization': 'Bearer ' + str(token)
至:
'Authorization': 'Bearer ' + creds.token

其他图案:

当使用 googleapis for python 时service.files().list(),它变成如下。

service.files().delete(fileId=file_id).execute()

笔记:

  • Drive API 中的“文件:删除”方法不返回任何值。所以请注意这一点。

    如果成功,此方法返回一个空的响应正文。

参考:


推荐阅读