AlmaLinux服务器调用Google API出现TimeoutError问题求助
AlmaLinux服务器连接Google Sheets API超时问题排查与修复
错误信息
(venv) [perezegor@server bots]$ python main.py ^CTraceback (most recent call last): File "/home/bots/main.py", line 57, in <module> data_from_sheet = read_sheet('Sheet1!A2:G') File "/home/bots/main.py", line 33, in read_sheet result = sheet.values().get(spreadsheetId=SPREADSHEET_ID, range=range_name).execute() File "/home/bots/venv/lib/python3.10/site-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper return wrapped(*args, **kwargs) File "/home/bots/venv/lib/python3.10/site-packages/googleapiclient/http.py", line 923, in execute resp, content = _retry_request( File "/home/bots/venv/lib/python3.10/site-packages/googleapiclient/http.py", line 191, in _retry_request resp, content = http.request(uri, method, *args, **kwargs) File "/home/bots/venv/lib/python3.10/site-packages/google_auth_httplib2.py", line 209, in request self.credentials.before_request(self._request, method, uri, request_headers) File "/home/bots/venv/lib/python3.10/site-packages/google/auth/credentials.py", line 230, in before_request self._blocking_refresh(request) File "/home/bots/venv/lib/python3.10/site-packages/google/auth/credentials.py", line 193, in _blocking_refresh self.refresh(request) File "/home/bots/venv/lib/python3.10/site-packages/google/oauth2/service_account.py", line 445, in refresh access_token, expiry, _ = _client.jwt_grant( File "/home/bots/venv/lib/python3.10/site-packages/google/oauth2/_client.py", line 308, in jwt_grant response_data = _token_endpoint_request( File "/home/bots/venv/lib/python3.10/site-packages/google/oauth2/_client.py", line 268, in _token_endpoint_request response_status_ok, response_data, retryable_error = _token_endpoint_request_no_throw( File "/home/bots/venv/lib/python3.10/site-packages/google/oauth2/_client.py", line 215, in _token_endpoint_request_no_throw request_succeeded, response_data, retryable_error = _perform_request() File "/home/bots/venv/lib/python3.10/site-packages/google/oauth2/_client.py", line 191, in _perform_request response = request( File "/home/bots/venv/lib/python3.10/site-packages/google_auth_httplib2.py", line 119, in __call__ response, data = self.http.request( File "/home/bots/venv/lib/python3.10/site-packages/httplib2/__init__.py", line 1724, in request (response, content) = self._request( File "/home/bots/venv/lib/python3.10/site-packages/httplib2/__init__.py", line 1444, in _request (response, content) = self._conn_request(conn, request_uri, method, body, headers) File "/home/bots/venv/lib/python3.10/site-packages/httplib2/__init__.py", line 1366, in _conn_request conn.connect() File "/home/bots/venv/lib/python3.10/site-packages/httplib2/__init__.py", line 1156, in connect sock.connect((self.host, self.port)) TimeoutError: [Errno 110] Connection timed out
问题代码
def read_sheet(range_name): try: SERVICE_ACCOUNT_FILE = 'service_account.json' SPREADSHEET_ID = '' logging.info(f"Reading data from sheet: {range_name}") creds = Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=["https://www.googleapis.com/auth/spreadsheets.readonly"], ) service = build('sheets', 'v4', credentials=creds) sheet = service.spreadsheets() result = sheet.values().get(spreadsheetId=SPREADSHEET_ID, range=range_name).execute() return result.get('values', []) except Exception as e: logging.error(f"Error in read_sheet: {e}") raise
问题背景
上述Python代码用于连接Google API读取表格数据,在PyCharm及其他服务器上运行正常,但部署到AlmaLinux服务器时出现超时错误。已通过ping验证IPv4连通性正常,问题仍未解决。
排查与修复步骤
1. 检查HTTPS端口连通性
ping仅验证ICMP协议连通性,而Google API使用HTTPS(443端口),需用以下命令测试端口可达性:
# 测试Google令牌端点端口 telnet oauth2.googleapis.com 443 # 或使用nc工具 nc -zv oauth2.googleapis.com 443
若连接失败,说明服务器防火墙或网络策略阻断了443端口的出站请求,执行以下命令调整防火墙规则:
sudo firewall-cmd --add-service=https --permanent sudo firewall-cmd --reload
2. 配置代理(若服务器需代理访问外网)
如果服务器处于内网环境,需通过代理访问外部网络,可通过两种方式配置:
- 临时设置环境变量:
export HTTP_PROXY=http://你的代理地址:端口 export HTTPS_PROXY=http://你的代理地址:端口
- 在代码中直接配置代理:
修改代码中构建service的部分,添加代理配置:
import httplib2 # 配置代理信息 http = httplib2.Http(proxy_info=httplib2.ProxyInfo(httplib2.socks.PROXY_TYPE_HTTP, '你的代理地址', 端口)) service = build('sheets', 'v4', credentials=creds, http=http)
3. 验证DNS解析
若DNS解析异常也会导致连接超时,手动解析Google API域名:
nslookup oauth2.googleapis.com nslookup sheets.googleapis.com
若解析失败,修改服务器DNS配置,添加公共DNS:
echo "nameserver 8.8.8.8" | sudo tee -a /etc/resolv.conf
4. 确认服务账号权限
确保AlmaLinux服务器上使用的service_account.json文件正确,且该服务账号已被添加到目标Google表格的共享列表中,权限设置为查看者即可。
5. 更换HTTP客户端库
httplib2在部分环境下存在兼容性问题,可替换为requests库配合google-auth使用:
from google.oauth2 import service_account from googleapiclient.discovery import build from googleapiclient.http import HttpRequest import requests from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry def read_sheet(range_name): try: SERVICE_ACCOUNT_FILE = 'service_account.json' SPREADSHEET_ID = '' logging.info(f"Reading data from sheet: {range_name}") creds = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=["https://www.googleapis.com/auth/spreadsheets.readonly"], ) # 配置带重试机制的requests会话 session = requests.Session() retry = Retry(total=3, backoff_factor=1, status_forcelist=[500, 502, 503, 504]) adapter = HTTPAdapter(max_retries=retry) session.mount('https://', adapter) # 自定义HTTP请求方法 def request(http, *args, **kwargs): response = session.request(*args, **kwargs) return response.status_code, response.text, response.headers service = build('sheets', 'v4', credentials=creds, requestBuilder=HttpRequest) sheet = service.spreadsheets() result = sheet.values().get(spreadsheetId=SPREADSHEET_ID, range=range_name).execute() return result.get('values', []) except Exception as e: logging.error(f"Error in read_sheet: {e}") raise
内容的提问来源于stack exchange,提问作者perezegor
相关产品推荐
相关产品推荐

