Задать вопрос
@wows15
В автоматизации сила, брат

OSError: [WinError 121] Превышен таймаут семафора?

Первый раз столкнулся и удивился что в интернете нет никакой информации по этому поводу. Может кто знает как это исправить?

Traceback
Traceback (most recent call last):
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\aiohttp\connector.py", line 969, in _wrap_create_connection
    return await self._loop.create_connection(*args, **kwargs)  # type: ignore  # noqa
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 1056, in create_connection
    raise exceptions[0]
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 1041, in create_connection
    sock = await self._connect_sock(
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 955, in _connect_sock
    await self.sock_connect(sock, address)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 702, in sock_connect
    return await self._proactor.connect(sock, address)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\windows_events.py", line 812, in _poll
    value = callback(transferred, key, ov)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\windows_events.py", line 599, in finish_connect
    ov.getresult()
OSError: [WinError 121] Превышен таймаут семафора

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Admin\Desktop\Binance\main.py", line 100, in <module>
    while True:
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
    return future.result()
  File "C:\Users\Admin\Desktop\Binance\main.py", line 89, in main

  File "C:\Users\Admin\Desktop\Binance\main.py", line 65, in fetch_spot
    return ''
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\aiohttp\client.py", line 1117, in __aenter__
    self._resp = await self._coro
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\aiohttp\client.py", line 520, in _request
    conn = await self._connector.connect(
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\aiohttp\connector.py", line 535, in connect
    proto = await self._create_connection(req, traces, timeout)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\aiohttp\connector.py", line 892, in _create_connection
    _, proto = await self._create_direct_connection(req, traces, timeout)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\aiohttp\connector.py", line 1051, in _create_direct_connection
    raise last_exc
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\aiohttp\connector.py", line 1020, in _create_direct_connection
    transp, proto = await self._wrap_create_connection(
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\aiohttp\connector.py", line 975, in _wrap_create_connection
    raise client_error(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host api.binance.com:443 ssl:default [Превышен таймаут семафора]

В прлошлый раз было на этой строчке:
async with s.get(f'{url}{symbol}') as r:

Код
import aiohttp
import asyncio
import httplib2
import apiclient.discovery
import json
from time import sleep
from oauth2client.service_account import ServiceAccountCredentials
from time import perf_counter


def write_to_google_sheet(p2p, spot):
    CREDENTIALS_FILE = 'creds.json'
    spreadsheet_id = '1OBerxf9dfIdMGh0C3M8KsW_Mnhd-NM8B0-BD-Hxy2dI'

    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        CREDENTIALS_FILE,
        'https://www.googleapis.com/auth/spreadsheets')
    httpAuth = credentials.authorize(httplib2.Http())
    service = apiclient.discovery.build('sheets', 'v4', httpAuth)

    service.spreadsheets().values().batchUpdate(
        spreadsheetId=spreadsheet_id,
        body={
            'valueInputOption': 'USER_ENTERED',
            'data': [
                {'range': 'D2:D8',
                 'majorDimension': 'COLUMNS',
                 'values': [p2p[:7]]},
                {'range': 'B2:B8',
                 'majorDimension': 'COLUMNS',
                 'values': [p2p[:14][7:]]},
                {'range': 'E2:E8',
                 'majorDimension': 'COLUMNS',
                 'values': [p2p[-14:][:-7]]},
                {'range': 'C2:C8',
                 'majorDimension': 'COLUMNS',
                 'values': [p2p[-7:]]},
                {'range': 'I2:I64',
                 'majorDimension': 'COLUMNS',
                 'values': [ spot[:63] ]},
                {'range': 'J2:J64',
                 'majorDimension': 'COLUMNS',
                 'values': [ spot[63:] ]}
            ]
        }
    ).execute()


async def fetch_p2p(s, url, data):
    async with s.post(url, json=data) as r:
        body = json.loads(await r.read())

    return body['data'][0]['adv']['price']


async def fetch_spot(s, url, symbol):
    if not symbol:
        return ''
    async with s.get(f'{url}{symbol}') as r:
        body = json.loads(await r.read())

    return float(body['bidPrice']), float(body['askPrice'])


async def main():
    p2p_url = 'https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search'
    spot_url = 'https://api.binance.com/api/v1/ticker/bookTicker?symbol='

    with open('patterns_p2p.json', encoding='utf-8') as f:
        patterns_p2p = json.loads(f.read())
    with open('patterns_spot.txt', encoding='utf-8') as f:
        patterns_spot = [pattern for pattern in f.read().split('\n')]

    async with aiohttp.ClientSession() as s:
        tasks = []
        for i in range(28):
            task = asyncio.ensure_future(fetch_p2p(s, p2p_url, patterns_p2p[i]))
            tasks.append(task)

        p2p = await asyncio.gather(*tasks)

        tasks = []
        for i in range(32):
            task = asyncio.ensure_future(fetch_spot(s, spot_url, patterns_spot[i]))
            tasks.append(task)

        spot = await asyncio.gather(*tasks)

        tasks = []
        for i in range(32, 63):
            task = asyncio.ensure_future(fetch_spot(s, spot_url, patterns_spot[i]))
            tasks.append(task)

        spot2 = await asyncio.gather(*tasks)
        for answer in spot2:
            spot.append(answer)

        spot = [el[0] if el else '' for el in spot] + [el[1] if el else '' for el in spot]

    return p2p, spot


loop = asyncio.get_event_loop()

while True:
    perfs = perf_counter()

    try:
        p2p, spot = loop.run_until_complete(main())
        write_to_google_sheet(p2p, spot)
    except OSError as e:
        if e.errno == 121:
            pass

    if 10 - perf_counter() + perfs > 0:
        sleep(10 - perf_counter() + perfs)
  • Вопрос задан
  • 4967 просмотров
Подписаться 2 Простой 6 комментариев
Пригласить эксперта
Ваш ответ на вопрос

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

Похожие вопросы