簡體   English   中英

Google Drive API for Python:如何創建憑證?

[英]Google Drive API for Python: how to create credential?

我正在編寫一個 Python 腳本來自動將一些文件上傳到 Google Drive。 由於我還是一個新手 Python 程序員,這和其他任何事情一樣都是一個練習,我開始關注Google Quickstart並決定使用他們的quickstart.py作為我自己腳本的基礎。 在討論如何為您的 Python 腳本創建憑據的部分中,它指的是“創建憑據”鏈接,位於https://developers.google.com/workspace/guides/create-credentials

我點擊鏈接,進入我的一個 Google Cloud 項目,並嘗試使用“內部”項目設置 OAuth 同意屏幕,正如他們告訴你的那樣......但我不能。 谷歌說:

“由於您不是 Google Workspace 用戶,因此您只能將您的應用提供給外部(一般受眾)用戶。

所以我嘗試創建一個“外部”項目,然后繼續使用桌面應用程序創建一個新的客戶端 ID。 然后我下載 JSON 憑據並將它們放在與我的 Python 腳本相同的文件夾中,作為"credentials.json" I then execute the Python script in order to authenticate it: the browser opens, I log into my Google account, give it my permissions... and then the browser hangs, because it's redirecting to a localhost URL and obviously my little Python script isn根本不聽我的電腦。

我相信他們最近一定改變了這一點,因為一年前我開始遵循相同的 Python 教程並且可以毫無問題地創建憑據,但 Google Drive API 文檔尚未更新。 那么......我現在如何為 Python 腳本創建憑據?

編輯:在此處添加我的腳本的源代碼。 正如我所說,它與 Google 的“quickstart.py”非常相似:

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.errors import HttpError


# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/drive.metadata', 'https://www.googleapis.com/auth/drive']



def main():
    """Shows basic usage of the Drive v3 API.
    Prints the names and ids of the first 10 files the user has access to.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token_myappname.pickle'):
        with open('token_myappname.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_myappname.pickle', 'wb') as token:
            pickle.dump(creds, token)



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

    # 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(items[0])
 
        print('Files:')
        for item in items:
            #print (item)
            print(u'{0}   {1}   {2}'.format(item['name'], item['owners'], item['parents']))
 

我建議您使用服務帳戶來訪問雲端硬盤。

為此,您需要與服務帳戶 email 共享驅動器(或文件夾)。 然后使用此代碼

from googleapiclient.discovery import build
import google.auth

SCOPES = ['https://www.googleapis.com/auth/drive.metadata', 'https://www.googleapis.com/auth/drive']



def main():
    credentials, project_id = google.auth.default(scopes=SCOPES)


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

    # Call the Drive v3 API
    results = service.files().list(
        q=f"'1YJ6gMgACOqVVbcgKviJKtVa5ITgsI1yP' in parents",
        pageSize=10, fields="nextPageToken, files(id, name, owners, parents)").execute()
    items = results.get('files', [])


    if not items:
        print('No files found.')
    else:
        #print(items[0])

        print('Files:')
        for item in items:
            #print (item)
            print(u'{0}   {1}   {2}'.format(item['name'], item['owners'], item['parents']))

如果您在 Google Cloud 上運行代碼,例如在計算引擎實例中,您需要使用您在驅動器中授權的服務帳戶自定義 VM。 (不要使用計算引擎默認服務帳戶,否則您需要在 VM 上進行額外配置)

如果您在 GCP 之外運行腳本,則需要生成服務帳戶密鑰文件並將其存儲在本地服務器上。 然后,創建一個引用存儲的密鑰文件的完整路徑的環境變量GOOGLE_APPLICATION_CREDENTIALS

除了 Guillaume Blaquiere 發布的其他解決方案之外,我還自己找到了另一個解決方案,我想在這里發布它以防萬一。 我所要做的就是......呃,實際上閱讀我正在復制和粘貼的代碼,特別是這一行:

creds = flow.run_local_server(port=0)

我在快速入門之外查看了 Google 的文檔,發現如下: https://google-auth-oauthlib.readthedocs.io/en/latest/reference/google_auth_oauthlib.flow.html

事實證明,示例代碼在我的計算機打開了一個本地端口來監聽請求,它可能由於“端口 0”部分或其他網絡問題而無法正常工作。

所以我發現的解決方法是使用文檔中的不同身份驗證方法:

  creds = flow.run_console()  

在這種情況下,您可以在命令行中手動粘貼 Google 提供給您的身份驗證代碼。 我剛試了一下,我的憑據愉快地存儲在我的本地泡菜文件中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM