Ошибка: google.auth.exceptions.TransportError: Unable to find the server at oauth2.googleapis.com
Я делаю проект на django. С помощью celery мне надо в определённое время обновлять гугл таблицу, закидывая в неё новые данные из стороннего api. Но как только celery получает задачу, у меня возникает ошибка:
[2024-04-01 14:34:00,336: INFO/MainProcess] Task google_ads.tasks.update_google_spreadsheet[13da8463-27eb-447c-8967-8c385fd79d7b] received
[2024-04-01 14:34:00,339: DEBUG/MainProcess] TaskPool: Apply <function fast_trace_task at 0x000001EF25461F80> (args:('google_ads.tasks.update_google_spreadsheet', '13da8463-27eb-447c-8967-8c385fd79d7b', {'lang': 'py', 'task': 'google_ads.tasks.update_google_spreadsheet', 'id': '13da8463-27eb-447c-8967-8c385fd79d7b',
'shadow': None, 'eta': None, 'expires': None, 'group': None, 'group_index': None, 'retries': 0, 'timelimit': [None, None], 'root_id': '13da8463-27eb-447c-8967-8c385fd79d7b', 'parent_id': None, 'argsrepr': '()', 'kwargsrepr': '{}', 'origin': 'gen16544@LAPTOP-09UDD77E', 'ignore_result': False, 'replaced_task_nesting':
0, 'stamped_headers': None, 'stamps': {}, 'properties': {'correlation_id': '13da8463-27eb-447c-8967-8c385fd79d7b', 'reply_to': '87fb7af1-8e34-37ad-b7f9-e2fc09b0c815', 'periodic_task_name': 'update-google-spreadsheet-every-night', 'delivery_mode': 2, 'delivery_info': {'exchange': '', 'routing_key': 'celery'}, 'priority': 0, 'body_encoding': 'base64', 'delivery_tag': 'fa0a621b-a10f-404f-9512-33f98cc0a571'}, 'reply_to': '87fb7af1-8e34-37ad-b7f9-e2fc09b0c815', 'correlation_id':... kwargs:{})
[2024-04-01 14:34:00,349: WARNING/MainProcess] 1
[2024-04-01 14:34:00,597: WARNING/MainProcess] 3
[2024-04-01 14:34:00,634: INFO/MainProcess] file_cache is only supported with oauth2client<4.0.0
[2024-04-01 14:34:00,645: WARNING/MainProcess] 4
[2024-04-01 14:34:00,654: DEBUG/MainProcess] Starting new HTTPS connection (1): luck2you.ru:443
[2024-04-01 14:34:01,614: DEBUG/MainProcess] https://luck2you.ru:443 "GET /jl8sn.php?page=Stats&camp_id=55&group1=27&group2=290&date=9&num_page=1&val_page=All&api_key=80000019bdb5f8f0830a2523952418bb6eccb13 HTTP/1.1" 200 None
[2024-04-01 14:34:01,862: WARNING/MainProcess] 7
[2024-04-01 14:34:01,865: WARNING/MainProcess] 5
[2024-04-01 14:34:02,458: DEBUG/MainProcess] URL being requested: POST https://sheets.googleapis.com/v4/spreadsheets/1IfqgOYPkTNqsh1leF2ftulW5OGeBk0-auF3xT9pL4yA/values:batchUpdate?alt=json
[2024-04-01 14:34:02,528: DEBUG/MainProcess] Making request: POST https://oauth2.googleapis.com/token
[2024-04-01 14:34:02,691: ERROR/MainProcess] Task google_ads.tasks.update_google_spreadsheet[13da8463-27eb-447c-8967-8c385fd79d7b] raised unexpected: TransportError(ServerNotFoundError('Unable to find the server at oauth2.googleapis.com'))
Traceback (most recent call last):
File "C:\Users\jrsyt\OneDrive\Документы\VS_Code\googleAds\env\Lib\site-packages\httplib2\__init__.py", line 1366, in _conn_request
conn.connect()
File "C:\Users\jrsyt\OneDrive\Документы\VS_Code\googleAds\env\Lib\site-packages\httplib2\__init__.py", line 1156, in connect
sock.connect((self.host, self.port))
File "C:\Users\jrsyt\OneDrive\Документы\VS_Code\googleAds\env\Lib\site-packages\eventlet\greenio\base.py", line 255, in connect
if socket_connect(fd, address):
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\jrsyt\OneDrive\Документы\VS_Code\googleAds\env\Lib\site-packages\eventlet\greenio\base.py", line 39, in socket_connect
err = descriptor.connect_ex(address)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
socket.gaierror: [Errno 11004] getaddrinfo failed
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\jrsyt\OneDrive\Документы\VS_Code\googleAds\env\Lib\site-packages\google_auth_httplib2.py", line 119, in __call__
response, data = self.http.request(
^^^^^^^^^^^^^^^^^^
File "C:\Users\jrsyt\OneDrive\Документы\VS_Code\googleAds\env\Lib\site-packages\httplib2\__init__.py", line 1724, in request
(response, content) = self._request(
^^^^^^^^^^^^^^
File "C:\Users\jrsyt\OneDrive\Документы\VS_Code\googleAds\env\Lib\site-packages\httplib2\__init__.py", line 1444, in _request
(response, content) = self._conn_request(conn, request_uri, method, body, headers)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\jrsyt\OneDrive\Документы\VS_Code\googleAds\env\Lib\site-packages\httplib2\__init__.py", line 1373, in _conn_request
raise ServerNotFoundError("Unable to find the server at %s" % conn.host)
httplib2.error.ServerNotFoundError: Unable to find the server at oauth2.googleapis.com
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\jrsyt\OneDrive\Документы\VS_Code\googleAds\env\Lib\site-packages\celery\app\trace.py", line 477, in trace_task
R = retval = fun(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^
File "C:\Users\jrsyt\OneDrive\Документы\VS_Code\googleAds\env\Lib\site-packages\celery\app\trace.py", line 760, in __protected_call__
return self.run(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\jrsyt\OneDrive\Документы\VS_Code\googleAds\google_ads\tasks.py", line 37, in update_google_spreadsheet
update_spreadsheet_values(service, link, formatted_data)
File "C:\Users\jrsyt\OneDrive\Документы\VS_Code\googleAds\google_ads\utils.py", line 86, in update_spreadsheet_values
}).execute()
^^^^^^^^^
File "C:\Users\jrsyt\OneDrive\Документы\VS_Code\googleAds\env\Lib\site-packages\googleapiclient\_helpers.py", line 130, in positional_wrapper
return wrapped(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\jrsyt\OneDrive\Документы\VS_Code\googleAds\env\Lib\site-packages\googleapiclient\http.py", line 923, in execute
resp, content = _retry_request(
^^^^^^^^^^^^^^^
File "C:\Users\jrsyt\OneDrive\Документы\VS_Code\googleAds\env\Lib\site-packages\googleapiclient\http.py", line 191, in _retry_request
resp, content = http.request(uri, method, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\jrsyt\OneDrive\Документы\VS_Code\googleAds\env\Lib\site-packages\google_auth_httplib2.py", line 209, in request
self.credentials.before_request(self._request, method, uri, request_headers)
File "C:\Users\jrsyt\OneDrive\Документы\VS_Code\googleAds\env\Lib\site-packages\google\auth\credentials.py", line 230, in before_request
self._blocking_refresh(request)
File "C:\Users\jrsyt\OneDrive\Документы\VS_Code\googleAds\env\Lib\site-packages\google\auth\credentials.py", line 193, in _blocking_refresh
self.refresh(request)
File "C:\Users\jrsyt\OneDrive\Документы\VS_Code\googleAds\env\Lib\site-packages\google\oauth2\service_account.py", line 445, in refresh
access_token, expiry, _ = _client.jwt_grant(
^^^^^^^^^^^^^^^^^^
File "C:\Users\jrsyt\OneDrive\Документы\VS_Code\googleAds\env\Lib\site-packages\google\oauth2\_client.py", line 308, in jwt_grant
response_data = _token_endpoint_request(
^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\jrsyt\OneDrive\Документы\VS_Code\googleAds\env\Lib\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 "C:\Users\jrsyt\OneDrive\Документы\VS_Code\googleAds\env\Lib\site-packages\google\oauth2\_client.py", line 215, in _token_endpoint_request_no_throw
request_succeeded, response_data, retryable_error = _perform_request()
^^^^^^^^^^^^^^^^^^
File "C:\Users\jrsyt\OneDrive\Документы\VS_Code\googleAds\env\Lib\site-packages\google\oauth2\_client.py", line 191, in _perform_request
response = request(
^^^^^^^^
File "C:\Users\jrsyt\OneDrive\Документы\VS_Code\googleAds\env\Lib\site-packages\google_auth_httplib2.py", line 126, in __call__
raise exceptions.TransportError(exc)
google.auth.exceptions.TransportError: Unable to find the server at oauth2.googleapis.com
Вот мой код задачи:
from celery import shared_task
from .utils import fetch_data_from_api, update_spreadsheet_values, filter_data
from .models import Campaign
from google.oauth2 import service_account
from oauth2client.service_account import ServiceAccountCredentials
import httplib2
import googleapiclient.discovery
CREDENTIALS_FILE = 'genuine-flight-417318-36aacf4a1fc2.json' # Имя файла с закрытым ключом
@shared_task
def update_google_spreadsheet():
print(1)
# Получение данных из БД
campaigns = Campaign.objects.all()
for campaign in campaigns:
camp_id = campaign.campaign_id
domen = campaign.domen
link = campaign.spreadsheet_link
conversion_name = campaign.conversion_name
api_key = campaign.api_key
print(3)
credentials = service_account.Credentials.from_service_account_file(CREDENTIALS_FILE, scopes=['https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'])
service = googleapiclient.discovery.build('sheets', 'v4', credentials=credentials)
print(4)
# Получение данных из API
data = fetch_data_from_api(camp_id, api_key)
if data is not None and data != "no_clicks":
print(7)
new_data = filter_data(data, domen)
formatted_data = [{"name": item['name'], "conversion_name": conversion_name} for item in new_data]
print(5)
update_spreadsheet_values(service, link, formatted_data)
print(6)
elif data == "no_clicks":
print(8)
spreadsheet_id = link.split('/')[-2]
service.spreadsheets().values().clear(
spreadsheetId=spreadsheet_id,
range="",
body={}
).execute()
print(2)
И код функции update_spreadsheet_values
:
# Заполнение гугл-таблицы данными
def update_spreadsheet_values(service, link, data):
# Формируем данные для обновления
current_datetime = datetime.now().strftime("%d %b %Y %H:%M:%S").upper()
values = [[entry['name'], entry['conversion_name'], current_datetime] for entry in data]
data_to_update = {
"range": "A1:C{}".format(len(values)),
"majorDimension": "ROWS",
"values": values
}
# Выполняем обновление таблицы
spreadsheet_id = link.split('/')[-2]
results = service.spreadsheets().values().batchUpdate(spreadsheetId=spreadsheet_id, body={
"valueInputOption": "USER_ENTERED",
"data": [data_to_update]
}).execute()
return results
Почему-то, когда я использую эту функцию не через celery, а когда сам запрашиваю данные в первый раз, всё работает прекрасно. Поэтому, непонятно, почему тоже самое через celery не работает.