何使用使用Python的驱动器API将文件上传到Google驱动

何使用使用Python的驱动器API将文件上传到Google驱动

本文介绍了如何使用使用Python的驱动器API将文件上传到Google驱动器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用其API将文件上传到Google驱动器,我正在使用代码

I want to upload a file to google drive using its API, I am using the code

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

但是,我收到如下响应错误消息.

However, I am getting response error message as below.

还有其他方法可以使用python来完成工作.

Is there some other way to do my job using python.

我需要登录到Google云以访问用于身份验证令牌或凭据的API

Should I need to sign in to google cloud to access API for authentication token or credentials

推荐答案

最后我了解了如何使用api将文件上传到google驱动器.

Finally I Understood how do I upload file to google drive using api.

首先,您需要安装python库,该库提供了使用drive api的方法.安装库:pip install google-api-python-client然后编写如下代码.

first you need to install python library which gives the methods to use drive api.installing the library: pip install google-api-python-clientthen code as below.

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 可以正常工作.

above code snippet is to create object/variable which allow you to get inside the drive with a right credential. here drive_service does that work.

文件上传代码在下面.

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.

The file ID is important because if you want to download the file from the drive you need the file ID.

这篇关于如何使用使用Python的驱动器API将文件上传到Google驱动器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 08:40