Saravanan666/pypi-org huggingface dataset:
Package: asyncakinator
An async API wrapper for the online game, Akinator, written in Python.Akinatoris a web-based game which tries to determine what character you are thinking of by asking a series of questions.InstallingTo install, just run the following command:# MacOS/Linuxpython3-mpipinstall-Uasyncakinator# Windowspy-3-mpipinstall-UasyncakinatorRequirementsPython ≥3.9aiohttpDocumentationDocumention can be foundhere.Quick ExamplesHere’s a quick little example of the library being used to make a simple, text-based Akinator game:importasynciofromasyncakinatorimport(Akinator,Answer,CanNotGoBack,InvalidAnswer,Language,NoMoreQuestions,Theme)game=Akinator(language=Language.ENGLISH,theme=Theme.ANIMALS,)asyncdefmain():question=awaitgame.start()whilegame.progression<=80:print(question)user_input=input("Answer:  ")try:answer=Answer.from_str(user_input)exceptInvalidAnswer:print("Invalid answer")continuetry:question=awaitgame.answer(answer)exceptCanNotGoBack:print("This is the first question, you can't go back.")continueexceptNoMoreQuestions:breakawaitgame.win()correct=input(f"You are thinking of{game.first_guess.name}({game.first_guess.description}). "f"Am I correct?\n{game.first_guess.absolute_picture_path}\n---\nAnswer:  ")ifAnswer.from_str(correct)==Answer.YES:print("Nice.")else:print("Maybe next time.")awaitgame.close()asyncio.run(main())
Package: asyncakumuli
Welcome toAsyncAkumuli!This library contains a small async wrapper for submission of data to,
and (rudimentary) reading from,Akumuli.Also included:A basic unit testTest scaffolding, to easily test your own codea utility to read the last timestamp, as Akumuli doesn’t go backwardshelper code to interpred RRD / collectd input so that you can feed those
to Akumulia couple of example scriptsTests and collectd support currently require Trio because (a) anyio doesn’t
support subprocesses, (b) UDP socket support in anyio is kindof limited.
Package: asyncalchemy
AsyncAlchemyA thin async wrapper forSQLAlchemysessions.Besides being async, the wrapper manages the context of the session for the execution block.Commits incoming changes if successfull or rolls back changes if an exceptions occurs.Note: The upcoming SQLAlchemy 1.4 version will include built-in async functionality, it's recommended to upgrade to it once it'sreleased.InstallPippipinstallasyncalchemyFrom SourceThe project usespoetryfor dependency management and packaging.To run from source clone project and:pipinstallpoetry
poetryinstallUsageBasic Examplefromasyncalchemyimportcreate_session_factory# Create AsyncAlchemy session factorysession_factory=create_session_factory(db_uri,Base)# Create sessionasyncwithsession_factory()assession:awaitsession.query(Something).filter_by(something="else")Example With Extra Paramsfromsqlalchemy.poolimportNullPoolfromasyncalchemyimportcreate_session_factory# Create session factory with additional SQLAlchemy paramssession_factory=create_session_factory(db_uri,Base,poolclass=NullPool)# Create sessionasyncwithsession_factory()assession:awaitsecond_session.add(Something)awaitsecond_session.flush()# Reuse sessionasyncwithsession_factory(reuse_session=session)assecond_session:awaitsession.delete(Something)
Package: asyncall
# asyncall  – 更加简单方便的异步调用方式# 特性
1. 支持 python2 和 python3
2. 更加方便的异步调用方式
3. 支持惰性获取结果# 用法` >>> import asyncio >>> import asyncall >>> async def demo(para): ...     await asyncio.sleep(1) ...     return para ... >>> paras = ['A', 'B', 'C'] >>> res = asyncall.task_map(paras, async_func=demo) >>> >>> res ['A', 'B', 'C'] `详见 tests/test_async.py# 注意
1. python2 需要安装相关第三方库（requirements.txt）
Package: asyncamqp
Asyncamqp is a little extension to aioamqp based on the ideas from this
pull request (https://github.com/Polyconseil/aioamqp/pull/118). The changes
here get rid of the callbacks stuff.InstallInstall it using pip$pipinstallasyncamqpUsageTo publish stuff, just do the same as you would do with aioamqp:awaitchannel.basic_publish(payload='hi there!',exchange_name='',routing_key='my-rt')To consume stuff, you don’t need to use callbacks anymore.asyncwithchannel.basic_consume(queue_name='my-queue',exchange_name='',routing_key='my-queue')asconsumer:asyncformsginconsumer:print(msg.body)Consuming messages this way we always wait for a new message to arrive in the
queue. We can use a timeout in milliseconds for it, too:# now we pass the timeout argumentasyncwithchannel.basic_consume(queue_name='my-queue',exchange_name='',routing_key='my-queue',timeout=100)asconsumer:asyncformsginconsumer:print(msg.body)Or we could simply consume the messages already in the queue and stop
consuming stuff when we have no more messages:# now we pass the wait_message argument.asyncwithchannel.basic_consume(queue_name='my-queue',exchange_name='',routing_key='my-queue',wait_message=False)asconsumer:asyncformsginconsumer:print(msg.body)As it is a simple extension to aioamqp, please refer to theaioamqp’s docsfor full information. Just remember that when consuming it you don’t use
callbacks but the context manager/async for stuff.
Package: async-amqp
async_amqpTheasync_amqplibrary is a pure-Python implementation of theAMQP 0.9.1 protocol.Built on top ofanyio, it provides an API based on coroutines, making it easy to write highly concurrent applications.Bug reports, patches and suggestions welcome! Just open anissueor send apull request.StatusThe code works. Porting code that uses aioamqp (or even plain
python-amqp) should be reasonably straightforward.All tests from aioamqp have been ported and succeed.async_amqpwas renamed fromasyncamqp, but that was taken on pypi.asyncamqpwas renamed fromtrio_amqpbut anyio support was deemed to be a good
idea.trio_amqpin turn was forked fromaioamqp.testsTo run the tests, you’ll need to install the Python test dependencies:pip install -r ci/requirements_dev.txtTests require an instance of RabbitMQ. You can start a new instance using docker:docker run -d --log-driver=syslog -e RABBITMQ_NODENAME=my-rabbit --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3-managementRabbitMQ requires a “guest” user (password “guest”) with admin privileges.You can run the tests withmake test(requirespytest).tests using docker-composeStart RabbitMQ usingdocker-composeup-drabbitmq. When RabbitMQ has started, start the tests usingdocker-composeup--buildaioamqp-testFuture workAdd coverage reporting. Increase coverage (duh).Try restarting a failed AMQP connection instead of cancelling everything.
Package: asyncapi-sphinx-ext
This extension adds some directives to integrate documentation for your pub-sub
application usingasyncapispecification.You can useasyncapispecifications in your source code doc string or in your
documentation to generate a beautiful documentation plus overview. Further the
specification might be used for other things as well (not supported yet).WarningThis is still in a early stage.InstallationInstall the sphinx extension withpip install asyncapi_sphinx_ext.UsageThe extension adds two directivesasyncapi_channelsandasyncapi_overview.Theasyncapi_channelsdirective is used to add the some pub/sub documentation
and theasyncapi_overviewis used to create a table with the all the pub/sub
topics defined.For a full example checkoutusage_example.Important Linkssource:https://github.com/mortbauer/asyncapi-sphinx-extdocumentation:https://asyncapi-sphinx-ext.readthedocs.org/en/latest/pypi:https://pypi.org/project/asyncapi-sphinx-ext/
Package: asyncapp
Simple object-oriented asynchronous application wrapper.Author: Marcin BorowiczContact: marcinbor85 at gmail comDate: 2018/01/14Version: 0.1.0License: MITMain featuresBased on standard “asyncio” libraryPython3 compatibleSimplified and robust stopping of coroutinesNo warnings during application stopping (a common newbies issue)Downloadhttps://pypi.python.org/pypi/asyncapphttps://github.com/marcinbor85/asyncappInstallInstall using pip (no separate download required):pip install asyncappInstall from sources:python setup.py installSource codeSource code on GitHub:https://github.com/marcinbor85/asyncappGet code with git:git clonehttps://github.com/marcinbor85/asyncapp.git
Package: async-app
Key FeaturesService-oriented application layoutIntegrate different asyncio libraries with easetyping-friendlyConfig that can enforce types (viatypeguardorpytypes)Installationpip install async_apppip install async_app[typeguard]to enforce Config’s types withtypeguard.pip install async_app[pytypes]to enforce Config’s types withpytypes.Developmentrequirements.txt lists all dependencies needed to run tests and generate reports.CI tests each change against latest release of CPython 3 (Windows and macOS) as well as dev (macOS and Ubuntu)
and nightly builds (Ubuntu).
Tests are run against both pytypes and typeguard. Combined coverage is uploaded to PyPI.
See.travis.yml,.appveyor.ymlandsetup.cfgfor the detailed configuration.
Package: async_armor
info:Graceful drop-in replacement for asyncio.shieldInstallationpipinstallasync_armorUsageimportasynciofromasync_armorimportarmorcalls=0asyncdefcall_shield():globalcallsawaitasyncio.sleep(1)calls+=1@armorasyncdefcall_deco():globalcallsawaitasyncio.sleep(1)calls+=1asyncdefmain():task=armor(call_shield())task.cancel()task=asyncio.ensure_future(call_deco())task.cancel()loop=asyncio.get_event_loop()loop.run_until_complete(main())armor.close()loop.run_until_complete(armor.wait_closed())assertcalls==2loop.close()Python 3.3+ is required
Package: async-asgi-testclient
async-asgi-testclientAsync ASGI TestClient is a library for testing web applications that implements ASGI specification (version 2 and 3).The motivation behind this project is building a common testing library that doesn't depend on the web framework (Quart,Startlette, ...).It works by calling the ASGI app directly. This avoids the need to run the app with a http server in a different process/thread/asyncio-loop. Since the app and test run in the same asyncio loop, it's easier to write tests and debug code.This library is based on the testing module provided inQuart.QuickstartRequirements: Python 3.6+Installation:pipinstallasync-asgi-testclientUsagemy_api.py:fromquartimportQuart,jsonifyapp=Quart(__name__)@app.route("/")asyncdefroot():return"plain response"@app.route("/json")asyncdefjson():returnjsonify({"hello":"world"})if__name__=='__main__':app.run()test_app.py:fromasync_asgi_testclientimportTestClientimportpytest@pytest.mark.asyncioasyncdeftest_quart_app():from.my_apiimportappasyncwithTestClient(app)asclient:resp=awaitclient.get("/")assertresp.status_code==200assertresp.text=="plain response"resp=awaitclient.get("/json")assertresp.status_code==200assertresp.json()=={"hello":"world"}Supportscookiesmultipart/form-datafollow redirectsresponse streamsrequest streamswebsocket support
Package: asyncbasehttp
Async Http ServerThe simplest async python http server library.Exampleimport asyncio
from asyncbasehttp import request_handler, Request, Response

@request_handler
async def handle_request(req: Request):
    return Response.create_ok_response(f'You requested path: {req.path}'.encode())


async def main():
    server = await asyncio.start_server(handle_request, port=8000)
    print("http://localhost:8000")
    await server.serve_forever()

asyncio.run(main())
Package: async-batcher
Async BatcherThis project provides a Python library to batch the asynchronous requests and handle them in batches.How to useTo use the library, you need to install the package in your environment. You can install the package using pip:pipinstallasync-batcherThen, you can create a newAsyncBatcherclass by implementing theprocess_batchmethod:fromasync_batcher.batcherimportAsyncBatcherclassMyAsyncBatcher(AsyncBatcher):asyncdefprocess_batch(self,batch):# Process the batchprint(batch)# Create a new instance of the `MyAsyncBatcher` classasync_batcher=MyAsyncBatcher(batch_size=20)async_batcher.start()BenchmarkTo evaluate the performance of theAsyncBatcherlibrary, we used theKeras examplewithlocustto simulate multiple users making requests to the server.In this example, we have a tensorflow model that takes ~11ms to make a single prediction and ~13ms to process
a batch of 200 predictions.For this benchmark, we ran the FastAPI server with Uvicorn with 12 workers,
on a MacBook Pro with Apple M2 Max chip (12 cores).Predict endpoint:Optimized Predict endpoint:As we can see from the graphs, for the/predictendpoint, the failure rate started to increase linearly at the RPS
of ~284 requests/second, and the 95th percentile response time was ~1100ms at this point. Then with the increase of
the RPS, the number of successful requests was ~130 requests/second in average, with a high failure rate
(~300 from ~400 requests/second).For the/optimized_predictendpoint, the failure was smaller than 3 requests/second (0.00625%) during the whole test,
the average response time was increasing slightly with the increase of the RPS, and it reached ~120ms in average at
the end of the test (> 480 requests/second), with a 95th percentile response time almost stable and smaller than 500ms.You can find check the reports for more details:predict__report.htmloptimized_predict__report.htmlUse casesTheAsyncBatcherlibrary can be used in any application that needs to handle asynchronous requests in batches,
such as:Serving machine learning models that optimize the batch processing (e.g. TensorFlow, PyTorch, Scikit-learn, etc.)Storing multiple records in a database in a single query to optimize the I/O operations (or to reduce the cost of the
database operations, e.g. AWS DynamoDB)Sending multiple messages in a single request to optimize the network operations (or to reduce the cost of the network
operations, e.g. Kafka, RabbitMQ, AWS SQS, AWS SNS, etc.)
Package: asyncbg
Asyncio background tasksAsyncio background tasks in Python 3.7 and later.Run CPU intensive long running tasks without blocking the asyncio
loop, implemented as a lightweight asyncio layer on top of the
multiprocessing module.Alternatively run tasks in other threads.Project homepage:https://github.com/eerimoq/asyncbgDocumentation:https://asyncbg.readthedocs.org/en/latestInstallationpipinstallasyncbgExamplesThere are more examples in theexamples folder.CallCallwork(a, b)in another process. The script output isResult: 9.importasyncioimportasyncbgdefwork(a,b):returna+basyncdefmain():result=awaitasyncbg.call(work,4,5)print(f'Result:{result}')asyncio.run(main())Process poolCreate a process pool with two workers, and callwork()three
times in it (up to two callbacks called in parallel).importasyncioimportasyncbgdefwork():passasyncdefmain():withasyncbg.ProcessPoolExecutor(max_workers=2)aspool:awaitasyncio.gather(pool.call(work),pool.call(work),pool.call(work))asyncio.run(main())Call threadCallwork(a, b)in another thread. The script output isResult: 9.importasyncioimportasyncbgdefwork(a,b):returna+basyncdefmain():result=awaitasyncbg.call_thread(work,4,5)print(f'Result:{result}')asyncio.run(main())Thread poolCreate a thread pool with two workers, and callwork()three times
in it (up to two callbacks called in parallel).importasyncioimportasyncbgdefwork():passasyncdefmain():withasyncbg.ThreadPoolExecutor(max_workers=2)aspool:awaitasyncio.gather(pool.call(work),pool.call(work),pool.call(work))asyncio.run(main())
Package: asyncbing
AsyncBingasyncbing is an asyncio api wrapper for theBing Search Api. It uses a modernasync/awaitpython api.DocsInstallingpython -m pip install asyncbingFor the stable version of asyncbing.python -m pip install git+https://github.com/TennisBowling/asyncbing/For the unstable/cutting edge of asyncbing. Not recommended in production. \UsageImport it withfrom asyncbing import searchThen initialize asyncbing with your Bing Search Api keyguidelikes = search.Search('APIKEYGOESHERE')Sample usageSearchingimportasyncbingimportasyncioasyncdefmain():asyncwithasyncbing.tearch('key')ass:resp=awaits.fetch('cool search term')print(resp.matches)oneresult=resp.getOne()print(oneresult.name)print(oneresult.url)print(oneresult.snippet)asyncio.run(main())Translatingimportasyncbingimportasyncioasyncdefmain():asyncwithasyncbing.translate('key',region='useast')ast:resp=awaitt.translate('je veux traduire')print(resp.detected_language)print(resp.translated_output)print(resp.translated_language)asyncio.run(main())(Normally, searching isn't part of the Bing Api's. It's part of the Microsoft Cognitive Api's. Might as well rename this to asyncms, or asyncmsapi, no?)
Package: async-bioservices
Async BioservicesDescriptionasync_bioservicesis a utility package forCOMO. Its purpose is to provie true
asynchronous access to theBioservicespackage. This is done by
wrapping the synchronous functions inasynciotasks. Currently, the only function this package provides is a wrapper
around thedb2dbfunction in Bioservices.InstallationTo installasync_bioservices, you can use pip:pipinstallasync_bioservicesUsageTo useasync_bioservices, simply import thefetch_gene_infofunction and call it with the relevant parametersfromasync_bioservices.fetchimportfetch_gene_infofromasync_bioservices.input_databaseimportInputDatabasefromasync_bioservices.output_databaseimportOutputDatabasefromasync_bioservices.taxon_idimportTaxonIDfetch_gene_info(input_values=["1","2","3"],input_db=InputDatabase.GENE_ID,output_db=OutputDatabase.GENE_SYMBOL,taxon_id=TaxonID.HOMO_SAPIENS)ParametersParameterTypeRequired?Default ValueDescriptioninput_valueslist[str]YesN/AThe input values to convertinput_dbInputDatabaseYesN/AThe input typeoutput_dbOutputDatabaseorlist[OutputDatabase]Notuple(OutputDatabase.GENE_SYMBOL.value,OutputDatabase.GENE_ID.value, OutputDatabase.CHROMOSOMAL_LOCATION.valueThe type to returntaxon_idTaxonIDorintNoTaxonID.HOMO_SAPIENS(9606)The taxonomy of the input typequietboolNoFalseShould all output be suppressed?remove_duplicatesboolNoFalseShould duplicates be removed from the returned dataframe?cacheboolNoTrueShould cache be used?delayintNo5How long of a delay should be enforced if the API is accessed to quickly?concurrencyintNo8(max 20)How many concurrent requests can be made at once?batch_lengthintNo300(max 500 iftaxon_idisTaxonID.HOMO_SAPIENS)How many items should be converted at once?Returnsasync_bioservicesreturns a dataframe with the input and output databases as column names. The index of the dataframe
has been reset, starting at 0An example dataframe is seen belowIndexGene IDGene Symbol00-11A1BG22A2M33A2MP144-
Package: asyncblink
AsyncBlink is a small extention to Blinker and enables you to use
coroutines as receivers for your signals.InstallInstallation is simple, via pip:$pipinstallasyncblinkUsageUsage is simple, too. Create a signal, connect some receivers to it
and then use thesend()method to trigger all receiversfromasyncblinkimportsignalmy_signal=signal('nice-signal')asyncdefcoro_receiver(sender,**kwargs):# an expensive io operation herereturn'done'defreceiver(sender):return'ok'my_signal.connect(coro_receiver)my_signal.connect(receiver)my_signal.send('some-sender')Other than that, AsyncBlink's usage is the same as Blinker, Take a look at the
`Blinker documentationfor further
information.Why this still exists?Blinker now supports coroutines viasignal.async_send, so why asyncblink
is still alive?The blinker's implementation awaits for coroutines and it is not what I want
so asyncblink schedules the coroutine and returns a task.Source CodeSource code is hosted ongithub.
Package: async-blp
async_blpOverviewThe goal ofasync_blpis to create simple and fast Bloomberg Open API wrapper that can be used in highload environments.
It allows asynchronous processing of hundreds of
Bloomberg request simultaneously. Currentlyasync_blpprovides support for reference and historical data,
instruments lookup and field search, as well as subscriptions.
More request types will be added in the future.FeaturesFast. Usingasyncioallows to process Bloomberg requests simultaneously while creating little overheadSimple.async_blptakes care of creating and managing Bloomberg sessions as well as of parsing responsesUser-friendly output. Data is returned as apandas.DataFrameobjectError handling. Security and field errors are returned in a separate object that can be easily inspectedInstallationYou can install async_blp from PyPI usingpip install async_blpRequirementsPython 3.7+PandasBloomberg C++ SDK version 3.12.1+Bloomberg API for Python (more info here:https://www.bloomberg.com/professional/support/api-library/)python -m pip install --index-url=https://bloomberg.bintray.com/pip/simple blpapiDocumentationhttps://async-blp.readthedocs.io/en/latest/ExamplesBefore usingasync_blp, installblpapifrom the link above and login in the Bloomberg Terminal.importasync_blpasyncdefblp_example(loop):bloomberg=async_blp.AsyncBloomberg(loop=loop)data,_=awaitbloomberg.get_reference_data(['F US Equity'],['LAST_PRICE'])# it is important to wait until Bloomberg successfully closes all the sessionsawaitbloomberg.stop()returndataMore examples can be found here:https://github.com/rockscie/async_blp/tree/master/examples
Package: async-bot-api-adapters
This package allows to interact with vk and telegram API using the same
interface.It’s main purpose is to simply switch 🕹 between services while
developing bots.SetupFirstly you should export environment variables. Create.envfile
and fill vars:TELEGRAM_TOKEN=telegram_token
VK_TOKEN=vk_tokenExampleUpload Images to vk and tg.importasyncioimportaiofilesfromadapters.factoryimportcreate_adapterfromadapters.enumsimportAdapterTypefromdotenvimportload_dotenvload_dotenv()tg_adapter=create_adapter(adapter_type=AdapterType.TELEGRAM)vk_adapter=create_adapter(adapter_type=AdapterType.VK)asyncdefmain():asyncwithaiofiles.open('test.png',mode='rb')asdata:content=awaitdata.read()awaitasyncio.gather(*[tg_adapter.send_image(chat_id=-195789610,image=content),vk_adapter.send_image(chat_id=2000000006,image=content)])asyncio.run(main())
Package: asyncbots
This library provides a simpleasynciobased interface for writingRTM<https://api.slack.com/rtm>bots for Slack. Many distinct functions can be run through a single Slack bot plugin, triggered by user defined commands (e.g.!myCommand).ExampleA bot which can be triggered by the message!greet Guidolooks like this:fromasyncbots.botimportSlackBot,registerfromasyncbots.commandimportMessageCommandfrompyparsingimportalphas,WordclassMyBot(SlackBot)def__init__(self):self.name='My Bot'# Match 'greet' followed by any wordself.expr='greet'+Word(alphas).setResultsName('user')@register()asyncdefhandler(self,sender,channel,parsed_message):returnMessageCommand('Hello '+parsed_message['user'])
Package: async-cache
info:A caching solution for asyncioInstallationpipinstallasync-cacheBasic Usage# LRU CachefromcacheimportAsyncLRU@AsyncLRU(maxsize=128)asyncdeffunc(*args,**kwargs):"""
    maxsize : max number of results that are cached.
              if  max limit  is reached the oldest result  is deleted.
    """pass# TTL CachefromcacheimportAsyncTTL@AsyncTTL(time_to_live=60,maxsize=1024)asyncdeffunc(*args,**kwargs):"""
    time_to_live : max time for which a cached result  is valid
    maxsize : max number of results that are cached.
              if  max limit  is reached the oldest result  is deleted.
    """pass# Supports primitive as well as non-primitive function parameter.# Currently TTL & LRU cache is supported.Advanced UsageclassCustomDataClass:id:intvalue:intfromcacheimportAsyncLRU@AsyncLRU(maxsize=128)asyncdeffunc(model:"CustomDataClass"):...# function logic...# async-cache will work even if function parameters are:#   1. orm objects#   2. request object#   3. any other custom object type.
Package: async-cached
Caching decorator for async functionsThis is a replacement for@cached()decorator fromcachetools.cachetoolsdoes not support async at the time of writing.Installationpip install async-cachedExamplefrom cachetools import LRUCache
    from asynccached import asynccached

    
    _cache = LRUCache(maxsize=1)


    @asynccached(cache=_cache, key=lambda arg: arg)
    async def func(arg):
        pass