Linux服务器上gspread连接Google Sheet时挂起问题求助
Gspread在Linux服务器连接Google Sheet时挂起,Windows正常运行
代码示例
import gspread gc = gspread.service_account(filename='bot/creds.json') doc = gc.open("Tournaments") print(doc)
现象对比
- Windows 10环境:运行完全正常,输出如下:
<Spreadsheet 'Tournaments' id:[REMOVED]> - Linux服务器环境:运行时直接挂起,按下
Ctrl+C中断后,得到如下报错:^CTraceback (most recent call last): File "testing.py", line 3, in <module> doc = gc.open("Tournaments") File "/home/[REMOVED]/.local/lib/python3.8/site-packages/gspread/client.py", line 152, in open self.list_spreadsheet_files(title, folder_id), File "/home/[REMOVED]/.local/lib/python3.8/site-packages/gspread/client.py", line 127, in list_spreadsheet_files res = self.request("get", url, params=params).json() File "/home/[REMOVED]/.local/lib/python3.8/site-packages/gspread/client.py", line 79, in request response = getattr(self.session, method)( File "/usr/lib/python3/dist-packages/requests/sessions.py", line 546, in get return self.request('GET', url, **kwargs) File "/home/[REMOVED]/.local/lib/python3.8/site-packages/google/auth/transport/requests.py", line 476, in request self.credentials.before_request(auth_request, method, url, request_headers) File "/home/[REMOVED]/.local/lib/python3.8/site-packages/google/auth/credentials.py", line 133, in before_request self.refresh(request) File "/home/[REMOVED]/.local/lib/python3.8/site-packages/google/oauth2/service_account.py", line 410, in refresh access_token, expiry, _ = _client.jwt_grant( File "/home/[REMOVED]/.local/lib/python3.8/site-packages/google/oauth2/_client.py", line 193, in jwt_grant response_data = _token_endpoint_request(request, token_uri, body) File "/home/[REMOVED]/.local/lib/python3.8/site-packages/google/oauth2/_client.py", line 161, in _token_endpoint_request response_status_ok, response_data = _token_endpoint_request_no_throw( File "/home/[REMOVED]/.local/lib/python3.8/site-packages/google/oauth2/_client.py", line 115, in _token_endpoint_request_no_throw response = request(method="POST", url=token_uri, headers=headers, body=body) File "/home/[REMOVED]/.local/lib/python3.8/site-packages/google/auth/transport/requests.py", line 183, in __call__ response = self.session.request( File "/usr/lib/python3/dist-packages/requests/sessions.py", line 533, in request resp = self.send(prep, **send_kwargs) File "/usr/lib/python3/dist-packages/requests/sessions.py", line 646, in send r = adapter.send(request, **kwargs) File "/usr/lib/python3/dist-packages/requests/adapters.py", line 439, in send resp = conn.urlopen( File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 665, in urlopen httplib_response = self._make_request( File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 376, in _make_request self._validate_conn(conn) File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 996, in _validate_conn conn.connect() File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 314, in connect conn = self._new_conn() File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 159, in _new_conn conn = connection.create_connection( File "/usr/lib/python3/dist-packages/urllib3/util/connection.py", line 74, in create_connection sock.connect(sa) KeyboardInterrupt
补充信息
- 代码存储在服务器的网络驱动器中,两台设备的代码和目录结构完全一致
- 等待超过10分钟后,代码能成功连接
- 对Web开发相关技术较为陌生,需要通俗易懂的解释和解决方案
问题通俗解释
核心原因是Linux服务器和Google认证服务器之间的网络链路不通畅:
Windows的网络环境能快速和Google的服务器建立连接、完成认证,但Linux服务器可能因为防火墙限制、代理未配置、DNS解析缓慢、网络链路拥堵等问题,导致连接认证的过程被卡住,需要长时间等待才能建立成功。
解决方案
1. 先排查网络连通性
在Linux服务器的终端执行以下命令,测试和Google认证服务器的连接:
- 测试延迟和丢包:
ping oauth2.googleapis.com - 测试能否快速访问认证接口:
curl -v https://oauth2.googleapis.com/token
如果命令执行很慢或超时,直接指向网络问题,优先解决网络层面的问题。
2. 给代码添加超时限制
避免代码无限挂起,同时快速触发超时提示,方便排查:
import gspread from requests import Timeout from google.auth.transport.requests import Request # 自定义带超时的请求工具,超时时间设为30秒(可根据需要调整) class TimeoutRequest(Request): def __init__(self, timeout=30): self.timeout = timeout super().__init__() def __call__(self, *args, **kwargs): kwargs.setdefault("timeout", self.timeout) return super().__call__(*args, **kwargs) # 使用自定义的超时请求初始化gspread gc = gspread.service_account(filename='bot/creds.json', request_factory=TimeoutRequest) try: doc = gc.open("Tournaments") print(doc) except Timeout: print("连接超时,请检查服务器网络设置")
3. 检查防火墙/代理设置
- 如果服务器有防火墙,确认没有阻止出站请求到
*.googleapis.com这类Google API域名 - 如果服务器需要通过代理访问外网,先配置代理:
方式一:终端临时设置(运行代码前执行)
方式二:在代码开头添加代理配置export HTTP_PROXY=http://你的代理地址:端口 export HTTPS_PROXY=http://你的代理地址:端口import os os.environ['HTTP_PROXY'] = 'http://你的代理地址:端口' os.environ['HTTPS_PROXY'] = 'http://你的代理地址:端口'
4. 更换DNS服务器
如果是DNS解析慢导致的连接延迟,把Linux服务器的DNS换成公共DNS:
- 编辑
/etc/resolv.conf文件,添加以下内容:nameserver 8.8.8.8 nameserver 8.8.4.4 - 保存后,重新测试网络连接
5. 升级依赖库
旧版本的依赖库可能存在网络兼容问题,更新到最新版:
pip install --upgrade gspread requests google-auth google-auth-oauthlib google-auth-httplib2
内容的提问来源于stack exchange,提问作者Luminance
相关产品推荐
相关产品推荐

