亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 Python 和 Drive API v3 將文件上傳到 Google Drive

如何使用 Python 和 Drive API v3 將文件上傳到 Google Drive

慕哥9229398 2022-07-26 10:46:58
我嘗試使用 Python 腳本從本地系統將文件上傳到 Google Drive,但我不斷收到 HttpError 403。腳本如下:from googleapiclient.http import MediaFileUploadfrom googleapiclient import discoveryimport httplib2import authSCOPES = "https://www.googleapis.com/auth/drive"CLIENT_SECRET_FILE = "client_secret.json"APPLICATION_NAME = "test"authInst = auth.auth(SCOPES, CLIENT_SECRET_FILE, APPLICATION_NAME)credentials = authInst.getCredentials()http = credentials.authorize(httplib2.Http())drive_serivce = discovery.build('drive', 'v3', credentials=credentials)file_metadata = {'name': 'gb1.png'}media = MediaFileUpload('./gb.png',                        mimetype='image/png')file = drive_serivce.files().create(body=file_metadata,                                    media_body=media,                                    fields='id').execute()print('File ID: %s' % file.get('id'))錯誤是:googleapiclient.errors.HttpError: <HttpError 403 when requestinghttps://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&alt=json&fields=id returned "Insufficient Permission: Request had insufficient authentication scopes.">我在代碼中使用了正確的范圍還是遺漏了什么?我還嘗試了我在網上找到的一個腳本,它工作正常,但問題是它需要一個靜態令牌,該令牌會在一段時間后過期。那么如何動態刷新令牌呢?這是我的代碼:import jsonimport requestsheaders = {    "Authorization": "Bearer TOKEN"}para = {    "name": "account.csv",    "parents": ["FOLDER_ID"]}files = {    'data': ('metadata', json.dumps(para), 'application/json; charset=UTF-8'),    'file': ('mimeType', open("./test.csv", "rb"))}r = requests.post(    "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",    headers=headers,    files=files)print(r.text)
查看完整描述

6 回答

?
墨色風雨

TA貢獻1853條經驗 獲得超6個贊

要使用范圍“https://www.googleapis.com/auth/drive”,您需要提交谷歌應用程序進行驗證。

查找范圍的圖像

因此,使用范圍“https://www.googleapis.com/auth/drive.file”而不是“https://www.googleapis.com/auth/drive”來上傳文件而不進行驗證。

也使用 SCOPES 作為列表。

前任:SCOPES = ['https://www.googleapis.com/auth/drive.file']

我可以使用上面的 SCOPE 成功地將文件上傳和下載到谷歌驅動器。


查看完整回答
反對 回復 2022-07-26
?
開滿天機

TA貢獻1786條經驗 獲得超13個贊

“權限不足:請求的身份驗證范圍不足?!?/p>

意味著您已通過身份驗證的用戶尚未授予您的應用程序執行您嘗試執行的操作的權限。

files.create方法要求您已使用以下范圍之一對用戶進行身份驗證。

http://img1.sycdn.imooc.com//62df55c70001311605730313.jpg

而您的代碼似乎確實使用了完整的驅動范圍。我懷疑發生的事情是您已經對用戶進行了身份驗證,然后更改了代碼中的范圍,并且沒有促使用戶再次登錄并同意。您需要從您的應用程序中刪除用戶的同意,方法是讓他們直接在他們的谷歌帳戶中刪除它,或者只是刪除您存儲在應用程序中的憑據。這將強制用戶再次登錄。


谷歌登錄還有一個批準提示強制選項,但我不是 python 開發人員,所以我不完全確定如何強制。它應該類似于下面的 prompt='consent' 行。


flow = OAuth2WebServerFlow(client_id=CLIENT_ID,

                           client_secret=CLIENT_SECRET,

                           scope='https://spreadsheets.google.com/feeds '+

                           'https://docs.google.com/feeds',

                           redirect_uri='http://example.com/auth_return',

                           prompt='consent')

同意屏幕

如果操作正確,用戶應該會看到這樣的屏幕

http://img1.sycdn.imooc.com//62df55d1000144ee05600477.jpg

提示他們授予您對其云端硬盤帳戶的完全訪問權限


令牌泡菜

如果您在https://developers.google.com/drive/api/v3/quickstart/python遵循谷歌教程,則需要刪除包含用戶存儲同意的 token.pickle。


if os.path.exists('token.pickle'):

    with open('token.pickle', 'rb') as token:

        creds = pickle.load(token)


查看完整回答
反對 回復 2022-07-26
?
小怪獸愛吃肉

TA貢獻1852條經驗 獲得超1個贊

