我想上传一个文件到google drive使用它的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
但是,我收到如下响应错误消息。
{“错误”:{“错误”:{“域”:“全局”,“原因”:"authError",“消息”:“本接口不支持HTTP基本鉴权”,"locationType":“头部”,“位置”:“授权”},“代码”:401,“消息”:“本接口不支持HTTP基本鉴权”}}
有没有其他方法可以使用python来完成我的工作。
我是否需要登录到google cloud才能访问API以获取身份验证令牌或凭据
发布于 2018-06-04 14:37:41
最后,我明白了如何使用api将文件上传到google drive。
首先,你需要安装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。
发布于 2018-05-31 18:20:50
为了访问私有用户数据,您需要获得用户的许可。没有我的允许,你不能上传到我的硬盘账号。
用户名:密码
名为basic authentication,并在2015年为此使用了谷歌关闭的登录和密码。
现在,为了访问私有用户数据,您需要使用Oauth2。
我建议从Python quickstart开始
"""
Shows basic usage of the Drive v3 API.
Creates a Drive v3 API service and prints the names and ids of the last 10 files
the user has access to.
"""
from __future__ import print_function
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
# Setup the Drive v3 API
SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'
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)
service = build('drive', 'v3', http=creds.authorize(Http()))
# Call the Drive v3 API
results = service.files().list(
pageSize=10, fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
if not items:
print('No files found.')
else:
print('Files:')
for item in items:
print('{0} ({1})'.format(item['name'], item['id']))
发布于 2021-10-20 19:18:23
简单的方法
首先,使用以下命令安装google驱动器库:
!pip install gdown
加载数据
复制您的google驱动器(确保您有正确的google链接):
!gdown https://test_google_url.com
如果需要,解压缩文件:
!unzip test_file_here.zip
https://stackoverflow.com/questions/50621832
复制相似问题