@borisalekseev
extra beginner junior python backend

Google sheets рвёт соединение, почему не помогает переподключение?

Апи google sheets (библиотека gspread, под капотом requests):
import gspread
from gspread.exceptions import APIError

def get_sheet(auth_data=GOOGLE_PATH, sheet_id=SHEET_ID, another_id=analytics_id) -> gspread.Worksheet:
    """Авторизуется и возвращает нужный лист"""
    gc = gspread.service_account(filename=auth_data)
    file = gc.open_by_key(sheet_id)
    return file.get_worksheet_by_id(another_id)


рабочий класс
class Stats:
    def __init__(self, sku):
        self.sku = sku
        self.sheet = get_sheet()

    def get_info(self):
        try:
            data = self.sheet.get_all_records(numericise_ignore=['all'])
            _df = pd.DataFrame(data)
            _df["Прибыль в день"] = _df["Прибыль в день"].apply(self._to_float)
            _df["Дата "] = _df["Дата "].apply(self._to_date)
            return _df[_df['FBO SKU'] == str(self.sku)]
        except APIError:  # inherited from main GSpreadException
            self.sheet = get_sheet()
            return self.get_info()
        except RecursionError:
            print("Не получилось взять данные из аналитики")

При этом в логе ошибка не от gspread а от google auth library:
Ошибка
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    from telegram import bot
  File "/root/ozon_seller/telegram/__init__.py", line 1, in <module>
    from .bot import bot
  File "/root/ozon_seller/telegram/bot.py", line 5, in <module>
    from bot.main import stop_bot, start_bot
  File "/root/ozon_seller/bot/main.py", line 2, in <module>
    from bot.services.tasks import product_worker, manager, ProductTask, product_sales_worker
  File "/root/ozon_seller/bot/services/tasks.py", line 6, in <module>
    from bot.services.analyzer import Analyzer
  File "/root/ozon_seller/bot/services/analyzer.py", line 5, in <module>
    from bot.services.product import OzonProduct
  File "/root/ozon_seller/bot/services/product.py", line 13, in <module>
    sheet = ProductStats(None)
  File "/root/ozon_seller/google_sheets_api/api.py", line 25, in __init__
    self.sheet = get_sheet()
  File "/root/ozon_seller/google_sheets_api/api.py", line 17, in get_sheet
    file = gc.open_by_key(sheet_id)
  File "/root/.local/share/virtualenvs/ozon_seller-Nx_beC3m/lib/python3.8/site-packages/gspread/client.py", line 170, in open_by_key
    return Spreadsheet(self, {"id": key})
  File "/root/.local/share/virtualenvs/ozon_seller-Nx_beC3m/lib/python3.8/site-packages/gspread/spreadsheet.py", line 34, in __init__
    metadata = self.fetch_sheet_metadata()
  File "/root/.local/share/virtualenvs/ozon_seller-Nx_beC3m/lib/python3.8/site-packages/gspread/spreadsheet.py", line 254, in fetch_sheet_metadata
    r = self.client.request("get", url, params=params)
  File "/root/.local/share/virtualenvs/ozon_seller-Nx_beC3m/lib/python3.8/site-packages/gspread/client.py", line 79, in request
    response = getattr(self.session, method)(
  File "/root/.local/share/virtualenvs/ozon_seller-Nx_beC3m/lib/python3.8/site-packages/requests/sessions.py", line 600, in get
    return self.request("GET", url, **kwargs)
  File "/root/.local/share/virtualenvs/ozon_seller-Nx_beC3m/lib/python3.8/site-packages/google/auth/transport/requests.py", line 545, in request
    self.credentials.before_request(auth_request, method, url, request_headers)
  File "/root/.local/share/virtualenvs/ozon_seller-Nx_beC3m/lib/python3.8/site-packages/google/auth/credentials.py", line 133, in before_request
    self.refresh(request)
  File "/root/.local/share/virtualenvs/ozon_seller-Nx_beC3m/lib/python3.8/site-packages/google/oauth2/service_account.py", line 429, in refresh
    access_token, expiry, _ = _client.jwt_grant(
  File "/root/.local/share/virtualenvs/ozon_seller-Nx_beC3m/lib/python3.8/site-packages/google/oauth2/_client.py", line 289, in jwt_grant
    response_data = _token_endpoint_request(
  File "/root/.local/share/virtualenvs/ozon_seller-Nx_beC3m/lib/python3.8/site-packages/google/oauth2/_client.py", line 250, in _token_endpoint_request
    response_status_ok, response_data, retryable_error = _token_endpoint_request_no_throw(
  File "/root/.local/share/virtualenvs/ozon_seller-Nx_beC3m/lib/python3.8/site-packages/google/oauth2/_client.py", line 199, in _token_endpoint_request_no_throw
    request_succeeded, response_data, retryable_error = _perform_request()
  File "/root/.local/share/virtualenvs/ozon_seller-Nx_beC3m/lib/python3.8/site-packages/google/oauth2/_client.py", line 175, in _perform_request
    response = request(
  File "/root/.local/share/virtualenvs/ozon_seller-Nx_beC3m/lib/python3.8/site-packages/google/auth/transport/requests.py", line 199, in __call__
    six.raise_from(new_exc, caught_exc)
  File "<string>", line 3, in raise_from
google.auth.exceptions.TransportError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))

Получается, проблема в библиотеке и мне нужно самому хэндлить исключение из другой либы, которой пользуется gspread?
  • Вопрос задан
  • 92 просмотра
Решения вопроса 1
@borisalekseev Автор вопроса
extra beginner junior python backend
решение: использовать метод gspread.WorkSheet.login при обработке ошибки соединения.
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы