Saravanan666/pypi-org huggingface dataset:
Package: async-caches
Async CachesCaching library reimplementingdjango.core.cacheAPIwith async support and type hints, inspired byencode/databases.Currently three cache backends are available:dummy- Dummy cache backend that doesn't cache anything. Used to disable caching in tests!locmem- Cache backend that stores data in local memory. Lets you develop and test caching without need for actual cache server.redis- Redis cache intended for use in actual deployments.Requirements:Python 3.6+Documentation:https://rafalp.github.io/async-caches/Installation$pipinstallasync-cachesContributingContributions are welcome!If you've found a bug, got idea, question or just want to share the love, openGitHub issueor pull request!Credits and licenseThis is free software and you are welcome to modify and redistribute it under the conditions described in the license. For the complete license, refer to the LICENSE file.Parts of software come fromdatabasespackage developed by Tom Christie and contributors and fromDjangopackage developed by Django project maintainers and contributors.
Package: async-cache-updater
Async Cache UpdaterCaches the output of functions with time-based bucketsFree software: MIT licenseDocumentation:https://async-cache-updater.readthedocs.io.FeaturesTODOCreditsThis package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.History0.1.5 (2021-12-15)Add disabled setting0.1.4 (2021-09-21)Fix aioredis client0.1.3 (2021-09-21)Fix aioredis client0.1.2 (2021-09-14)Fix cache get_many0.1.1 (2021-09-01)Fix README0.1.0 (2021-08-28)First release on PyPI.
Package: async-call
Call====.. image:: https://api.codacy.com/project/badge/Grade/91959f98ff34469884415e96ba2ff763    :target: https://www.codacy.com/app/solarliner/call?utm_source=gitlab.com&amp;utm_medium=referral&amp;utm_content=solarliner/call&amp;utm_campaign=Badge_GradeThread-based, JS-like asynchronous calls for Python. Works in bothPython 2.7 and Python 3.5+.Install-------Release version:.. code:: bashpip install callDevelopment version.. code:: bashgit clone https://gitlab.com/solarliner/call.gitcd call# Activate virtualenv if neededpython setup.py installThe library requires no other dependencies, and (will soon) supportPython's ``await`` keyword.Use---Create a call:.. code:: pythondef cb(resolve, reject):result = factorial(100)resolve(result)call = Call(cb)Wrap a synchronous function in a Call:.. code:: pythoncall = Call.from_function(factorial, 10)Chain calls with the ``then`` keyword.. code:: pythoncall = Call(cb).then(lambda val: print(val))Catch errors:.. code:: pythoncall = Call(cb)\.then(lambda val: raise Exception())\.catch(lambda err: print('Whoops'))Compose calls:.. code:: pythonresults = Call.all([Call(cb) for _ in range(10)])Block thread until resolved (or raises on failure):.. code:: pythonresult = call.wait()Wait for call to either resolve or reject. Note that it is not recommended to get the data directly, as it may be``None``, which may or may not indicate that an error has occurred... code:: pythoncall.join()result = call.data  # Not recommendedContribute----------The repository follows the ``git flow`` standards. Create a feature branch, then ask for a pull/merge request.The main repository is on GitLab, however the GitHub mirror is functional and you should be able to ask for pullrequests. However, they will be processed in GitLab.
Package: async-casbin-sqlmodel-adapter
Async SQLModel Adapter for PyCasbinRepoGitHubPyPIAsync SQLModel Adapter is theSQLModeladapter forPyCasbin. With this library, Casbin can load policy from SQLModel supported database or save policy to it.Based onOfficially Supported Databases, The current supported databases are:PostgreSQLMySQLSQLiteInstallationpip install async_casbin_sqlmodel_adapterorpoetry add async-casbin-sqlmodel-adapterSimple Example# Stdlib:importasyncio# Thirdparty:importcasbinfromasync_casbin_sqlmodel_adapterimportAdapterfromsqlalchemy.ext.asyncioimportcreate_async_enginefromsqlmodelimportField,SQLModelengine=create_async_engine("sqlite+aiosqlite:///")classCasbinRule(SQLModel,table=True):# type: ignore"""CasbinRule class for SQLModel-based Casbin adapter."""__tablename__="casbin_rule"id:int=Field(primary_key=True)ptype:str=Field(max_length=255)v0:str=Field(max_length=255)v1:str=Field(max_length=255)v2:str|None=Field(max_length=255,default=None)v3:str|None=Field(max_length=255,default=None)v4:str|None=Field(max_length=255,default=None)v5:str|None=Field(max_length=255,default=None)def__str__(self)->str:arr=[self.ptype]# pylint: disable=invalid-nameforvin(self.v0,self.v1,self.v2,self.v3,self.v4,self.v5):ifvisNone:breakarr.append(v)return", ".join(arr)def__repr__(self)->str:returnf'<CasbinRule{self.id}: "{str(self)}">'asyncdefmain():asyncwithengine.begin()asconn:awaitconn.run_sync(SQLModel.metadata.create_all)adapter=Adapter(engine)e=casbin.AsyncEnforcer("path/to/model.conf",adapter,True)sub="alice"# the user that wants to access a resource.obj="data1"# the resource that is going to be accessed.act="read"# the operation that the user performs on the resource.ife.enforce(sub,obj,act):# permit alice to read data1async_casbin_sqlmodel_adapterpasselse:# deny the request, show an errorpassasyncio.run(main())Getting HelpPyCasbinLicenseThis project is licensed under theApache 2.0 license.
Package: async-cb-rate
async-cb-rateАсинхронная библиотека для парсинга курса валют с сайта ЦБ РФ.Библиотеку можно использовать для:мониторинга за курсом валютпостроения графиков изменения курсаУстановка c pippipinstallasync-cb-rateКраткий обзор функциональностиБиблиотека позволяет получить курс валюты на любой день. По умолчанию курс ищется на сегодняшний день.Функции возвращают объектыCurrency, с которыми удобно далее работать.importasynciofromasync_cb_rate.parserimportget_rate,get_codes,get_all_ratesasyncdefmain():usd_rate=awaitget_rate("USD")print(f"USD rate for today={usd_rate.price}₽")# USD rate for today=55.2987₽euro_rate=awaitget_rate("EUR")# EUR rate for today=52.7379₽print(f"EUR rate for today={euro_rate.price}₽")codes=awaitget_codes()print(f"Available codes:{codes}")# ['AUD', 'AZN', 'GBP', 'AMD', 'BYN', 'BGN', 'BRL', 'HUF', 'HKD', 'DKK', 'USD',# 'EUR', 'INR', 'KZT', 'CAD', 'KGS', 'CNY', 'MDL', 'NOK', 'PLN', 'RON', 'XDR', 'SGD', 'TJS', 'TRY', 'TMT', 'UZS',# 'UAH', 'CZK', 'SEK', 'CHF', 'ZAR', 'KRW', 'JPY']all_rates=awaitget_all_rates()print(f"All rates for today:{all_rates}")# [Currency(name='Австралийский доллар', code='AUD', price=35.9552,# date=datetime.datetime(2022, 10, 3, 23, 45, 29, 145779)), ...]asyncio.run(main())Доступные асинхронные функции библиотеки:get_codes(date)- получить все доступные коды валют на определённую дату:codes = await get_codes()  # Коды валютget_rate(code, date)- получить курс определённой валюты по её коду на определённую дату:usd_rate = await get_rate("USD")  # Курс доллара на сегодняget_all_rates(date)- получить курс всех доступных валют от ЦБ на определённую дату:all_rates = await get_all_rates()  # Все курсы валют на сегодня! По умолчанию поле date - это сегодня.Ошибки, которые можно получить при работе с библиотекой:NoValidDateError- функция была вызвана с датой, которая ещё не наступила.CurrencyRateNotFoundError- курс для данного кода валюты не найден.
Package: asyncchain
asyncchainSmall python library to allow "async chaining"UsageimportasynciofromasyncchainimportChainMetaclassTarget(metaclass=ChainMeta):asyncdeffirst(self):print("first")asyncdefsecond(self):print("second")asyncdefmain():my_target=Target()awaitmy_target.first().second()if__name__=="__main__":asyncio.run(main())
Package: async-chain
async-chainA coroutine builderWhat?Have you ever felt that theawaitsyntax in Python was a bit clunky when chaining multiple methods together?asyncdefon_message(event):message=awaitevent.get_message()author=awaitmessage.get_author()awaitauthor.send_message("Hello world!")Or even worse:asyncdefon_message(event):(await(await(awaitevent.get_message()).get_author()).send_message("Hello world!"))async-chainis here to solve your problem!asyncdefon_message(event):awaitevent.get_message().get_author().send_message("Hello world!")How?First, installasync_chainwith your favorite package manager:$pipinstallasync_chain$pipenvinstallasync_chain$poetryaddasync_chainThen, add the@async_chain.methoddecorator to any async method you wish to make chainable, and the problem will be
magically solved!importasync_chainclassMyEvent:@async_chain.methodasyncdefget_message(self):...
Package: async-class
async-classAdding abillity to write classes with awaitable initialization function.Table of contentsasync-classUsage exampleDocumentationClassAsyncClassClassAsyncObjectClassTaskStoreUsage exampleimportasynciofromasync_classimportAsyncClass,AsyncObject,task,linkclassMyAsyncClass(AsyncClass):asyncdef__ainit__(self):# Do async staff herepassclassMainClass(AsyncObject):asyncdef__ainit__(self):# Do async staff herepassasyncdef__adel__(self):""" This method will be called when object will be closed """passclassRelatedClass(AsyncObject):asyncdef__ainit__(self,parent:MainClass):link(self,parent)asyncdefmain():instance=awaitMyAsyncClass()print(instance)main_instance=awaitMainClass()related_instance=awaitRelatedClass(main_instance)assertnotmain_instance.is_closedassertnotrelated_instance.is_closedawaitmain_instance.close()assertmain_instance.is_closed# will be closed because linked to closed main_instanceassertrelated_instance.is_closedasyncio.run(main())DocumentationAsync objects might be created when no one event loop has been running.self.loopproperty is lazily evaluated.Module provides useful abstractions for writing async code.Objects inherited fromAsyncClassmight have their own__init__method, but it strictly not recommend.ClassAsyncClassIs a base wrapper with metaclass has noTaskStoreinstance and
additional methods likeself.create_taskandself.create_future.This class just solves the initialization problem:importasynciofromasync_classimportAsyncClassclassMyAsyncClass(AsyncClass):asyncdef__ainit__(self):future=self.loop.create_future()self.loop.call_soon(future.set_result,True)awaitfutureasyncdefmain():instance=awaitMyAsyncClass()print(instance)asyncio.run(main())ClassAsyncObjectBase class with task store instance and helpers for simple task
management.importasynciofromasync_classimportAsyncObjectclassMyClass(AsyncObject):asyncdef__ainit__(self):self.task=self.create_task(asyncio.sleep(3600))asyncdefmain():obj=awaitMyClass()assertnotobj.task.done()awaitobj.close()assertobj.task.done()asyncio.run(main())ClassTaskStoreTaskStoreis a task management helper. One instance hascreate_task()andcreate_future()methods and all created
entities will be destroyed whenTaskStorewill be closed viaclose()method.Also, a task store might create a linked copy of the self, which will be
closed when the parent instance will be closed.importasynciofromasync_classimportTaskStoreasyncdefmain():store=TaskStore(asyncio.get_event_loop())task1=store.create_task(asyncio.sleep(3600))child_store=store.get_child()task2=child_store.create_task(asyncio.sleep(3600))awaitstore.close()asserttask1.done()andtask2.done()asyncio.run(main())
Package: async-cleverbot
async_cleverbotAsyncio API wrapper for the Travitia Cleverbot API. (https://public-api.travitia.xyz/talk)InstallationInstalling withpipfrom PyPIpip install -U async_cleverbotInstalling withpip+gitfrom GitHubpip install -U git+https://github.com/crrapi/async-cleverbotUsageimportasync_cleverbotasaccleverbot=ac.Cleverbot("Your API key here")# Create the Cleverbot clientresponse=awaitcleverbot.ask("How are you today?")# Ask a question, returns async_cleverbot.cleverbot.Responseprint(response.text)# Text from the Response objectawaitcleverbot.close()Getting an API keyJoin theTravitia API Discord serverand use the> apicommand to request an API key.Using contextThis API supports a context parameter for background context, so let's make use of it!importasync_cleverbotasaccleverbot=ac.Cleverbot("Your API key here",ac.DictContext())response=awaitcleverbot.ask("How are you today?",246938839720001536)# 2nd param is an identifier, this can be a user id!print(response.text)response=awaitcleverbot.ask("I'm doing good too.",246938839720001536)print(response.text)print(cleverbot.context._storage)# "How are you today?" - returns most recent previous queriesawaitcleverbot.close()New in 0.2.1: EmotionsThis wrapper's API now supports selecting an emotion to influence its response.You can specify a custom emotion using the enumasync_cleverbot.Emotion.(The default emotion isEmotion.neutral)Supported emotions:async_cleverbot.Emotion.neutral/normal- Neutral responseasync_cleverbot.Emotion.sad/sadness- Sad responseasync_cleverbot.Emotion.fear/scared- Fearful responseasync_cleverbot.Emotion.joy/happy- Excited responseasync_cleverbot.Emotion.anger/angry- Angry responseAn exampleimportasync_cleverbotasaccleverbot=ac.Cleverbot("Your API key here")resp=awaitcleverbot.ask("What's up?",emotion=ac.Emotion.joy)print(resp.text)New in 0.2.2: Custom sessions, simpler contextYou can now pass context and your own session when creating a cleverbot client.importasync_cleverbotasaccleverbot=ac.Cleverbot("Your API key here",session=my_aiohttp_sess,context=ac.DictContext())In addition, DictContext no longer needs an argument.The argument has been preserved for backwards compatability.
Package: asynccli
A CLI framework based on asyncio.NoteThis is still inactivedevelopment. Things will change. For now, the basic framework is operational. If you are interested in helping out, or would like to see any particular features added, let me know.UsageThe simplest usage is to just pass in anasyncfunction.importasynccliasyncdefmycli():print("Hello, world.")if__name__=='__main__':app=asynccli.App(mycli)app.run()It can also be instantiated as a class, as long it has acallmethod.importasynccliclassDivisionCalculator(asynccli.CLI):numerator=asynccli.Integer(help_text='This is the numerator.')denominator=asynccli.Integer()asyncdefcall(self):print(self.first_num/self.second_num)if__name__=='__main__':app=asynccli.App(DivisionCalculator)app.run()In theDivisionCalculatorexample above, you would call your script like this:$ /path/to/script.py 2 3
0.6666666666666666What if you want to have a tiered CLI with a hierarchy of commands? First, create your command by subclassingCLIas above. Then, wrap the whole thing inside of theTieredCLIclass, and pass that to theApp.classCalculator(asynccli.TieredCLI):d=DivisionCalculatorNow, to invoke the script, you have an extra argument to call:$ /path/to/script.py d 2 3
0.6666666666666666Installationpip install asynccliRequirementsCurrently it requires Python 3.5 to make use ofasync/await. It usesargparseunder the hood, and therefore hasno dependenciesoutside of the standard library.RoadmapAdditionalArgumenttypesIntegration of additionalargparsefeaturesAdduvloopBetter support for help documentationTestingYou can invoke the test scripts a few different ways:$ py.test
$ python setup.py test
$ python -m py.testAnd, in order to generate the test coverage:$ coverage run -m py.testLicenseMITAuthorsasynccliwas written byAdam Hopkins.
Package: asyncclick
What’s AsyncClick?AsyncClick is a fork of Click that works well with trio or asyncio.Click is a Python package for creating beautiful command line interfaces
in a composable way with as little code as necessary. It’s the “Command
Line Interface Creation Kit”. It’s highly configurable but comes with
sensible defaults out of the box.It aims to make the process of writing command line tools quick and fun
while also preventing any frustration caused by the inability to
implement an intended CLI API.AsyncClick in four points:Arbitrary nesting of commandsAutomatic help page generationSupports lazy loading of subcommands at runtimeSeamlessly use async-enabled command and subcommand handlersInstallingInstall and update usingpip:$ pip install asyncclickAsyncClick supports Python 3.7 and newer, and PyPy3.A Simple Exampleimportanyioimportasyncclickasclick# You can use all of click's features as per its documentation.# Async commands are supported seamlessly; they just work.@click.command()@click.option("--count",default=1,help="Number of greetings.")@click.option("--name",prompt="Your name",help="The person to greet.")asyncdefhello(count,name):"""Simple program that greets NAME for a total of COUNT times."""forxinrange(count):ifx:awaitanyio.sleep(0.1)click.echo(f"Hello,{name}!")if__name__=='__main__':hello(_anyio_backend="trio")# or asyncio# You can use your own event loop:#    import anyio#    async def main():#        await hello.main()#    if __name__ == '__main__':#        anyio.run(main)# This is useful for testing.NoteAsyncClick automagically starts an anyio event loop and runs your
code asynchronously. You don’t need to useanyio.run.$ python hello.py --count=3
Your name: Click
Hello, Click!
Hello, Click!
Hello, Click!DonateThe Pallets organization develops and supports Click and other popular
packages. In order to grow the community of contributors and users, and
allow the maintainers to devote more time to the projects,please
donate today.The AsyncClick fork is maintained by Matthias Urlichs <matthias@urlichs.de>.
It’s not a lot of work, so if you’d like to motivate me, donate to the
charity of your choice and tell me that you’ve done so. ;-)LinksAsyncClickis sufficiently minimal to not have its own web page.Code:https://github.com/python-trio/asyncclickThese links point to the original, non-async-enabled, version ofClick.Website:https://palletsprojects.com/p/click/Documentation:https://click.palletsprojects.com/Changes:https://click.palletsprojects.com/changes/PyPI Releases:https://pypi.org/project/click/Source Code:https://github.com/pallets/clickIssue Tracker:https://github.com/pallets/click/issuesChat:https://discord.gg/pallets
Package: asyncclick-option-group
click-option-groupclick-option-groupis a Click-extension package that adds option groups
missing inClick.Aim and MotivationClick is a package for creating powerful and beautiful command line interfaces (CLI) in Python,
but it has no the functionality for creating option groups.Option groups are convenient mechanism for logical structuring CLI, also it allows you to set
the specific behavior and set the relationship among grouped options (mutually exclusive options for example).
Moreover,argparsestdlib package contains this
functionality out of the box.At the same time, many Click users need this functionality.
You can read interesting discussions about it in the following issues:issue 257issue 373issue 509issue 1137The aim of this package is to provide group options with extensible functionality
using canonical and clean API (Click-like API as far as possible).QuickstartInstallingInstall and update using pip:pipinstall-Uclick-option-groupA Simple ExampleHere is a simple example how to use option groups in your Click-based CLI.
Just useoptgroupfor declaring option groups by decorating
your command function in Click-like API style.# app.pyimportclickfromclick_option_groupimportoptgroup,RequiredMutuallyExclusiveOptionGroup@click.command()@optgroup.group('Server configuration',help='The configuration of some server connection')@optgroup.option('-h','--host',default='localhost',help='Server host name')@optgroup.option('-p','--port',type=int,default=8888,help='Server port')@optgroup.option('-n','--attempts',type=int,default=3,help='The number of connection attempts')@optgroup.option('-t','--timeout',type=int,default=30,help='The server response timeout')@optgroup.group('Input data sources',cls=RequiredMutuallyExclusiveOptionGroup,help='The sources of the input data')@optgroup.option('--tsv-file',type=click.File(),help='CSV/TSV input data file')@optgroup.option('--json-file',type=click.File(),help='JSON input data file')@click.option('--debug/--no-debug',default=False,help='Debug flag')defcli(**params):print(params)if__name__=='__main__':cli()$pythonapp.py--help
Usage:app.py[OPTIONS]Options:Serverconfiguration:Theconfigurationofsomeserverconnection-h,--hostTEXTServerhostname-p,--portINTEGERServerport-n,--attemptsINTEGERThenumberofconnectionattempts-t,--timeoutINTEGERTheserverresponsetimeoutInputdatasources:[mutually_exclusive,required]Thesourcesoftheinputdata--tsv-fileFILENAMECSV/TSVinputdatafile--json-fileFILENAMEJSONinputdatafile--debug/--no-debugDebugflag--helpShowthismessageandexit.Documentationhttps://click-option-group.readthedocs.io
Package: asyncclick-repl
asyncclick-replCommand to make a REPL out of a group by passing-ior--interactiveto the cli.
Inspired byclick-replbut using native
click command and shell completion.importasyncioimportasyncclickasclickfromasyncclick_replimportAsyncREPL@click.group(cls=AsyncREPL)asyncdefcli():pass@cli.command()@click.option("--count",default=1,help="Number of greetings.")@click.option("--name",prompt="Your name",help="The person to greet.")asyncdefhello(count,name):"""Simple program that greets NAME for a total of COUNT times."""for_inrange(count):awaitasyncio.sleep(0.1)click.echo(f"Hello,{name}!")cli(_anyio_backend="asyncio")myclickapp-i

