简体   繁体   English

如何使用 google drive v3 api 调用请求进行身份验证

[英]How do I authenticate using requests for google drive v3 api calls

I'm trying to use requests in python with the google drive api v3.我正在尝试将 python 中的请求与谷歌驱动器 api v3 一起使用。 I can get my script to authenticate and run calls with a service.我可以让我的脚本对服务进行身份验证和运行调用。 But I notice that most of the documentation for API V3 shows examples using http requests under the "reference" tab.但我注意到 API V3 的大部分文档都在“参考”选项卡下显示了使用 http 请求的示例。 When I try to complete a call using requests, I'm not sure how to put my Oath 2.0 authentication in to reference the token.pickle.当我尝试使用请求完成呼叫时,我不确定如何将我的 Oath 2.0 身份验证放入其中以引用 token.pickle。 Tried to force the token to a string but did not work.试图将令牌强制为字符串但没有用。 The whole script is below.整个脚本如下。 You can see the "#delete mp4File" section is where I'm trying to create a request and add authentication.您可以看到“#delete mp4File”部分是我尝试创建请求并添加身份验证的地方。 This is where I need help.这是我需要帮助的地方。

    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()

I believe your goal and your current situation as follows.我相信你的目标和你目前的情况如下。

  • You want to delete a file in Google Drive using requests with python.您想使用 python 的requests删除 Google 云端硬盘中的文件。
  • Your service = build('drive', 'v3', credentials=creds) can be used for deleting the file.您的service = build('drive', 'v3', credentials=creds)可用于删除文件。

Modification point:修改点:

  • In your script, the access token can be retrieved by creds.token .在您的脚本中,可以通过creds.token检索访问令牌。

When this is reflected to your script, it becomes as follows.当这反映到您的脚本中时,它变成如下。

Modified script:修改脚本:

From: 从:
 'Authorization': 'Bearer ' + str(token)
To: 到:
 'Authorization': 'Bearer ' + creds.token

Other pattern:其他图案:

When googleapis for python is used like service.files().list() , it becomes as follows.当像service.files().list()这样使用 python 的 googleapis 时,它变成如下。

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

Note:笔记:

  • The method of "Files: delete" in Drive API returns no values.驱动器 API 中的“文件:删除”方法不返回任何值。 So please be careful this.所以请注意这一点。

    If successful, this method returns an empty response body.如果成功,此方法将返回一个空的响应正文。

Reference:参考:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 谷歌驱动器 API v3 使用 Python - Google Drive API v3 using Python 我如何使用谷歌驱动器 api v3 将文件上传到共享驱动器 - How can i used google drive api v3 to upload a file to shared drive 如何在 Python 中使用 Google API v3 使驱动器文件夹“对网络公开”? - How to make drive folder "public to the web" using Google API v3 in Python? 使用驱动器 API V3 上传更新的带有 Python 的 Google 驱动器上的文件不起作用 - Upload updated a file on Google Drive with Python using Drive API V3 does not work 使用 Python 中的 next_chunk() 上传 Google Drive API v3 错误查看状态的说明? - Explaination on error viewing status of Google Drive API v3 upload using next_chunk() in Python? google Drive api v3 文件上传错误 - google Drive api v3 file upload errors 谷歌驱动器API v3(python)更新文件权限“角色” - google drive api v3 (python) update file premissions “role” 使用gzip通过API v3 Python 3优化上传到云端硬盘 - Using gzip to Optimize Upload to Drive using API v3 Python 3 如何使用对以下 API 调用的请求? - how do I use requests for the below API calls? googleapiclient.errors.HttpError 与 google drive v3 api 上传错误 - googleapiclient.errors.HttpError with google drive v3 api upload error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM