• 跳至主要內容
  • 跳至主要資訊欄
  • 跳至頁尾
  • Python應用
    • Python基礎操作
    • Web
      • Django
      • Flask
    • Chat bot
      • Line Bot
      • Telegram Bot
    • GUI
      • QT5
    • Google API
      • Google Drive
      • Google Gmail
      • Google sheet
    • 網頁技術
      • WordPress
      • HTML
      • CSS
      • JavaScript
  • 基本測試技術
    • Linux
    • 功能測試
    • 使用者測試
    • 壓力測試
    • 封包測試
    • 測試報告撰寫
    • 編寫測試用例
  • 自動化測試技術
    • API 自動化測試
      • Python API 測試
      • Postman
      • Jmeter
    • UI 自動化測試
      • AirTest
      • Appium
      • Robot Framework
      • Selenium
  • 問題跟蹤系統
    • Jira
    • Redmine
  • CI/CD
    • Git
    • Jenkins
    • Docker
    • K8S
    • Ngrok
  • 資料庫
    • MongoDB
    • MySQL
    • PostgreSQL
    • Redis
  • 伺服器
    • Heroku
    • Linode
    • Cloudways
    • GCP
    • AWS
  • 關於我
測試先生

測試先生

提供測試相關領域的技術文章以及其他軟體技術相關文章,如WordPress,Js,Css,Html,Python,Docker,Kubernetes,devops,k8s,jenkins,git,heroku,line,telegram

目前位置: 首頁 / Python應用 / Google API / Google Drive / 【Google API 教學】如何申請 OAuth 2.0 憑證? 使用Google Drive API 做示範給你看!

【Google API 教學】如何申請 OAuth 2.0 憑證? 使用Google Drive API 做示範給你看!

文章更新日期: 2022 年 4 月 19 日

如果你想上傳檔案到Google Drive或是從Google Drive下載檔案到本地端

不想要手動上傳而是想要自動上傳的話,推薦你可以使用Google Drive API

那到底該如何使用Google Drive API呢?

照著下方一步一步來,順利完成OAuth 2.0 憑證。

內容目錄

  • 申請 Google Drive API OAuth 2.0 憑證 流程
  • 建立 GCP(google cloud platform) 專案
  • 啟動 Google Drive API
  • 建立 Google Drive API 憑證
  • Google Drive API OAuth 同意畫面新增測試使用者
  • 授權 OAuth 執行 Python 取得 Google Drive 目錄檔案名稱
  • Google API error 403: access_denied
  • 更多技術文章

申請 Google Drive API OAuth 2.0 憑證 流程

要如何申請Google Drive API Oauth 2.0憑證呢?

首先到GCP(google cloud platform),申請新專案

專案內可以建立多個Google 相關的服務,我們則是建立一個Google Drive API的服務功能

建立 GCP(google cloud platform) 專案

假設你不知道怎麼建立GCP專案,可以照著下面做就行

進入到GCP後,點擊圖片1的位置,新增一個專案

第1步 新增專案

建立一個自己喜歡的專案名稱,接著按下建立

第2步 建立專案

選擇到自己新建立的專案,如下方圖片

第3步 切換專案

啟動 Google Drive API

進入API服務資訊主頁平台,主要是申請Google相關服務API以及憑證的項目

第4步 進入到API和服務主頁

點擊啟用API和服務

第5步 啟用API服務

由於我們是要使用Google Drive,因此我們直接搜尋Google Drive

第6步 搜尋GoogleDrive

點擊 Google Drive API

第7步 點擊GoogleDriveAPI

啟用 Google Drive API,點擊啟用

第8步 驟啟用GoogleDriveAPI

建立 Google Drive API 憑證

當我們啟用Google Drive API還是不夠的,需要建立憑證,作為我們執行程式中間的橋樑

因此點擊“建立憑證”

第9步 建立憑證

選擇 Google Drive API

選擇 使用者資料

接著點擊下一步

第10步憑證類型

應用程式名稱可以看你想取名什麼,我則是另名為Demo與專案名稱相同

使用者支援電子郵件以及開發人員聯絡資訊

輸入你目前登入GCP的Gmail

第11步OAuth 同意畫面

範圍部分就不用做選擇,直接點擊儲存並繼續

第12步 範圍

應用程式類型選擇電腦版應用程式

名稱可以自行定義,最後按下建立即可

第13步OAuth 用戶端 ID

順利建立好你的憑證嚕!

