Warm tip: This article is reproduced from serverfault.com, please click

How To Use Token In A Resumable Upload With Google Drive API (Python)

发布于 2020-12-03 23:21:40

I'm trying to implement resumable upload with Google Drive API via Python. It's important it will be resumable because I need to upload a few GB every time.

So I followed this tutorial. Yet, I have no idea how to use my token inside headers.

The problem is in uploadFile() --> access_token=?

It can't be the token itself (or at least not in its usual form)

from __future__ import print_function
import pickle
import os.path
import json
import os
import requests
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.http import MediaFileUpload

def auth():
    creds = None
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)
    global service
    service = build('drive', 'v3', credentials=creds)

def uploadFile():
    access_token = ??? #As I get it, it should be a string. But how do I stringify a token?

    filename = './20200229_151839_008.jpg'
    filesize = os.path.getsize(filename)

    # 1. Retrieve session for resumable upload.
    headers = {"Authorization": "Bearer " + access_token, "Content-Type": "application/json"}
    params = {
        "name": "20200229_151839_008.jpg",
        "mimeType": "image/img"
    }
    r = requests.post(
        "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",
        headers=headers,
        data=json.dumps(params)
    )
    location = r.headers['Location']


    # 2. Upload the file.
    headers = {"Content-Range": "bytes 0-" + str(filesize - 1) + "/" + str(filesize)}
    r = requests.put(
        location,
        headers=headers,
        data=open(filename, 'rb')
    )
    print(r.text)

Any help would be appreciated.

Thank you.

Questioner
Daniel Fridman
Viewed
0
Tanaike 2020-12-04 08:15:20

In order to retrieve the access token using the script of auth(), when your script is modified, please modify auth() as follows.

From:

global service
service = build('drive', 'v3', credentials=creds)

To:

global service, access_token
service = build('drive', 'v3', credentials=creds)
access_token = creds.token
  • In this case, please remove access_token = ???. By this, the script can be run with access_token retrieved from creds.token.

Note:

  • In this answer, it supposes that you have already been able to upload a file using Drive API. Please be careful this.

  • In your script, SCOPES is not declared. Please be careful this.

  • When I saw your script, it seems that you are using googleapis for python. In this case, you can also achieve the resumable upload using googleapis as follows. For this, please modify uploadFile as follows.

      def uploadFile():
          filename = './20200229_151839_008.jpg'
          metadata = {'name': '20200229_151839_008.jpg'}
          media_body = MediaFileUpload(filename, resumable=True)
          res = service.files().create(body=metadata, media_body=media_body).execute()
          print(res)