>hello--count2--nameFoo
Hello,Foo!
Hello,Foo!
>:qFeatures:Tab-completion. Using click's shell completionExecute system commands using!prefix. Note:!should be followed by a space e.g! ls:hshow commands help.Prompt configurationUseprompt_kwargsto provide configuration topython-prompt-toolkit'sPromptclassimportasyncclickasclickfromprompt_toolkit.historyimportFileHistoryfromasyncclick_replimportAsyncREPLprompt_kwargs={"history":FileHistory("./history"),}@click.group(cls=AsyncREPL,prompt_kwargs=prompt_kwargs)asyncdefcli():passcli()
Package: async-client-decorator
async-client-decoratorUsing@decoratorto esaily request an HTTP ClientThis framework based onaiohttp's http client framework.Use Union Type to describe the elements required in an HTTP request.InstallationPython 3.10 or higher is required.pip install async-client-decoratorQuick ExampleAn example is the API provided by theBUS API.importasyncioimportaiohttpfromasync_client_decoratorimportrequest,Session,Queryloop=asyncio.get_event_loop()classBusAPI(Session):def__init__(self,loop:asyncio.AbstractEventLoop):super().__init__("https://api.yhs.kr",loop)@request("GET","/bus/station")asyncdefstation_search_with_query(self,response:aiohttp.ClientResponse,name:Query|str):returnawaitresponse.json()asyncdefmain():asyncwithBusAPI(loop)asclient:response=awaitclient.station_search_with_query(name="bus-station-name")data=awaitresponse.json()print(len)loop.run_until_complete(main())