close

首先在  https://console.developers.google.com/  建立一個專案
可參考 ...http://echochio.pixnet.net/blog/post/45086034

利用 google 提供 python 的  oauth2client 去連接寫入資料

當然來有其他方式 例如  google apps scripts ...這再找時間測
scripts 看文件彈性不大 ....或許是我不會用

 

建立 Drive API  建立金鑰取得 json 檔案


下載 ....後看一下 內容 , 有

"client_email": "47387011111-compute@developer.gserviceaccount.com",

下載下來的 JSON 改名成 PythonUpload.json 放到程式可讀入的地方
python 要先裝 google 套件

 pip install --upgrade gspread oauth2client

建立google 試算表 , 名叫 UpladByPython , 欄位 : 時間 , 數值  , table 名 : 亂取沒差
但是 google 會自動產生1000 行 ...要都刪除, 我程式用 append 的方式將資料寫入

 

剛剛的 47387011111-compute@developer.gserviceaccount.com 用於建立的
google 試算表共用人員內 ....就是讓那 帳號可寫


網路上抄抄改改後程式 :

import sys
import time
import datetime
import gspread
from oauth2client.service_account import ServiceAccountCredentials as SAC
GDriveJSON = 'PythonUpload.json'
GSpreadSheet = 'UploadByPython'
WaitSecond = 60
print('Ctrl-C to stop')
count = 1
while True:
    try:
        scope = ['https://spreadsheets.google.com/feeds']
        key = SAC.from_json_keyfile_name(GDriveJSON, scope)
        gc = gspread.authorize(key)
        worksheet = gc.open(GSpreadSheet).sheet1
    except Exception as ex:
        print('connect google fail ', ex)
        sys.exit(1)
    new = datetime.datetime.now()
    print('will write to ' ,GSpreadSheet,'write ',new,' & ',count)
    worksheet.append_row((new, count))
    print('write OK ' ,GSpreadSheet)
    count = count+1
    time.sleep(WaitSecond)

出現 error

 ('connect google fail ', SSLError(SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:579)'),),))

如出現是 python 請求2.16.0開始需要Certifi,這會導致此SSL錯誤。指定版本2.15.1
才能卸載certifi 就可已解決 SSL 錯誤問題 

 pip install requests==2.15.1; pip uninstall -y certifi 

如正常 :

運用方式請參考 :

https://github.com/burnash/gspread

 
arrow
arrow
    全站熱搜

    echochio 發表在 痞客邦 留言(0) 人氣()