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

其他-如何通过Google Drive API在可恢复的上传中使用令牌(Python)

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

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

我正在尝试通过Python使用Google Drive API实现可恢复的上传。这是可恢复的,这一点很重要,因为我每次都需要上传几个GB。

因此,我遵循了教程。但是,我不知道如何在headers中使用我的令牌

问题出在uploadFile()-> access_token =?

它不能是令牌本身(或至少不是其通常形式)

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)

任何帮助,将不胜感激。

谢谢你。

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

为了使用的脚本检索访问令牌auth(),修改脚本后,请进行以下修改auth()

从:

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

至:

global service, access_token
service = build('drive', 'v3', credentials=creds)
access_token = creds.token
  • 在这种情况下,请删除access_token = ???这样,可以使用access_token从中检索脚本来运行脚本creds.token

笔记:

  • 在此答案中,假设你已经能够使用Drive API上传文件。请注意这一点。

  • 在你的脚本中,SCOPES未声明。请注意这一点。

  • 当我看到你的脚本时,似乎你正在将googleapis用于python。在这种情况下,你还可以按照以下方式使用googleapis实现可恢复的上传。为此,请uploadFile进行如下修改

      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)