All Projects → inyutin → Aiohttp_retry

inyutin / Aiohttp_retry

Licence: mit
Simple retry client for aiohttp.

Programming Languages

python
139335 projects - #7 most used programming language

Labels

Projects that are alternatives of or similar to Aiohttp retry

Web Main
🎉 Ultimate Emoji Generator
Stars: ✭ 261 (+467.39%)
Mutual labels:  aiohttp
Aiohttp Demos
Demos for aiohttp project
Stars: ✭ 517 (+1023.91%)
Mutual labels:  aiohttp
Aioslacker
slacker wrapper for asyncio
Stars: ✭ 23 (-50%)
Mutual labels:  aiohttp
Aioresponses
Aioresponses is a helper for mock/fake web requests in python aiohttp package.
Stars: ✭ 278 (+504.35%)
Mutual labels:  aiohttp
Sanic Ms
基于sanic的微服务基础架构
Stars: ✭ 336 (+630.43%)
Mutual labels:  aiohttp
Aiobotocore
asyncio support for botocore library using aiohttp
Stars: ✭ 630 (+1269.57%)
Mutual labels:  aiohttp
binance-chain-python
Binance chain SDK in Python
Stars: ✭ 22 (-52.17%)
Mutual labels:  aiohttp
Anan
安安 - 育儿医疗问答机器人
Stars: ✭ 20 (-56.52%)
Mutual labels:  aiohttp
Aiojobs
Jobs scheduler for managing background task (asyncio)
Stars: ✭ 492 (+969.57%)
Mutual labels:  aiohttp
Aiomixcloud
Mixcloud API wrapper for Python and Async IO
Stars: ✭ 23 (-50%)
Mutual labels:  aiohttp
Aiodocker
Python Docker API client based on asyncio and aiohttp
Stars: ✭ 288 (+526.09%)
Mutual labels:  aiohttp
Diy Async Web Framework
Learn how modern async web frameworks work, by writing simple clone from scratch
Stars: ✭ 309 (+571.74%)
Mutual labels:  aiohttp
Icarus
🕊️ An opensource community/forum project write with python3 aiohttp and vue.js. 一个开源的社区程序,临时测试站:https://t.myrpg.cn
Stars: ✭ 644 (+1300%)
Mutual labels:  aiohttp
Python3 Concurrency Pics 02
爬取 www.mzitu.com 全站图片,截至目前共5162个图集,16.5万多张美女图片,使用 asyncio 和 aiohttp 实现的异步版本只需要不到2小时就能爬取完成。按日期创建图集目录,保存更合理。控制台只显示下载的进度条,详细信息保存在日志文件中。支持异常处理,不会终止爬虫程序。失败的请求,下次再执行爬虫程序时会自动下载
Stars: ✭ 275 (+497.83%)
Mutual labels:  aiohttp
V3n0m Scanner
Popular Pentesting scanner in Python3.6 for SQLi/XSS/LFI/RFI and other Vulns
Stars: ✭ 847 (+1741.3%)
Mutual labels:  aiohttp
TG-FileStreamBot
Stream Telegram files to web
Stars: ✭ 193 (+319.57%)
Mutual labels:  aiohttp
Yarl
Yet another URL library
Stars: ✭ 617 (+1241.3%)
Mutual labels:  aiohttp
Rocketgram
Modern and powerful asynchronous telegram bot framework.
Stars: ✭ 37 (-19.57%)
Mutual labels:  aiohttp
Heroku Aiohttp Web
A project starter template for deploying an aiohttp app to Heroku
Stars: ✭ 14 (-69.57%)
Mutual labels:  aiohttp
Uplink
A Declarative HTTP Client for Python
Stars: ✭ 824 (+1691.3%)
Mutual labels:  aiohttp

Simple aiohttp retry client

codecov

Python 3.6 or higher.

Install: pip install aiohttp-retry.

Warning

This current version is 2.0+. It hasn't backward compatibility for previous versions.
You still can use v1.2 (pip install aiohttp-retry==1.2), but it is unsupported.

Examples of usage:

from aiohttp_retry import RetryClient, ExponentialRetry

async def main():
    retry_options = ExponentialRetry(attempts=1)
    retry_client = RetryClient(raise_for_status=False, retry_options=retry_options)
    async with retry_client.get('https://ya.ru') as response:
        print(response.status)
        
    await retry_client.close()
from aiohttp_retry import RetryClient, RandomRetry

async def main():
    retry_options = RandomRetry(attempts=1)
    retry_client = RetryClient(raise_for_status=False, retry_options=retry_options)

    response = await retry_client.get('/ping')
    print(response.status)
        
    await retry_client.close()
from aiohttp_retry import RetryClient

async def main():
    async with RetryClient() as client:
        async with client.get('https://ya.ru') as response:
            print(response.status)

You can also add some logic, F.E. logging, on failures by using trace mechanic.

import logging
import sys
from types import SimpleNamespace

from aiohttp import ClientSession, TraceConfig, TraceRequestStartParams

from aiohttp_retry import RetryClient, ExponentialRetry


handler = logging.StreamHandler(sys.stdout)
logging.basicConfig(handlers=[handler])
logger = logging.getLogger(__name__)
retry_options = ExponentialRetry(attempts=2)


async def on_request_start(
    session: ClientSession,
    trace_config_ctx: SimpleNamespace,
    params: TraceRequestStartParams,
) -> None:
    current_attempt = trace_config_ctx.trace_request_ctx['current_attempt']
    if retry_options.attempts <= current_attempt:
        logger.warning('Wow! We are in last attempt')


async def main():
    trace_config = TraceConfig()
    trace_config.on_request_start.append(on_request_start)
    retry_client = RetryClient(retry_options=retry_options, trace_configs=[trace_config])

    response = await retry_client.get('https://httpstat.us/503', ssl=False)
    print(response.status)

    await retry_client.close()

Look tests for more examples.
Be aware: last request returns as it is.

Documentation

RetryClient takes the same arguments as ClientSession[docs]
RetryClient has methods:

  • get
  • options
  • head
  • post
  • put
  • patch
  • put
  • delete

They are same as for ClientSession, but take one possible additional argument:

class RetryOptionsBase:
    def __init__(
        self,
        attempts: int = 3,  # How many times we should retry
        statuses: Optional[Iterable[int]] = None,  # On which statuses we should retry
        exceptions: Optional[Iterable[Type[Exception]]] = None,  # On which exceptions we should retry
    ):
        ...

    @abc.abstractmethod
    def get_timeout(self, attempt: int) -> float:
        raise NotImplementedError

You can specify RetryOptions both for RetryClient and it's methods. RetryOptions in methods override RetryOptions defined in RetryClient constructor.

You can define your own timeouts logic or use:

  • ExponentialRetry with exponential backoff
  • RandomRetry for random backoff
  • ListRetry with backoff you predefine by list

Request Trace Context

RetryClient add current attempt number to request_trace_ctx (see examples, for more info see aiohttp doc).

Change URL between retries

You can change URL between retries by specifying url as list of urls. Example:

from aiohttp_retry import RetryClient

retry_client = RetryClient()
async with retry_client.get(url=['/internal_error', '/ping']) as response:
    text = await response.text()
    assert response.status == 200
    assert text == 'Ok!'

await retry_client.close()

In this example we request /interval_error, fail and then successfully request /ping. If you specify less urls than attempts number in RetryOptions, RetryClient will request last url at last attempts. This means that in example above we would request /ping once again in case of failure.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].