簡體   English   中英

嘗試通過 Python 使用 PostgreSQL 數據更新谷歌表時出錯

[英]Error while trying to update google sheet using PostgreSQL data via Python

我正在使用以下代碼使用 PostgreSQL 表中的數據更新我擁有的谷歌表。 該表格每 15 到 30 分鍾刷新一次,我需要使用最新數據更新此 Google 表格。

下面是 Google 表格列。需要從第 4 行開始更新數據庫中的值。

在此處輸入圖像描述

下面是代碼,

import psycopg2
import gspread
#Service client credential from oauth2client
from oauth2client.service_account import ServiceAccountCredentials
# Print nicely
import pprint
#Create scope
scope =  ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']

cnx_psql = psycopg2.connect(host="xxx.xxx.xxx.xx", database="postgres", user="postgres",
                         password="**********", port="5432")
print('DB connected')
psql_cursor = cnx_psql.cursor()

Sql_query = '''select product_id,low_stock_date,sku from test.low_stock_date;'''
psql_cursor.execute(Sql_query)
results = psql_cursor.fetchall()
cell_values = (results)
#print("Executed the query...")
#print(cell_values)

creds = ServiceAccountCredentials.from_json_keyfile_name('/Users/lino/Documents/GS_secret/secret_key.json',scope)
client = gspread.authorize(creds)

sheet = client.open('https://docs.google.com/spreadsheets/d/*****cBOfy***z8WFOS*****').sheet1
pp = pprint.PrettyPrinter()
#Access all of the record inside that
result = sheet.get_all_record()

for i, val in enumerate(cell_values):  
    cell_list[i].value = val  
    sheet.update_cells(cell_list) 

psql_cursor.close()

cnx_psql.close()

收到以下錯誤,

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/gspread/client.py", line 123, in open
    self.list_spreadsheet_files()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/gspread/utils.py", line 37, in finditem
    return next((item for item in seq if func(item)))
StopIteration

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/lino/Documents/Googlesheet_update.py", line 30, in <module>
    sheet = client.open('https://docs.google.com/spreadsheets/d/*********').sheet1
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/gspread/client.py", line 131, in open
    raise SpreadsheetNotFound
gspread.exceptions.SpreadsheetNotFound

注意:已與客戶 email 地址共享谷歌表。

您正在嘗試使用完整的 URL 打開電子表格,但您使用的是僅適用於標題的open function。

文檔

您可以按其在 Google 文檔中顯示的標題打開電子表格:

 sh = gc.open('My poor gym results')

如果您想具體一點,請使用一個鍵(可以從電子表格的 url 中提取):

 sht1 = gc.open_by_key('0BmgG6nO_6dprdS1MN3d3MkdPa142WFRrdnRRUWl1UFE')

或者,如果您真的懶得提取該密鑰,請粘貼整個電子表格的 url

 sht2 = gc.open_by_url('https://docs.google.com/spreadsheet/ccc?key=0Bm...FE&hl')

在您的情況下,最后一個示例是 go 的方式,因此請使用client.open_by_url而不是client.open

暫無
暫無

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

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