我想使用其API将文件上传到Google驱动器,我正在使用代码
def newer():
url= 'https://USERNAME:[email protected]/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”:“此API不支持HTTP基本认证”,“ locationType”:“标题“,”位置“:”授权“}],”代码“:401,”消息“:”此API不支持HTTP基本认证“}}
还有其他方法可以使用python来完成我的工作。
我是否需要登录Google Cloud来访问用于身份验证令牌或凭据的API
最后,我了解了如何使用api将文件上传到Google驱动器。
首先,您需要安装python库,该库提供了使用驱动器api的方法。安装库:pip安装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。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句