![](/img/trans.png)
[英]MultiIndex pandas dataframe and writing to Google Sheets using gspread-pandas
[英]python gspread connection time out when writing to google sheets
這是我現有的連接代碼,可以正常工作
json_key = json.load(open('path/to/json.js'))
scope = ['https://spreadsheets.google.com/feeds']
credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'], scope)
gc = gspread.authorize(credentials)
但是大約10分鍾后,我的連接就會超時。
在閱讀了一些內容之后,我在連接代碼中發現了這個用法,
headers = gspread.httpsession.HTTPSession(headers={'Connection':'Keep-Alive'})
但我不確定如何將其包含在現有的連接代碼中。 包含它的正確方法是什么? 我所看到的示例與上面的連接代碼不同,並且這些示例指定了我使用的json連接文件中沒有的密碼
這是錯誤的輸出。 有時它們略有不同。 但這全都歸因於相同的連接超時
File "/usr/local/lib/python2.7/dist-packages/gspread/models.py", line 429, in update_acell
return self.update_cell(*(self.get_int_addr(label)), val=val)
File "/usr/local/lib/python2.7/dist-packages/gspread/models.py", line 440, in update_cell
self._cell_addr(row, col))
File "/usr/local/lib/python2.7/dist-packages/gspread/client.py", line 271, in get_cells_cell_id_feed
r = self.session.get(url)
File "/usr/local/lib/python2.7/dist-packages/gspread/httpsession.py", line 79, in get
return self.request('GET', url, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/gspread/httpsession.py", line 75, in request
raise HTTPError("%s: %s" % (response.status, response.read()))
如果超過了時間,則可以調用函數以重新連接到數據庫。 我提供了一個示例代碼片段,您可以將其合並到程序中。
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from datetime import datetime
from datetime import timedelta
def connect_database():
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
client = gspread.authorize(creds)
workbook1 = client.open("File_Name")
w1 = workbook1.worksheet("Sheet1")
w2 = workbook1.worksheet("Sheet2")
return w1,w2
program_start_time=datetime.now()
if datetime.now() > program_start_time + timedelta(minutes=10):
worksheet1, worksheet2 = connect_database()
program_start_time = datetime.now() #Resets the Program Start Time
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.