python-3.x - 如何使用对 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()
解决方案
我相信你的目标和你目前的情况如下。
- 您想使用
requests
python 删除 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 中的“文件:删除”方法不返回任何值。所以请注意这一点。
如果成功,此方法返回一个空的响应正文。
参考:
推荐阅读
- nestjs - 如何将配置服务值传递给 Nestjs 中的 TypeOrmModule 配置
- google-cloud-platform - 将 sonarqube 与 cloudbuild 集成
- vb.net - 使用 VB.net 监控远程 FTP 服务器
- asp.net - 如何为 ASP.NET 实现 GoJS 组织结构图编辑器?
- php - 以编程方式为每个租户(客户)创建自定义电子邮件收件箱
- apache-spark - Apache Spark 驱动程序、应用程序和计算资源
- python - ValueError: `x` 中的所有数组都应该具有相同的长度。找到一对: len(x[0]) = 97, len(x[?]) = 205
- type-conversion - 表达式生成器:迄今为止的时间戳
- django - 在 Django 中,当登录用户提交表单时,如何自动将用户名添加到模型中
- cypress - 赛普拉斯在登录后截断 URL