代码之家  ›  专栏  ›  技术社区  ›  Nianing

Python aiohttp请求已停止,但未引发异常

  •  7
  • Nianing  · 技术社区  · 11 年前

    我使用 aiohttp 以请求url。大多数时候,它正常运行,但有时会停止运行,而不会引发任何异常。

    正如您在代码中看到的,我捕获所有异常,但当它停止时,不会打印异常日志。

    日志如下所示:

    get_live_league_games: while True
    try
    yield from aiohttp.request
    

    但是 res = yield from r.json() '不打印,它停止并且不抛出任何异常。

    while True:
        print('get_live_league_games: while True')
        start = time.clock()
        try:
            print('try')
            r = yield from aiohttp.request('GET',url)
            print('yield from aiohttp.request')
            res = yield from r.json()
            print('res = yield from r.json()')
        except aiohttp.errors.DisconnectedError as e:
            logging.warning('get_live_league_games:',e)
            yield from asyncio.sleep(10)
            continue
        except aiohttp.errors.ClientError as e:
            logging.warning('get_live_league_games:',e)
            yield from asyncio.sleep(10)
            continue
        except aiohttp.errors.HttpProcessingError as e:
             logging.warning('get_live_league_games:',e)
             yield from asyncio.sleep(10)
             continue
        except Exception as e:
             logging.warning('get_live_league_games,Exception:',e)
             yield from asyncio.sleep(10)
             continue
        print('request internet time : ', time.clock()-start)
        yield from asyncio.sleep(10)
    
    1 回复  |  直到 11 年前
        1
  •  5
  •   Andrew Svetlov    11 年前

    那个 也许 由于互联网的性质,连接可能会“挂起”很长一段时间,然后才会出现断开错误。

    这就是为什么客户端http操作通常需要超时的原因。

    我建议包装 aiohttp.request() 调用 asyncio.wait_for .