简体   繁体   中英

How do I upload file to google drive using drive API using python?

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

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

However, I am getting response error message as below.

{ "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" } }

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

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

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

first you need to install python library which gives the methods to use drive api. installing the library: pip install google-api-python-client then 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()))

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.

File uploading code is below here.

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'))

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

In order to access private user data you need the permission of the user. You cant upload to my drive account without my permission.

USERNAME:PASSWORD

Is called basic authentication and uses login and password google shut down for this in 2015.

In order to access private user data now you will need to use Oauth2.

I suggest starting with the 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']))

Simple Way

First, install the google drive library using:

!pip install gdown

Load data

Copy your google drive (ensure you have the correct google link):

!gdown https://test_google_url.com

If required, unzip the file:

!unzip test_file_here.zip

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM