Saravanan666/pypi-org huggingface dataset:
Package: aiotgbot
Key FeaturesAsyncio andaiohttpbasedAllTelegram Bot APItypes and methods supportedBot API rate limit supportBoth long polling and webhooks supportedFully type annotated (PEP 484)Installationaiotgbot is available on PyPI. Use pip to install it:pipinstallaiotgbotRequirementsPython >= 3.8aiohttpaiojobsmsgspecbackofffrozenlistaiofreqlimityarlUsing aiotgbotfromtypingimportAsyncIteratorfromaiotgbotimport(Bot,BotUpdate,HandlerTable,PollBot,PrivateChatFilter,Runner)fromaiotgbot.storage_memoryimportMemoryStoragehandlers=HandlerTable()@handlers.message(filters=[PrivateChatFilter()])asyncdefreply_private_message(bot:Bot,update:BotUpdate)->None:assertupdate.messageisnotNonename=(f'{update.message.chat.first_name}'f'{update.message.chat.last_name}')awaitbot.send_message(update.message.chat.id,f'Hello,{name}!')asyncdefrun_context(runner:Runner)->AsyncIterator[None]:storage=MemoryStorage()awaitstorage.connect()handlers.freeze()bot=PollBot(runner['token'],handlers,storage)awaitbot.start()yieldawaitbot.stop()awaitstorage.close()defmain()->None:runner=Runner(run_context)runner['token']='some:token'runner.run()if__name__=='__main__':main()
Package: aiothornode
aiothornodeThis is a simple Python library to accessTHORChainnodes. It is asynchronous and usesaiohttp.Importantv.0.1.0 breaking changes:NamedTuples instead of DataClasses for Thor entitiesEnvironments were renamedNo more consensus featuresv.0.0.21 is hotfix. Port 1317 was disabled, so it is an emergency upgrade to save this lib. More news will be later...Features:Now it is just a convenient wrapper for THORNode APISupported endpoints:ConstantsMimirNodes (node accounts)Current TX queue lengthPools (current and at arbitrary height)Tendermint block at heightInbound addresses and other chain infoAsgard & Yggdrasil vaults (new!)Balance of THOR accountInstallationpython -m pip install git+https://github.com/tirinox/aiothornodeQuick startThe following code is quite self-documenting:import random

from aiothornode.connector import *
from aiothornode.env import *
import asyncio
import aiohttp


def delim():
    print('-' * 100)


async def main():
    env = MAINNET.copy()
    # env = ThorEnvironment(...)  # custom

    async with aiohttp.ClientSession() as session:
        connector = ThorConnector(env, session)

        genesis = await connector.query_genesis()
        print(f'Chain ID = {genesis["chain_id"]}')
        delim()

        chains = await connector.query_chain_info()
        chains = list(chains.values())
        print('Chain info:', chains)
        delim()

        print('Tendermint Block:')
        tender_block = await connector.query_tendermint_block_raw(100001)
        block_header = tender_block['result']['block']['header']
        print(f'{block_header["height"] = } and {block_header["time"] = }')
        delim()

        constants = await connector.query_constants()
        print(f'Constants: {constants}')
        delim()

        mimir = await connector.query_mimir()
        mimir_1 = mimir.get('MINIMUMBONDINRUNE')
        print(f'Mimir: {mimir}, MINIMUMBONDINRUNE = {mimir_1}')
        delim()

        queue = await connector.query_queue()
        print(f'Queue: {queue}')
        delim()

        node_accounts = await connector.query_node_accounts(consensus=False)
        print(f'Example node account: {random.sample(node_accounts, 1)[0]}')
        delim()

        pool = await connector.query_pool('BNB.BUSD-BD1', height=8218339)
        print(pool)
        delim()

        pools = await connector.query_pools()
        print(pools[0])
        print(f'Total {len(pools)} pools')
        delim()

        bank = await connector.query_balance('thor1dheycdevq39qlkxs2a6wuuzyn4aqxhve4qxtxt')
        print(f'Balance of {bank.address} is {bank.runes_float} Rune')
        delim()


if __name__ == '__main__':
    asyncio.run(main())TestingInstall PyTest and an async plugin for it:pip install pytest
pip install pytest-asyncioThen runpytest test
Package: aiothrift
Asyncio implementation for thrift protocol, which is heavily based onthriftpy2.Documentation:https://aiothrift.readthedocs.org/Installation$ pip install aiothriftUsage exampleThrift fileservice PingPong {
    string ping(),
    i64 add(1:i32 a, 2:i64 b),
}Serverimportasyncioimportaiothriftpingpong_thrift=aiothrift.load('pingpong.thrift',module_name='pingpong_thrift')classDispatcher:defping(self):return"pong"asyncdefadd(self,a,b):awaitasyncio.sleep(1)returna+basyncdefmain():server=awaitaiothrift.create_server(pingpong_thrift.PingPong,Dispatcher()))asyncwithserver:awaitserver.serve_forever()asyncio.run(main())Clientimportasyncioimportaiothriftpingpong_thrift=aiothrift.load('pingpong.thrift',module_name='pingpong_thrift')asyncdefgo():conn=awaitaiothrift.create_connection(pingpong_thrift.PingPong)print(awaitconn.ping())print(awaitconn.add(5,6))conn.close()asyncio.run(go())Or use ConnectionPoolimportasyncioimportaiothriftpingpong_thrift=aiothrift.load('pingpong.thrift',module_name='pingpong_thrift')asyncdefgo():client=awaitaiothrift.create_pool(pingpong_thrift.PingPong)print(awaitclient.ping())print(awaitclient.add(5,6))client.close()awaitclient.wait_closed()asyncio.run(go())It’s just that simple to begin withaiothrift, and you are not forced to useaiothrifton both server and client side.
So if you already have a normal thrift server setup, feel free to create an async thrift client to communicate with that server.RequirementsPython >= 3.7.0async-timeoutthriftpy2LICENSEaiothriftis offered under the MIT license.
Package: aiothrottle
aiothrottleThrottling, flow controlling StreamReader for aiohttpRequirementsPython >= 3.4.2aiohttphttps://pypi.python.org/pypi/aiohttpLicenseaiothrottleis offered under the GPL v3 license.Documentationhttps://aiothrottle.readthedocs.org/Source codeThe latest developer version is available in a github repository:https://github.com/panda73111/aiothrottleUsageimportasyncioimportaiohttpimportaiothrottle@asyncio.coroutinedefload_file(url):response=yield fromaiohttp.request("GET",url)data=yield fromresponse.read()withopen("largefile.zip","wb")asfile:file.write(data)response.close()# setup the rate limit to 200 KB/saiothrottle.limit_rate(200*1024)# download a large file without blocking bandwidthloop=asyncio.get_event_loop()loop.run_until_complete(load_file("http://example.com/largefile.zip"))# unset the rate limitaiothrottle.unlimit_rate()TODOUpload rate limiting classGeneral socket limiting classCHANGES0.1.3 (30-08-2016)Set minimum required Python version to 3.4.2, the same as aiohttp 1.0.0Made aiothrottle compatible with current aiohttp version again
(Now using aiohttp.StreamReader._buffer_size)Catching RuntimeError when trying to pause a closing _SSLProtocolTransport0.1.2 (08-08-2015)Fixed resuming transport too oftenAdded ‘rate_limit’ and ‘throttling’ propertiesFixed buffer limit control0.1.1 (08-02-2015)Added limit_rate() and unlimit_rate() globally and response-wiseRaising ValueError on invalid rate limitCancelling _check_handle in Throttle’s destructor0.1.0 (08-01-2015)Initial release with basic throttling functionality
Package: aio-throttle
This library is inspired bythis bookand this implementationhttps://github.com/vostok/throttling.Features:Set capacity(max parallel requests) and queue(max queued requests) limits.Per-consumer limits. For instance, to not allow any consumer to use more than 70% of service's capacity.Per-request priorities. For instance, to not allow requests with lowest priority to be queued or to now allow requests with normal priority to use more than 90% of service's capacity.Example:fromaio_throttleimportThrottler,MaxFractionCapacityQuota,ThrottlePriority,ThrottleResultcapacity_limit=100queue_limit=200consumer_quotas=[MaxFractionCapacityQuota(0.7)]priority_quotas=[MaxFractionCapacityQuota(0.9,ThrottlePriority.NORMAL)]throttler=Throttler(capacity_limit,queue_limit,consumer_quotas,priority_quotas)consumer,priority="yet another consumer",ThrottlePriority.HIGHasyncwiththrottler.throttle(consumer=consumer,priority=priority)asresult:...# check if result is ThrottleResult.ACCEPTED or notExample of an integration with aiohttp and prometheus_client()importaiohttpimportaiohttp.webimportaiohttp.web_requestimportaiohttp.web_responseimportaio_throttle@aio_throttle.aiohttp_ignore()# do not throttle this handlerasyncdefhealthcheck(_:aiohttp.web_request.Request)->aiohttp.web_response.Response:returnaiohttp.web_response.Response()asyncdefauthorize(_:aiohttp.web_request.Request)->aiohttp.web_response.Response:returnaiohttp.web_response.Response()asyncdefcreate_app()->aiohttp.web.Application:app=aiohttp.web.Application(middlewares=[aio_throttle.aiohttp_middleware_factory(capacity_limit=20,queue_limit=100,consumer_quotas=[aio_throttle.MaxFractionCapacityQuota[str](0.7)],priority_quotas=[aio_throttle.MaxFractionCapacityQuota[aio_throttle.ThrottlePriority](0.9,aio_throttle.ThrottlePriority.NORMAL)],metrics_provider=aio_throttle.PROMETHEUS_METRICS_PROVIDER,),])app.router.add_get("/healthcheck",healthcheck)app.router.add_post("/authorize",authorize)returnappaiohttp.web.run_app(create_app(),port=8080,access_log=None)
Package: aiothrottler
aiothrottlerThrottler for asyncio PythonInstallationpipinstallaiothrottlerUsageCreate a sharedThrottler, passing a minimum interval, e.g.0.5secondsfromaiothrottlerimportThrottlerthrottler=Throttler(min_interval=0.5)and then just before the piece(s) of code to be throttled,callthis andawaitits result.awaitthrottler()# There will be a gap of at least 0.5 seconds# between executions reaching this lineExample: multiple tasks throttledimportasyncioimporttimefromaiothrottlerimportThrottlerasyncdefmain():throttler=Throttler(min_interval=0.5)awaitasyncio.gather(*[worker(throttler)for_inrange(10)])asyncdefworker(throttler):awaitthrottler()# Interval of at least 0.5 seconds between prints# even though all workers started togetherprint(time.time())loop=asyncio.get_event_loop()loop.run_until_complete(main())loop.close()Example: single task throttled/smoothedimportasyncioimportrandomimporttimefromaiothrottlerimportThrottlerasyncdefmain():throttler=Throttler(min_interval=0.5)for_inrange(10):awaitthrottler()# Interval of at least 0.5 seconds between prints# even though each sleep is randomprint(time.time())awaitasyncio.sleep(random.random())loop=asyncio.get_event_loop()loop.run_until_complete(main())loop.close()Differences to alternativesThe API features a function to call toawaitits result [some use a context manager]The API is imperative [some use a functional approach/higher-order function]No polling is used [some use polling internally]Aminimum interval between resolutionsis used to throttle [rather that amax resolutions per time interval, which can cause an irregular pattern of resolutions]The tests cover edge cases, such as asserting on throttling after tasks being throttled have been cancelled [some alternatives do not]
Package: aiothrottles
aiothrottlesaiothrottles synchronization primitives are designed to be extension toasyncio synchronization primitives.For more details, seeaiothrottles Documentation.UsageThrottle implements a rate limiting for asyncio task.
A throttle can be used to guarantee limited access to a shared resources.The preferred way to use a Throttle is anasync withstatement:throttle=Throttle('3/s')# ... laterasyncwiththrottle:# access shared statewhich is equivalent to:throttle=Throttle('3/s')# ... laterawaitthrottle.acquire()try:# access shared statefinally:throttle.release()A call rate is determined by therateargument.
Pass the rate in the following formats:"{integer limit}/{unit time}""{limit's numerator}/{limit's denominator}{unit time}"rateexamples:4/s,5/m,6/h,7/d1/second,2/minute,3/hour,4/day1/3s,12/37m,1/5h,8/3dInstallationpipinstallaiothrottlesorpythonsetup.pyinstallSupported Python VersionsPython 3.6, 3.7, 3.8 and 3.9 are supported.TestRun all tests.pythonsetup.pytestRun tests with PyTest.python-mpytest[-kTEST_NAME][-mMARKER]Licenseaiothrottlesis released under the BSD 3-Clause License.
Package: aio-throttle-to-next-second
aio-throttle-to-next-secondThrottler for asyncio Python that throttles to the next whole second, as reported bytime.time(). This is useful to force an order on requests to a service that uses a "latest timestamp wins" strategy, such as S3.Installationpipinstallaio-throttle-to-next-secondUsageCreate a sharedThrottler, with no argumentsfromaio_throttle_to_next_secondimportThrottlerthrottler=Throttler()and then just before the piece(s) of code to be throttled,callthis andawaitits result.awaitthrottler()# Each execution reaching this line will reach this line at a different secondExample: multiple tasks throttledimportasyncioimporttimefromaio_throttle_to_next_secondimportThrottlerasyncdefmain():throttler=Throttler()awaitasyncio.gather(*[worker(throttler)for_inrange(10)])asyncdefworker(throttler):awaitthrottler()# Each print will show a distinct second, though all workers started togetherprint(int(time.time()))loop=asyncio.get_event_loop()loop.run_until_complete(main())loop.close()Example: single task throttledimportasyncioimportrandomimporttimefromaio_throttle_to_next_secondimportThrottlerasyncdefmain():throttler=Throttler()for_inrange(10):awaitthrottler()# Each print will show a distinct second, though there is a random sleepprint(int(time.time()))awaitasyncio.sleep(random.random())loop=asyncio.get_event_loop()loop.run_until_complete(main())loop.close()
Package: aiotieba
安装pipinstallaiotieba尝试一下importasyncioimportaiotiebaasyncdefmain():asyncwithaiotieba.Client()asclient:threads=awaitclient.get_threads("天堂鸡汤")forthreadinthreads[3:6]:print(f"tid={thread.tid}text={thread.text}")asyncio.run(main())输出样例---
tid=8537603600 text=一人发一句最喜欢的游戏台词
楼主先来
很喜欢lol布隆说的“夜晚越黑暗，星星就越明亮”，尤其在当下这个有着诸多缺点的世界里，这句话让我感觉舒服了很多在人们已不再相信理想主义的至暗时刻，高擎炬火之人便显得更加重要，至少我会坚持我的理想
---
tid=8093410706 text=大概是剪切板里的一些有意思的话
今天看自己的剪切板快满了，稍微翻翻突然发现以前存的一些话还挺有意思，就放在这里啦
（咦，疑似水帖啊我）
---
tid=8537699088 text=记录一下自己人生第一次当“老师”的经历^_^
明天我带的孩子们就“毕业”了，第一次当老师我改变了很多也收获了很多，就想着给自己记录一下这段宝贵的经历:-)继续阅读入门教程项目特色收录数十个常用API类型注解全覆盖，方法注释全覆盖，类属性注释全覆盖，内部命名统一支持protobuf序列化请求参数支持websocket接口与官方版本高度一致的密码学实现友情链接TiebaManager（吧务管理器 有用户界面）TiebaLite（第三方安卓客户端 Archived）基于aiotieba的高弹性吧务审查框架贴吧protobuf定义文件合集（更新至12.51.7.1）特别鸣谢为本开源项目提供的免费产品授权
Package: aiotieba-reviewer
客户名单2024.02.24更新吧名关注量浏览量（30天平均）发帖量抗压背锅543152084402943940孙笑川5383418478024144280原神内鬼69151337550721945憨批7299215782347995lol半价2099998886803882新孙笑川971561210527381vtuber23216415166682元气骑士2841717691941天堂鸡汤39619767851626友情链接TiebaManager（吧务管理器 有用户界面）TiebaLite（第三方安卓客户端）贴吧protobuf定义文件合集
Package: aiotiktok
aiotiktokis super simple and fast library
to get all video data from TikTokSimple RequestimportasynciofromaiotiktokimportClienttiktok=Client()asyncdefmain():awaittiktok.get_data(url="some url")asyncio.run(main())SignatureFor use method user_feed_sig you must up your application.This must be done in order to be able to generate a signature for a request to the private TikTok apiFollow this instructionhttps://github.com/sheldygg/tiktok-signatureAfter you have run it, you must specify a reference when initializing the Client classfromaiotiktokimportClienttiktok=Client(signature_url="some url")By default ishttp://127.0.0.1:8002/signatureThen you can get user feedfromaiotiktokimportClienttiktok=Client()awaittiktok.user_feed_sig("playboicarti")
Package: aiotime
aiotimeAnasynciotest helper that allows you to deterministically control the event loop's internal clock in your tests, affecting the behavior of the following functions:asyncio.sleeploop.call_atloop.call_laterNote about behaviorIf you enter theaiotime.FastForwardcontext manager (as in thewithblock in the examples below), then theloopsupplied to its constructor will STOP triggering scheduled events, tasks or callbacks. Once you__enter__the context manager, you MUST call the returned object or the event loop will be stuck in time. Only when you__exit__the context manager will the loop return to normal behavior.(Using the same event loop with and withoutaiotimecontrol is not supported; there may be unexpected effects with scheduling at the margins.)Getting started# TODO Add to pypiControllingasyncio.sleeploop=asyncio.get_event_loop()# Try sleeping with normal loop behaviorstart=dt.datetime.now()sleep_task=asyncio.create_task(asyncio.sleep(0.25))awaitsleep_taskassertdt.datetime.now()-start>dt.timedelta(seconds=0.25)withaiotime.FastForward(loop)asff:# Try fast-forwarding through the sleepstart=dt.datetime.now()sleep_task=asyncio.create_task(asyncio.sleep(0.25))awaitff(1.5)# ff more than necessaryawaitsleep_taskassertdt.datetime.now()-start<dt.timedelta(seconds=0.05)Controllingloop.call_laterloop=asyncio.get_event_loop()withaiotime.FastForward(loop)asff:# Try call_later() with fast-forwardingstart=dt.datetime.now()event=asyncio.Event()deftest():event.set()loop.call_later(0.25,test)awaitff(1.5)# ff more than necessaryawaitasyncio.wait_for(event.wait(),2)# timeout just in caseassertdt.datetime.now()-start<dt.timedelta(seconds=0.05)# call_later() with normal loop behavior now, after context manager exitsstart=dt.datetime.now()event=asyncio.Event()deftest():event.set()loop.call_later(0.25,test)awaitasyncio.wait_for(event.wait(),1)# timeout just in caseassertdt.datetime.now()-start>dt.timedelta(seconds=0.25)
Package: aiotimeout
aiotimeoutTimeout context manager for asyncio PythonUsagefromaiotimeoutimporttimeout# Will raise an asyncio.TimeoutErrorwithtimeout(1):awaitasyncio.sleep(1.5)# Will not raise anythingwithtimeout(1):awaitasyncio.sleep(0.5)You can respond to a timeout fromoutsidethe context by catchingasyncio.TimeoutErrortry:withtimeout(1):awaitasyncio.sleep(1.5)print('This line is not reached')exceptasyncio.TimeoutError:print('Timed out')or you can respond to a timeout frominsidethe context by catchingasyncio.CancelledErrorand re-raising.try:withtimeout(1):try:awaitasyncio.sleep(1.5)exceptasyncio.CancelledErrorprint('Doing some cleanup')raiseexceptasyncio.TimeoutError:print('Timed out')Differences to alternativesasyncio.wait_fordoes not offer a context manager. In some cases a context manager is clearer.asyncio.wait_forcreates/uses an extra task. In some cases this is not necessary, and an extra task adds non-determinism in terms of sequence of operations.Clearer internal code [in the author's opinion]. Rather than a custom class,contextlib.contextmanageris used.
Package: aiotimer
AsyncIO compatible periodic timer. Linux only and very alpha API.ExampleThe timer is implemented as a straightforward protocol similar to how
the asyncio’s network protocols are handled:classMyTimer(aiotimer.Protocol):def__init__(self):self.counter=0deftimer_started(self,timer):self.timer=timerdeftimer_ticked(self):# Callback triggered when the timer interval elapses...deftimer_overrun(self):# Callback triggered if the timer_ticked callback runtime# should exceed the timer interval. Return True to# reschedule, otherwise the timer is aborted.returnTruedeferror_received():...The protocol can then be used to create a new timer:# Schedule once every 10th of a secondaiotimer.create_timer(MyTimer,0.1,loop=loop)
Package: aio-timers
aio-timersTiming utilities based onasyncio.Setuppip install aio-timersUsageimportasynciofromaio_timersimportTimerdefcallback(name):print("Hello{}!".format(name))# timer is scheduled heretimer=Timer(5,callback,callback_args=("World",))# wait until the callback has been executedloop=asyncio.get_event_loop()loop.run_until_complete(timer.wait())print("end")Output:(after 5 seconds)Hello World!endTimerCalls acallbackafterdelayseconds.The timer is executed as a task on an event loop.The callback is invoked:as a synchronous function if it is not a coroutine;with an await if it is a coroutine or thecallback_asyncflag is set toTrue.Any result returned by the callback is ignored.ConstructorTimer(delay, callback, callback_args=(), callback_kwargs={}, callback_async=False, *, loop=None)where:delay, seconds before thecallbackis executed;callback, the callback to execute afterdelaysecondscallback_args, (optional, default=()) positional arguments to pass tocallbackcallback_kwargs, (optional, default={}) keyword arguments to pass tocallbackcallback_async, (optional, default=False) ifTruethe callback will be executed on the event loop (await)loop, (optional, default=None) event loop where the delayed task will be scheduled (ifNonewill useasyncio.get_event_loop())NOTE: thecallback_asyncflag should be used when a coroutine is decorated (e.g., usingfunctools.partial).cancel()Cancels the execution of the callback.async .wait()Wait until the callback has been executed or its execution has been canceled.If the execution has been canceled, will raiseasyncio.CancelledError.
Package: aiotinydb
aiotinydbasyncio compatibility shim forTinyDBEnables usage of TinyDB in asyncio-aware contexts without slow syncronous IO.See documentation on compatible version ofTinyDB.Basically all API calls fromTinyDBare supported inAIOTinyDB. With the following exceptions: youshould notuse basicwithsyntax andclosefunctions. Instead, youshoulduseasync with.importasynciofromaiotinydbimportAIOTinyDBasyncdeftest():asyncwithAIOTinyDB('test.json')asdb:db.insert(dict(counter=1))loop=asyncio.new_event_loop()loop.run_until_complete(test())loop.close()CPU-bound operations likedb.search(),db.update()etc. are executed synchronously and may block the event loop under heavy load. Use multiprocessing if that's an issue (see#6andexamples/processpool.pyfor an example).MiddlewareAny middlewares you useshould beasync-aware. See example:fromtinydb.middlewaresimportCachingMiddlewareasVanillaCachingMiddlewarefromaiotinydb.middlewareimportAIOMiddlewareclassCachingMiddleware(VanillaCachingMiddleware,AIOMiddlewareMixin):"""Async-aware CachingMiddleware. For more info readdocstring for `tinydb.middlewares.CachingMiddleware`"""passIf middleware requires some special handling on entry and exit, override__aenter__and__aexit__.Concurrent database accessInstances ofAIOTinyDBsupport database access from multiple coroutines.Onunix-like systems, it's also possible to access one database concurrently from multiple processes when usingAIOJSONStorage(the default) orAIOImmutableJSONStorage.Installationpip install aiotinydb