python - 如何使用 python 的驱动器 API 将文件上传到谷歌驱动器?
问题描述
我想使用它的 API 将文件上传到谷歌驱动器,我正在使用代码
def newer():
url= 'https://USERNAME:PASSWORD@www.googleapis.com/upload/drive/v3/files?uploadType=media'
data='''{{
"name":"testing.txt",
}}'''
response = requests.post(url, data=data)
print response.text
但是,我收到如下响应错误消息。
{ "error": { "errors": [ { "domain": "global", "reason": "authError", "message": "HTTP Basic Authentication is not supported for this API", "locationType": "header ", "location": "Authorization" } ], "code": 401, "message": "HTTP Basic Authentication is not supported for this API" } }
有没有其他方法可以使用 python 来完成我的工作。
我是否需要登录谷歌云来访问 API 以获取身份验证令牌或凭据
解决方案
最后我明白了如何使用 api 将文件上传到谷歌驱动器。
首先你需要安装 python 库,它提供了使用驱动 api 的方法。安装库: pip install google-api-python-client 然后代码如下。
from __future__ import print_function
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
from apiclient.http import MediaFileUpload,MediaIoBaseDownload
import io
# Setup the Drive v3 API
SCOPES = 'https://www.googleapis.com/auth/drive.file'
store = file.Storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = tools.run_flow(flow, store)
drive_service = build('drive', 'v3', http=creds.authorize(Http()))
上面的代码片段是创建对象/变量,允许您使用正确的凭据进入驱动器。这drive_service
是行得通的。
文件上传代码在下面。
def uploadFile():
file_metadata = {
'name': 'fileName_to_be_in_drive.txt',
'mimeType': '*/*'
}
media = MediaFileUpload('Filename_of_your_local_file.txt',
mimetype='*/*',
resumable=True)
file = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute()
print ('File ID: ' + file.get('id'))
文件 ID 很重要,因为如果要从驱动器下载文件,则需要文件 ID。
推荐阅读
- c++ - 使用 Visual Studio 在 Unreal 中创建一个新的 C++ 类给了我太多错误
- java - 由于版本仅通过终端构建失败
- javascript - 在 discord.js 中使用角色反应获得警告
- c++ - 将 2 个长值相除会在 C++ 中产生错误的输出
- css - Thunderbird - css - 主/(“浏览器”?)页面样式 - bg img 设置
- linux - 在 windows 和 linux 之间使用相同的 git 存储库会导致额外的提交
- web - 为什么我可以在网站上看到信息,但在网站的源代码页上看不到?
- firebase - 如何在收到通知后导航到特定屏幕?
- xcode - CLLocationManager:在 iOS 13 中未调用 didChangeAuthorizationStatus
- r - R:R中的矩阵代数:将值分配给另一个矩阵和表中的空矩阵