Saravanan666/pypi-org huggingface dataset:
Package: async-dramatiq
Quick StartBackgroundDramatiqis a background task-processing library for Python with a focus on simplicity, reliability and performance.This package,async-dramatiq, extends Dramatiq to provide the following:Support for Asyncio (issue #238)Message scheduling support (scheduling cookbook)SetupTo provide async support for your actors all you need to do is add theAsyncMiddlewareto your broker.RabbitMQ Brokerimport dramatiq
from dramatiq.brokers.rabbitmq import RabbitmqBroker

rabbitmq_broker = RabbitmqBroker(host="rabbitmq")
rabbitmq_broker.add_middleware(AsyncMiddleware())  # <--- Here
dramatiq.set_broker(rabbitmq_broker)Redis Brokerimport dramatiq
from dramatiq.brokers.redis import RedisBroker

redis_broker = RedisBroker(host="redis")
redis_broker.add_middleware(AsyncMiddleware()) # <--- Here
dramatiq.set_broker(redis_broker)RunningThe SchedulerWe leverageapscheduleras our scheduling system. Check outrun_scheduler.pyfor an example of running this scheduler.Dramatiq WorkerFor more details check out the official guide todramatiqordocker-compose.yamlfor a specific example.ExamplePlay around withworker-heartbeat-example. A functioning and featured example implementation.Async MiddlewareAsyncMiddlewarewill start aAsyncWorkerwhich will be used to run the event loop. This event loop will be shared across the Worker threads.Startup and Shutdown EventsTo startup and shutdown any resources theAsyncMiddlewareprovides two hooks:Before the event loop is startedAfter the event loop is stopped
To allow for standing up or tearing down of shared async resourcesExamplefrom async_dramatiq.middleware import AsyncMiddleware

async def startup() -> None:
    """This function should contain your resource initialization code."""
    pass

async def shutdown() -> None:
    """This function should contain your resource teardown code."""
    pass


class MyAsyncMiddleware(AsyncMiddleware):
    def before_async_worker_thread_startup(
        self, _: RabbitmqBroker, thread: AsyncWorker, **kwargs: dict[str, Any]
    ) -> None:
        thread.event_loop.run_until_complete(startup())

    def after_async_worker_thread_shutdown(
        self, _: RabbitmqBroker, thread: AsyncWorker, **kwargs: dict[str, Any]
    ) -> None:
        thread.event_loop.run_until_complete(shutdown())
        thread.event_loop.close()Async ActorThe async actor,async_actor,  acts as a thin wrapper around the Dramatiq actor providing a variety of new functionality.Interval JobsRun a job at some interval@async_actor(interval=timedelta(seconds=5))
def run_every_5_seconds() -> None:
    passCron JobsRun a job on a crontab ( Seehttps://crontab.guru/. )@async_actor(interval="0 0 * * *")
def run_at_midnight() -> None:
  pass
Package: async-drf
Django REST framework async viewsHow to usefrom async_drf.mixins import AsyncMixin, AsyncListModelMixin
from async_drf.viewsets import AsyncGenericViewSet

class ProductsViewSet(AsyncMixin, AsyncGenericViewSet, AsyncListModelMixin):
	serializer_class = ProductsSerializer
	queryset = ProductModel.objects.prefetch_related().all()

	async def list(self, request: Request, *args, **kwargs):
	    # do async stuff here
		return Response(data=data)
Package: asyncdynamo
Asyncdynamo===========Asynchronous Amazon DynamoDB library for TornadoRequires boto>=2.3 and python 2.7Tested with Tornado 1.2.1Installation------------Installing from github: `pip install  git+https://github.com/bitly/asyncdynamo.git`Installing from source: `git clone git://github.com/bitly/asyncdynamo.git; cd asyncdynamo; python setup.py install`Usage-----Asyncdynamo syntax seeks to mirror that of [Boto](http://github.com/boto/boto).```pythonfrom asyncdynamo import asyncdynamodb = asyncdynamo.AsyncDynamoDB("YOUR_ACCESS_KEY", "YOUR_SECRET_KEY")def item_cb(item):print itemdb.get_item('YOUR_TABLE_NAME', 'ITEM_KEY', item_cb)```Requirements------------The following two python libraries are required* [boto](http://github.com/boto/boto)* [tornado](http://github.com/facebook/tornado)Issues------Please report any issues via [github issues](https://github.com/bitly/asyncdynamo/issues)
Package: async-Eel
async-EelEel is a little Python library for making simple Electron-like offline HTML/JS GUI apps,
with full access to Python capabilities and libraries.AboutPython3.6+useasynciooriginal README.mdoriginal repositoryI design this library forasyncioevent loop users.The original usesgeventand both event loops have difficulty in using simultaneously.Installpipinstallasync-eelHow to useIt looks like same usage, but something is different, please look atexample codes.I forkedeel_bootstrap(JP)as good example.Author@namuyan_mineLicenceMIT
Package: async-email
django-async-emailEMAILS_TEMPLATES={"password_reset":{"subject":"registration/password_set_subject.txt","body_html":"registration/password_set_email.html","body_txt":"registration/password_set_email.txt",}}Important notesBe careful with the email configured on the settings.DEFAULT_FROM_EMAIL.An invalid email on settings.DEFAULT_FROM_EMAIL will not allow your project to runpython setup.py sdist bdist_wheel && pip uninstall -y django_async_email && python -m pip install dist/django_async_email-0.1.0-py2.py3-none-any.whlDemo projectcddemo_project# Build and run the docker imagedocker-composebuild&&docker-composeup-ddemo_project# Run migrationsdocker-composeexecdemo_projectpythonmanage.pymigrate# Create the superuserdocker-composeexecdemo_projectpythonmanage.pycreatesuperuserceleryworker--app=demo_project.celery-linfo--pool=eventlet
Package: asyncer
Asyncer, async and await, focused on developer experience.Documentation:https://asyncer.tiangolo.comSource Code:https://github.com/tiangolo/asyncerAsynceris a small library built on top ofAnyIO.Asyncerhas a small number of utility functions that allow working withasync,await, and concurrent code in a more convenient way under my (@tiangolo - Sebastián Ramírez) very opinionated and subjective point of view.The main goal ofAsynceris to improvedeveloper experienceby providing better support forautocompletionandinline errorsin the editor, andmore certaintythat the code isbug-freeby providing better support for type checking tools likemypy.Asynceralso tries to improveconvenienceand simplicity when working withasynccodemixedwith regularblocking code, allowing to use them together in a simpler way... again, under my verysubjectivepoint of view.🚨 WarningThis small library only exists to be able to use theseutility functionsuntil (and if) they are integrated intoAnyIO.It will probably take some time for that to happen (or to be decided if it will be included or not).So I made this to be able to use these ideas right now. 🤓Can I Use It?Yes 🎉 (but continue reading).You can use this and evaluate thelibrary API designI'm proposing. It will probably be useful to know if it works and is useful for you (I hope so).But still, consider this lab material, expect it to change a bit. 🧪If you use it,pin the exact Asyncer versionfor your project, to make sure it all works.Havetestsfor your project (as you should, anyway). Andupgrade the versiononce you know that the new version continues to work correctly.Still, it'sjust 4 functions, so there's not much to change, if you had to refactor your code to update something it would not be much.And if you don't want to addasynceras a dependency to your project, you can also just copy the main file and try out those functions, it's quite small (but in that case you won't get updates easily).RequirementsAsAsynceris based onAnyIOit will be also installed automatically when you installAsyncer.Installation$pipinstallasyncer---> 100%Successfully installed asyncer anyioHow to UseYou can read more about each of the use cases and utility functions inAsyncerin thetutorial.As a sneak preview of one of the utilities, you cancall sync code from async codeusingasyncify():importtimeimportanyiofromasyncerimportasyncifydefdo_sync_work(name:str):time.sleep(1)returnf"Hello,{name}"asyncdefmain():message=awaitasyncify(do_sync_work)(name="World")print(message)anyio.run(main)Asyncer'sasyncify()will use AnyIO underneath to dothe smart thing, avoid blocking the mainasyncevent loop, and run thesync/blocking function in aworker thread.Editor SupportEverything inAsynceris designed to get the bestdeveloper experiencepossible, with the best editor support.Autocompletionfor function arguments:Autocompletionfor return values:Inline errorsin editor:Support for tools likemypy, that can help you verify that yourcode is correct, and prevent many bugs.LicenseThis project is licensed under the terms of theMIT license.
Package: asynces
# asynces[![Build Status](https://travis-ci.org/fabregas/asynces.svg?branch=master)](https://travis-ci.org/fabregas/asynces)[![codecov](https://codecov.io/gh/fabregas/asynces/branch/master/graph/badge.svg)](https://codecov.io/gh/fabregas/asynces)### Asyncio driver for Elasticsearch and Python 3.5+Its goal is to create an asyncio transport for the official elasticsearch python driver.The **asynces** package provides the AsyncElasticsearch class inherited fromthe Elasticsearch class (see [elasticsearch](https://elasticsearch-py.readthedocs.io/en/master/index.html)).All methods from the Elasticsearch class instance (see [API doc](http://elasticsearch-py.readthedocs.io/en/master/api.html))are available in the AsyncElasticsearch class instance.Each API method returns [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutines) that must be awaited.Example of asynces usage:```pythonimport asynciofrom asynces import AsyncElasticsearchasync def test(loop):es = AsyncElasticsearch('http://127.0.0.1:9200/', loop=loop)doc = {'hello': 'world'}await es.index(index='my-index', doc_type='test', body=doc, refresh=False)await es.indices.refresh(index="my-index")ret = await es.search(index='my-index')print(ret)es.close()loop = asyncio.get_event_loop()loop.run_until_complete(test(loop))loop.close()```## InstallationFirst, you should install the latest version of [elasticsearch](https://elasticsearch-py.readthedocs.io/en/master/index.html#compatibility)compatible with your elasticsearch server version.After that you should install asynces package:> pip install asynces
Package: async-etcd3gw
async-etcd3gwAn async etcd3 grpc-gateway v3 API Python client, derived frometcd3gw.Library Installation$ pip install async-etcd3gwUsageYou can find examples in examples folder.Basic usage example:importasynciofromasync_etcd3gwimportAsyncEtcd3Clientasyncdefmain():client=AsyncEtcd3Client(host="etcd",port=2379)# Put keyawaitclient.put(key="foo",value="bar")# Get keyprint("get key foo",awaitclient.get(key="foo"))# Get all keysprint("get all keys",awaitclient.get_all())# Create lease and use itlease=awaitclient.lease(ttl=100)awaitclient.put(key="foo",value="bar",lease=lease)# Get lease keysprint("get lease keys",awaitlease.keys())# Refresh leaseawaitlease.refresh()# Release all acquired resourcesawaitclient.close()if__name__=="__main__":asyncio.run(main())Linksetcdetcd gRPC APIetcd3gw, An etcd3 grpc-gateway v3 API Python clientetcd gRPC gatewayAIOHTTP, Asynchronous HTTP Client/Server for asyncio and Python.
Package: asynceth
asyncethAn asyncio ethereum jsonrpc libraryInstallpip install asyncethUsage Exampleimport asyncio
from asynceth import JsonRPCClient
from asynceth import Contract

async def example_jsonrpc_request():
    client = JsonRPCClient("http://localhost:8485")
    balance = await client.eth_getBalance("0x0000000000000000000000000000000000000000")
    print(balance)

asyncio.get_event_loop().run_until_complete(example_jsonrpc_request())

greeter_code = """
contract Greeter is Mortal {
    /* Define variable greeting of the type string */
    string greeting;

    /* This runs when the contract is executed */
    function Greeter(string _greeting) public {
        greeting = _greeting;
    }

    /* Main function */
    function greet() constant returns (string) {
        return greeting;
    }
}
"""

# NOTE: example requires `solc` to be installed, and private_key must be the private key to an
# account on the ethereum node pointed to by JsonRPCClient that has funds to deploy the contract
private_key = os.urandom(32)
async def example_contract_deployment():
    client = JsonRPCClient("http://localhost:8485")
    greeter = await Contract(client, greeter_code).set_signer(private_key).deploy("Hello World")
    greeting = await greeter.greet()
    assert greeting == "Hello World"

asyncio.get_event_loop().run_until_complete(example_contract_deployment())Running testspython setup.py testORvirtualenv -p python3 env
env/bin/pip install -r requirements.txt -r requirements-testing.txt
env/bin/py.testHistory0.0.1Initial release
Package: asyncEvento
Fully asynchronous python library to listen and emit events like in nodejsInstallation`pip install asyncEvento`Compatibiltypy36, py37UsageRead docs at:DocsWhy asyncEventoHandling asynchronous coroutines can be painful at times, using asyncEvento one can register a function with a certain event and later can fire the event on completion of some asynchronous tasks, which will in turn lead to execute all the functions registered to the event which was fired.Read the Docs for moreinfoScopeasyncEvento can be used in many areas where asynchronous tasks are to be handled with much ease.For eg:Asynchronous file handlingCopyrightCopyright 2018 Akshit GroverLicensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License athttp://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Package: async-executor
async-executorAsync execution poolExamplesLimit the number of concurrently running awaitablesimportasyncioimporttimeimportasync_executorasyncdefsleep_and_print(i):print(f'{i}{int(time.time())}- before sleep')awaitasyncio.sleep(1)print(f'{i}{int(time.time())}- after sleep')asyncdefmain():# limit to a maximum of two concurrent executionsexecutor=async_executor.AsyncExecutor(max_concurrent=2)# awaitables are only queued here - nothing is runforiinrange(5):executor.submit(sleep_and_print,i)# awaitables begin executingasyncfortaskinexecutor:task.result()asyncio.run(main())This shows that only a maximum of two executions are allowed to run concurrently.$ python examples/example_1.py
0 1670613515 - before sleep
1 1670613515 - before sleep
0 1670613516 - after sleep
1 1670613516 - after sleep
2 1670613516 - before sleep
3 1670613516 - before sleep
2 1670613517 - after sleep
3 1670613517 - after sleep
4 1670613517 - before sleep
4 1670613518 - after sleepInstallationpip install async-executorLicenseasync-executoris distributed under the terms of theMITlicense.
Package: async-exit-stack
AsyncExitStack backport for Python 3.5+Free software: PSF licenseDocumentation:https://docs.python.org/3.7/library/contextlib.html#contextlib.AsyncExitStackThis package contains code from the CPython project.Installpip install async_exit_stackUsage examplefromasync_exit_stackimportAsyncExitStackasyncdefsome_async_function():asyncwithAsyncExitStack()asstack:connections=[awaitstack.enter_async_context(get_connection())foriinrange(5)]# All opened connections will automatically be released at the end of# the async with statement, even if attempts to open a connection# later in the list raise an exception.ReferenceRefer toPython 3.7 contextlib documentationfor a complete reference and more context.classAsyncExitStackAn asynchronous context manager, similar to ExitStack, that supports combining
both synchronous and asynchronous context managers, as well as having
coroutines for cleanup logic.The close() method is not implemented, aclose() must be used instead.enter_async_context(cm)Similar to enter_context() but expects an asynchronous context manager.push_async_exit(exit)Similar to push() but expects either an asynchronous context manager or a coroutine.push_async_callback(callback,*args,**kwds)Similar to callback() but expects a coroutine.aclose()Similar to close() but properly handles awaitables.History1.0.0 (2018-05-07)First release based on Python 3.7b4.
Package: async-extensions
async-extensionsAsynchronous extensions.InstallingPython 3.8 or above is required.pipInstalling the library withpipis quite simple:$pipinstallasync-extensionsAlternatively, the library can be installed from source:$gitclonehttps://github.com/nekitdev/async-extensions.git$cdasync-extensions$python-mpipinstall.poetryYou can addasync-extensionsas a dependency with the following command:$poetryaddasync-extensionsOr by directly specifying it in the configuration like so:[tool.poetry.dependencies]async-extensions="^2.0.2"Alternatively, you can add it directly from the source:[tool.poetry.dependencies.async-extensions]git="https://github.com/nekitdev/async-extensions.git"SupportIf you need support with the library, you can send anemailor refer to the officialDiscord server.ChangelogYou can find the changeloghere.Security PolicyYou can find the Security Policy ofasync-extensionshere.ContributingIf you are interested in contributing toasync-extensions, make sure to take a look at theContributing Guide, as well as theCode of Conduct.Licenseasync-extensionsis licensed under the MIT License terms. SeeLicensefor details.
Package: async-faceit-api
Async faceit APIAsync wrapper for the faceit API.Here are the docsGetting startedIf you dont already have a loop in your programm you need to create one.
Here is a basic example which will search players by the username and
prints out a dict with the nicknames and player_ids:import asyncio
from src.async_faceit_api import FaceitAPI


async def my_task():
    api_key = "..."
    api = FaceitAPI(api_key)
    players = await api.search_players("username")
    print({player.nickname: player.player_id for player in players.items})


if __name__ == "__main__":
    loop = asyncio.new_event_loop()
    loop.run_until_complete(my_task())
    loop.close()Its recomended to store the api_key somewhere safe (e.g .env file)!
Here is another example on how you can implement the api:class MyApi(FaceitAPI):
    def __init__(self):
        api_key = os.getenv('faceit_api_key')
        super().__init__(api_key)

    async def get_played_maps_parallel(self, player_id):
        matches = await self.player_history(player_id, Game.CS_GO)
        all_match_stats = await asyncio.gather(*[self.match_stats(match.match_id) for match in matches.items])
        maps = {}
        for match_stat in all_match_stats:
            match_stat: MatchStats
            map = match_stat.rounds[0].round_stats['Map']
            if map in maps:
                maps[map] += 1
            else:
                maps[map] = 1
        return maps


async def my_task():
    api = MyApi()
    player_id = "..."
    print(await api.get_played_maps_parallel(player_id))


if __name__ == "__main__":
    loop = asyncio.new_event_loop()
    loop.run_until_complete(my_task())
    loop.close()Error HandlingNote that the async api methods return an object of type FaceitApiError
if the request was not successful. To distinguish between a successful
response and an error, you can easily use the object as a boolean expression:games = await api.games()
    if games:
        print('success')
    else:
        print('error')
Package: async-factory-boy
factory_boyextension
with asynchronous ORM supportRequirementspython (3.8, 3.9, 3.10)InstalationInstall usingpippip install async_factory_boyUsageasync_factory_boy integrate with Object Relational Mapping (ORM) through
subclass offactory.Factory. All supported are listed below.SQLAlchemy, withasync_factory_boy.factory.sqlalchemy.AsyncSQLAlchemyFactoryfromasync_factory_boy.factory.sqlalchemyimportAsyncSQLAlchemyFactoryclassTestModelFactory(AsyncSQLAlchemyFactory):classMeta:model=TestModelsession=sessionname=Faker("name")created_at=Faker("date_time")Tortoise ORM, withasync_factory_boy.factory.tortoise.AsyncTortoiseFactoryfromasync_factory_boy.factory.tortoiseimportAsyncTortoiseFactoryclassTestModelFactory(AsyncTortoiseFactory):classMeta:model=TestModelname=Faker("name")created_at=Faker("date_time")and factory usagetest=awaitTestModelFactory.create()test=awaitTestModelFactory.build()For test configuration examples checktests/directory.
Package: async-fastapi-jwt-auth
Async fork of FastAPI JWT AuthOriginal lib:Documentation:https://indominusbyte.github.io/fastapi-jwt-authSource Code:https://github.com/IndominusByte/fastapi-jwt-authAsync fork:Documentation:https://sijokun.github.io/async-fastapi-jwt-authSource Code:https://github.com/sijokun/async-fastapi-jwt-auth/FeaturesFastAPI extension that provides JWT Auth support (secure, easy to use and lightweight), if you were familiar with flask-jwt-extended this extension suitable for you, cause this extension inspired by flask-jwt-extended 😀Access tokens and refresh tokensFreshness TokensRevoking TokensSupport for WebSocket authorizationSupport for adding custom claims to JSON Web TokensStoring tokens in cookies and CSRF protectionInstallationThe easiest way to start working with this extension with pippipinstallasync-fastapi-jwt-authIf you want to use asymmetric (public/private) key signing algorithms, include theasymmetricextra requirements.pipinstall'async-fastapi-jwt-auth[asymmetric]'LicenseThis project is licensed under the terms of the MIT license.
Package: async-fetcher
Installationpipinstallasync-fetcher# orpipinstall-egit+https://github.com/night-crawler/async-fetcher.git@#egg=async-fetcherSampleaf=AsyncFetch({'first':AsyncFetch.mk_task(build_url('request-info')),'second':AsyncFetch.mk_task('http://example.com/'),'fail':AsyncFetch.mk_task(build_url('404'))})responses=af.go()mk_taskstatic method can take this arguments::paramfail_silently:bool,donotraiseexceptions,defaultisFalse;fortestpurpose,donotuseinproduction:paramnum_retries:int,*optional*,defaultis-1;-1-noretries;0-useAsyncFetch.num_retries:paramautodetect_content_type:ifno`content-type`headerwasspecified,set`content-type`as`application/json`fordict,and`text/html`otherwise;defaultisTrue:paramjson_encoder:JSONEncoder,*optional*,JSONencoderfordataserializationtriestouseDRF's encoder, or default JSONEncoder from json package; default is JSONEncoder:paramurl:str,*required*,urladdress:paramapi_key:str,optionalAPIkeypassedintoHEADERSdict:paramdata:dict,*optional*,requestdata.DefaultisNone,:parammethod:str,*optional*,HTTPrequestmethod.DefaultisTrue.:paramheaders:dict,*optional*,optionalHTTPheaders:paramresponse_type:str,*optional*,HTTPresponsetype(infactit's just aiohttp'smethodname,i.e.text,orjson);defaultis'json':paramlanguage_code:str,set`accept-language`header:paramtimeout:float,*optional*,timetowaitforresponseinsecondsbeforeTimeoutError:paramquery:dict,*optional*,urlgetarguments:paramdo_not_wait:bool,*optional*,failsilentlywithnoretriesandemptyresultsetaf0=AsyncFetch({})tcp_connector=af0.get_tcp_connector()af1=AsyncFetch({'1':AsyncFetch.mk_task(build_url('request-info')),'2':AsyncFetch.mk_task(build_url('request-info')),},tcp_connector=tcp_connector)responses=af1.go()