2021年4月13日 星期二

Google API - Python 學習筆記

Google API - python ver.

紀錄一些使用 python 呼叫 Google API 的心得

基本前置作業

  • Google Account
    首先你要有 google 帳號。
  • Google Cloud Platform project
    想要使用 Google Cloud Platform (GCP) 的 service,你需要創建一個 GCP project。左上角 project name 右邊的倒三角按下去新增。
  • Enable API
    旁邊的 API&Services => Library => 新增你想要的服務。不過我當初沒有用這步,應該是我用 Oauth 而非 API Keys 的關係 ( 完整介紹 )。
  • Credentials
    產生金鑰,我是選 Desktop App,然後下載其 json 檔就樣就好。雖然 Google Guide 其實有給很多講解及步驟,但我沒做也能運行。

安裝 google python api library

  • 安裝 google api python
    首先安裝 google-api-python-client,點進去有安裝方法,這裡用 Linux 做些紀錄。基本上是安裝一個 virtualenv,讓他新增一個獨立且乾淨的 python 執行環境,然後利用這虛擬環境去下載他門的 library。
        # 安裝虛擬 python 環境和 google-api-python-client
        pip install virtualenv
        virtualenv <your-env>
        source <your-env>/bin/activate
        <your-env>/bin/pip install google-api-python-client
  • 安裝 google_auth_oauthlib
    再來安裝 Oauth 2.0
        <your-env>/bin/pip install google_auth_oauthlib

安裝 google python api library

我寫這篇的主因,因為 google python api library 已經不再更新,有些 sample code 已經過時不能使用所以在這裡紀錄一些可用的 sample code。
  • Sample Code - flow
    這是 Google Oauth API Scope 我拿 blogger 做測試。完整的程式碼在 sample.py,輸出結果在 output.json。這裡擷取片段,順序還要參考完整的程式碼。 
        # 首先是連線設置,Flow 這個 class 是用來讀取你的 Credentials 來認證你的程式。
        # client_secrets.json = 你下載的 Oauth json file。
        # SCOPES = 你宣告要使用哪些功能 ( ex. gmail, blogger... )
        from google_auth_oauthlib.flow import InstalledAppFlow
        SCOPES = ['https://www.googleapis.com/auth/blogger']
        flow = InstalledAppFlow.from_client_secrets_file(
            'client_secrets.json', SCOPES)
    
        # 用 port 0 連線 GCP,這裡會用預設瀏覽器去做認證,結束後會跟你說可以關閉網頁
        creds = flow.run_local_server(port=0)
  • Sample Code - token
    這裡回傳值 creds,是 GCP 給的暫時性 token,若你的 token 還在且未過期,你就可以用此 token 直接連線而不用再透過瀏覽器認證。
        # 如果你有儲存 token,可以直接用 token 重新連線
        # token expired 的話且沒過太就的話可以用 creds.refresh(Request()) 做 refresh token
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
        if not creds.valid:
            if creds.expired and creds.refresh_token:
                creds.refresh(Request())
  • Sample Code - build
    這裡依照 Blogger API Guide 去做取資料。
        # 先依照 scope 取得服務,再依照 api 的格式去取得資料
        # posts() 跟 list() 都是依照 Blogger API Guide 去填寫的,最後執行 execute()
        # 回傳會是 dict,要自己轉 json
        from googleapiclient.discovery import build
        service = build('blogger', 'v3', credentials=creds)
        posts = service.posts().list(blogId=BLOGID,maxResults=3).execute()
參考資料 :
1.我跟Google官網

Related Posts:

  • Python Windows 換行符號與 Unix 換行轉換 ( convert CRLF to LF ) Convert CRLF to LF def convertCRLFtoLF(self, filename): WINDOWS_LINE_ENDING = b'\r\n' UNIX_LINE_ENDING = b'\n' with open(filename, "rb") as f: content = f.read() … Read More
  • C 語言 - unsigned char char 與 unsigned char 的區別     單看兩個變數類型是沒有差別的, char -128 ~ 127, unsigned char 0 ~ 255,範圍大小一樣,並沒差別。唯一差別是在賦值的時候。 賦值的時候 char 與 unsigned char 的區別     (signed) char 有符號 bit ,這會導致你在賦予值時,(signed) char 會依照情況去… Read More
  • Python UnitTest Unit Test      單元測試有一個通用模式 AAA原則,理解了就可以開始實作 Arrange   : 初始化物件、要用到的參數 Act   : 呼叫要測試的方法 Assert   : 驗證測試結果 Python Unit Test      unittest — Uni… Read More
  • 網頁開發(1) 使用 IE 瀏覽器時 Javascript 失效我本人非專業寫網頁,大學沒寫過是進公司才學的,因為沒人維護XD 公司常用瀏覽器是 IE,因為IE可以直接讓你以檔案總管的方式直接開啟 file://... 的超連結,其他瀏覽器都會擋,詳細原因我不知道,但這個可以讓你方便調用 SERVER 上資料,方便很多,其實其他瀏覽器也可以辦到,但要做設定,但不可能你叫公司員工都做這設定,所以大家都用 IE,離題了... JS 檔放到 Server 後無反應     我自己在寫程式時,第… Read More
  • Windows Command Line CMD : Command Line 列出檔案 dir // 列出當前資料夾下的檔案 dir /s // 列出當前資料夾下 + 子資料夾的檔案 dir /? // 列出所有 dir 的指令參數 輸出成檔案 dir /? > 123.txt… Read More

0 意見:

張貼留言

Popular Posts