可以先點擊下方下載也可以按下完成後,憑證頁面也是有下載的地方。

接著點擊完成就可以了!

第14步您的憑證

Google Drive API OAuth 同意畫面新增測試使用者

這時候不代表完成了,我們要去更改OAuth同意畫面的資訊

如果沒有更改的話,是沒有辦法順利授權的!

因此點擊OAuth同意畫面去新增測試使用者

第15步 點擊OAuth同意畫面

點擊ADD USERS 新增測試使用者

第16步 新增測試使用者

一樣輸入登入GCP的帳戶,當然的你可以新增其他使用者的帳戶

當他們使用同一個憑證時,只要有符合測試使用者Gmail時,就會給於授權

第17步 新增測試使用者帳號

回到憑證頁面,點擊下載icon也就是你的憑證

下載檔案會是一個json檔案

第18步 下載憑證

授權 OAuth 執行 Python 取得 Google Drive 目錄檔案名稱

下載後,先建立一個資料夾,把檔名修改為 credentials.json

另外在建立一個檔案叫做 quickstart.py

程式碼參考下方,直接複製儲存,不用作任何修改

再終端機執行 python3 quickstart.py

from __future__ import print_function

import os.path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

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


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.json 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.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # 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.json', 'w') as token:
            token.write(creds.to_json())

    try:
        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.')
            return
        print('Files:')
        for item in items:
            print(u'{0} ({1})'.format(item['name'], item['id']))
    except HttpError as error:
        # TODO(developer) - Handle errors from drive API.
        print(f'An error occurred: {error}')


if __name__ == '__main__':
    main()
第19步 執行程式碼

會叫起瀏覽器,選擇你的google帳號

你會發現OAuth名稱會是你建立的對應名稱,像我的名稱就是Demo

第20步 選擇Google帳戶

這時候請點擊繼續,為何上面顯示這個應用程式未經Google驗證呢?

主要是我們還是在測試階段,如果上到正式的話,需要更完善的資料才行

但我主要是自己本地端使用,不需要上到正式。

第21步 點擊繼續

點擊允許

第22步 點擊允許

授權給Demo 查看你的Google雲端硬碟檔案

第23步 給予授權Google Drive

搞定!授權成功嚕!

第24步 顯示授權成功

切回你的終端機查看,可以取得到你的Google Drive雲端目錄的資料名稱嚕!

第25步 顯示Google Drive 目錄檔案名稱

Google API error 403: access_denied

假設你沒有將你的google帳號加入到測試使用者

想要授權成功,就必須新增 OAuth 同意畫面測試使用者或是更改資訊

出現下面的畫面,代表顯示授權錯誤

沒給測試帳號會顯示授權錯誤

授權過後,再次執行還需要走這些流程嗎?

是不用的,再執行的資料夾下會自動產生一個 token

事後就不需要走這些過程嚕!

透過上面的教學,我們可以針對Google 提供的各種服務API,建立 OAuth 2.0憑證。

文章內的程式碼都可以直接複製下來練習操作,或是直接套用到自己的專案都行!

多練習,對自已會有很大的幫助!

一回生二回熟,將所學習到內容變成自己的知識。

人就是要學習自己不會的事情,這樣才會不斷的成長、進步!

更多技術文章

透過下方按鈕找尋到相關的技術文章,希望可以幫助到正在學習的你

html 教學文章
Python 教學文章
Ngrok 教學
Jenkins 教學
WordPress 教學
Chatbot 教學

加入到我的粉絲專頁,不定期發布最新文章資訊!
有任何文章問題都可以詢問喔!

測試先生

文章分類: Google Drive 文章標籤: access_denied, google api, google cloud platform, google drive, google drive api, oauth 2.0 © 2021–2022

主要資訊欄

  • 電子郵件
  • Facebook
  • GitHub
  • LinkedIn
  • 申請 Google Drive API OAuth 2.0 憑證 流程
  • 建立 GCP(google cloud platform) 專案
  • 啟動 Google Drive API
  • 建立 Google Drive API 憑證
  • Google Drive API OAuth 同意畫面新增測試使用者
  • 授權 OAuth 執行 Python 取得 Google Drive 目錄檔案名稱
  • Google API error 403: access_denied
  • 更多技術文章

Footer

  • 隱私權政策
  • 免責聲明與使用條款
  • 聯絡我們
  • 電子郵件
  • Facebook
  • GitHub
  • LinkedIn

Copyright © 2022 · Magazine Pro on Genesis Framework · WordPress · 登入