您可以使用google-api-python-client構建Drive 服務以使用Drive API。

  • 按照此答案的前 10 個步驟獲得您的授權。

  • 如果您希望用戶只通過一次同意屏幕,則將憑據存儲在文件中。它們包括一個刷新令牌,應用程序可以在 expired 之后使用它來請求授權。例子

使用有效的Drive Service,您可以通過調用如下函數來上傳文件upload_file

def upload_file(drive_service, filename, mimetype, upload_filename, resumable=True, chunksize=262144):

    media = MediaFileUpload(filename, mimetype=mimetype, resumable=resumable, chunksize=chunksize)

    # Add all the writable properties you want the file to have in the body!

    body = {"name": upload_filename} 

    request = drive_service.files().create(body=body, media_body=media).execute()

    if getFileByteSize(filename) > chunksize:

        response = None

        while response is None:

            chunk = request.next_chunk()

            if chunk:

                status, response = chunk

                if status:

                    print("Uploaded %d%%." % int(status.progress() * 100))

    print("Upload Complete!")

現在傳入參數并調用函數...


# Upload file

upload_file(drive_service, 'my_local_image.png', 'image/png', 'my_imageination.png' )

您將在 Google Drive 根文件夾中看到名為my_imageination.png的文件。


有關 Drive API v3 服務和可用方法的更多信息,請點擊此處。


getFileSize()功能:


def getFileByteSize(filename):

    # Get file size in python

    from os import stat

    file_stats = stat(filename)

    print('File Size in Bytes is {}'.format(file_stats.st_size))

    return file_stats.st_size

上傳到驅動器中的某些文件夾很容易...

只需在請求正文中添加父文件夾 ID。


這是File 的屬性。

http://img1.sycdn.imooc.com//62df55e80001f40d08600156.jpg

例子:

request_body = {

  "name": "getting_creative_now.png",

  "parents": ['myFiRsTPaRentFolderId',

              'MyOtherParentId',

              'IcanTgetEnoughParentsId'],

}


查看完整回答
反對 回復 2022-07-26
?
九州編程

TA貢獻1785條經驗 獲得超4個贊

回答:

刪除您的token.pickle文件并重新運行您的應用程序。

更多信息:

只要您擁有正確的憑據集,那么在更新應用程序范圍時所需要做的就是重新獲取令牌。刪除位于應用程序根文件夾中的令牌文件,然后再次運行應用程序。如果你有https://www.googleapis.com/auth/drive范圍,并且在開發者控制臺中啟用了 Gmail API,你應該很好。


查看完整回答
反對 回復 2022-07-26
?
紫衣仙女

TA貢獻1839條經驗 獲得超15個贊

也許這個問題有點過時了,但我找到了一種從 python 上傳文件到谷歌驅動器上的簡單方法


pip install gdrive-python

然后,您必須允許腳本使用此命令在您的 Google 帳戶上上傳文件并按照說明操作:


python -m drive about

最后,上傳文件:


form gdrive import GDrive


drive = GDrive()

drive.upload('path/to/file')

有關 GitHub 存儲庫的更多信息:https ://github.com/vittoriopippi/gdrive-python


查看完整回答
反對 回復 2022-07-26
?
慕姐8265434

TA貢獻1813條經驗 獲得超2個贊

我找到了將文件上傳到谷歌驅動器的解決方案。這里是:


import requests

import json

url = "https://www.googleapis.com/oauth2/v4/token"


        payload = "{\n\"" \

                  "client_id\": \"CLIENT_ID" \

                  "\",\n\"" \

                  "client_secret\": \"CLIENT SECRET" \

                  "\",\n\"" \

                  "refresh_token\": \"REFRESH TOKEN" \

                  "\",\n\"" \

                  "grant_type\": \"refresh_token\"\n" \

                  "}"

        headers = {

            'grant_type': 'authorization_code',

            'Content-Type': 'application/json'

        }


        response = requests.request("POST", url, headers=headers, data=payload)


        res = json.loads(response.text.encode('utf8'))



        headers = {

            "Authorization": "Bearer %s" % res['access_token']

        }

        para = {

            "name": "file_path",

            "parents": "google_drive_folder_id"

        }

        files = {

            'data': ('metadata', json.dumps(para), 'application/json; charset=UTF-8'),

            # 'file': open("./gb.png", "rb")

            'file': ('mimeType', open("file_path", "rb"))

        }

        r = requests.post(

            "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",

            headers=headers,

            files=files

        )

        print(r.text)

要生成客戶端 ID、客戶端密碼和刷新令牌,您可以點擊鏈接:-單擊此處


查看完整回答
反對 回復 2022-07-26
  • 6 回答
  • 0 關注
  • 384 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號