Saravanan666/pypi-org huggingface dataset:
Package: async-lru-threadsafe
info:Simple lru cache for asyncioInstallationpipinstallasync-lruUsageThis package is a port of Python’s built-infunctools.lru_cachefunction forasyncio. To better handle async behaviour, it also ensures multiple concurrent calls will only result in 1 call to the wrapped function, with allawaits receiving the result of that call when it completes.importasyncioimportaiohttpfromasync_lruimportalru_cache@alru_cache(maxsize=32)asyncdefget_pep(num):resource='http://www.python.org/dev/peps/pep-%04d/'%numasyncwithaiohttp.ClientSession()assession:try:asyncwithsession.get(resource)ass:returnawaits.read()exceptaiohttp.ClientError:return'Not Found'asyncdefmain():fornin8,290,308,320,8,218,320,279,289,320,9991:pep=awaitget_pep(n)print(n,len(pep))print(get_pep.cache_info())# CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)# closing is optional, but highly recommendedawaitget_pep.cache_close()asyncio.run(main())TTL (time-to-live, expiration on timeout) is supported by acceptingttlconfiguration
parameter (off by default):@alru_cache(ttl=5)asyncdeffunc(arg):returnarg*2The library supports explicit invalidation for specific function call bycache_invalidate():@alru_cache(ttl=5)asyncdeffunc(arg1,arg2):returnarg1+arg2func.cache_invalidate(1,arg2=2)The method returnsTrueif corresponding arguments set was cached already,Falseotherwise.Python 3.8+ is requiredThanksThe library was donated byOcean S.A.Thanks to the company for contribution.
Package: asynclxd
asyncLXD is an asyncio-based client library for the theLXDREST API.It provides an high level API to interact with resources on LXD servers, such
as containers, images, networks, profiles and storage.LXD servers are accessible through theasynclxd.remote.Remoteclass, which
exposes server details and configuration, as well as access to resource
collections.Collections (such ascontainers,images,profiles,networks, …) allow
creating and fetching resources, which can be modified, updated or deleted.For example:frompprintimportpprintfromasynclxdimportlxc# get all remotes defined in the client configremotes=lxc.get_remotes()asyncwithremotes['local']asremote:# fetch all images and print their detailsresp=awaitremote.images.read()forimageinresp:resp=awaitimage.read()pprint(resp.metadata)# image details have been read, now they're also cached (same# output as above)pprint(image.details())# fetch a single container by namecontainer=awaitremote.containers.get('c')pprint(container.details())# rename itawaitcontainer.rename('new-c')# change some detailsawaitcontainer.update({'description':'foo'})# and now delete itawaitcontainer.delete()
Package: async_magic
IPython Async_magicAsync at the top level repl !In[1]:importaiohttpIn[2]:res=awaitaiohttp.get('https://api.github.com')File"<ipython-input-2-52b78a6e45a0>",line1res=awaitaiohttp.get('https://api.github.com')^SyntaxError:invalidsyntaxIn[3]:%load_extasync_magicIn[4]:res=%awaitaiohttp.get('https://api.github.com')In[5]:awaitres.json()Out[5]:{'authorizations_url':'https://api.github.com/authorizations','code_search_url':'https://api.github.com/search/code?q={query}{&page,per_page,sort,order}','commit_search_url':'https://api.github.com/search/commits?q={query}{&page,per_page,sort,order}','current_user_authorizations_html_url':'https://github.com/settings/connections/applications{/client_id}','current_user_repositories_url':'https://api.github.com/user/repos{?type,page,per_page,sort}','current_user_url':'https://api.github.com/user','emails_url':'https://api.github.com/user/emails','emojis_url':'https://api.github.com/emojis',...}Note the%on assignments inres = %awaitaiohttp.get('https://api.github.com')Change loop:Use%loop <loop>
Package: async-mail
async_mailBy django inspired async mail package.Supports simple-settings and django settings. These settings entries are expected
to be presentEMAIL_BACKEND = 'async_mail.backends.smtp.EmailBackend'
EMAIL_SENDER = 'no-reply@nelen-schuurmans.nl'
EMAIL_HOST = 'your-host-name'

EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_PORT = 25
EMAIL_USE_TLS = True
EMAIL_TIMEOUT = 5ExampleTo send a single mailfrom async_mail import Mail
from async_mail.models import Message

mail = Mail()
message = Message(
    sender="lars.claussen@mail.com",
    recipients=["lars.claussen@mail.com"],
    subject="one mail",
    message_body="one mail to rule them all"
)
await mail.send_message(message)TODOconsole backendpydantic settings supportmultiple SMTP clients instead of gather for true async executionFree software: MIT licenseDocumentation:https://async-mail.readthedocs.io.CreditsThis package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.History0.1b (2020-06-03)Beta release.
Package: asyncmc
# Asyncmc![Build state](https://travis-ci.org/ErDmKo/asyncmc.svg?branch=master)[Asyncmc](https://github.com/ErDmKo/asyncmc) is a memcached client for [Tornado](https://github.com/tornadoweb/tornado) web framework.Asyncmc work with python 2.7 and python 3## Quick links* [Source (github)](https://github.com/ErDmKo/asyncmc)* [License](https://raw.githubusercontent.com/ErDmKo/asyncmc/master/LICENSE.txt)* [Examples](https://github.com/ErDmKo/asyncmc/blob/master/examples)## Hello, MemcachedHere is a simple "Hello, Memcached" example for Tornado with Memcached```pythonimport tornado.ioloopfrom tornado import genimport asyncmcloop = tornado.ioloop.IOLoop.instance()@gen.coroutinedef out():mc = asyncmc.Client(servers=['localhost:11211'], loop=loop)yield mc.set(b"some_key", b"Some value")value = yield mc.get(b"some_key")print(value)values = yield mc.multi_get(b"some_key", b"other_key")print(values)yield mc.delete(b"another_key")loop.run_sync(out)```## Requires+ [Tornado](https://github.com/tornadoweb/tornado)+ [Memcached](http://memcached.org/)## InstallationTo install asyncmc, simply:```bash$ pip install asyncmc```# LICENSEAsyncmc is licensed under MIT.
Package: async-mediawiki
async-mediawikiAn asynchronous python libary to get mediawiki contentInstallationIt requires Python 3.6 or above and aiohttppip3 install async-mediawikiDevelopment Version:pip3 install git+https://github.com/Gelbpunkt/async-mediawikiUsageimportasync_mediawikiasmwwiki=mw.Wiki("wiki api url here")#make a Wiki object which is the key to the librarywiki=mw.Wiki.wikipedia("en")#alternate constructor for Wikipedia Wikisawaitwiki.create_account("test","pass1234")#create an account in the wikiawaitwiki.login("test","pass1234")#login with the newly made userawaitwiki.get_random_pages(3)#get a list of pagespage=wiki.get_page("Mediawiki")#get a specific pageprint(awaitpage.html)#print the pure page htmlprint(awaitpage.markdown)#print the pure page markdown (wiki code)print(awaitpage.text)#print the page's text (library handled filtering of the HTML)awaitpage.edit("That's a nice lib!")#edit the page, automatically uses the logged in user or anonymousawaitwiki.close()#the Wiki object also supports a context manager (async with) to close automaticallyLicense
Package: async-message-handler
Asynchronous Message HandlerThis package is a niche message handler solution between asyncio event loop and processes/threads (Aka multiprocessing.Process/threading.Thread).You can install this package bypip install async-message-handlerAMH creates asynchronous connection between asyncio event loop and another python process/thread.How to use?Code below shows basic usage of message handler api. This message api is completely nonblocking in asyncio event loop.import time
import asyncio
import multiprocessing as mp

from asynchronous_message_handler import ProcessCommandHandler, CommandContext, ProcessCommand, Events

#Creating new command handler object.
handler = ProcessCommandHandler(timeout=15)

def sample_process(context:CommandContext):
    #You should initialize context to be bound.
    context.initialize()

    #Waits until new message, this operation is blocking for this process.
    #If you want it to be nonblocking use blocking=False parameter.

    command:ProcessCommand = context.get_next()
    print(command.get_payload())

    #Sleep for 5 seconds.
    time.sleep(5)
    command.reply("Hello from process.")

    time.sleep(5)
    #Send message from process to asynchronous context.
    context.send_message("This is a late message from process.")


#This is a sample event handler for new messages from process/thread.
@handler.on(Events.NewMessage)
def message_callback(message):
    print(message)


async def main():
    #This is asyncio context.
    response = await handler.command("Hello from asyncio.")
    print(response)
    #Waiting for a while for sample process to loop message demo.
    await asyncio.sleep(8)



if __name__=="__main__":
    process = mp.Process(target=sample_process, args=(handler.get_command_context(),))
    process.start()
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    process.join()
Package: async-metrics
async_metricsasynciometrics for your app.Available metrics:asyncio: event loop status, policy and exception handler and tasks info;system: uptime, platform, recursion limit, default encoding, phisical and virtual processors, system load and process user;dependencies: application dependencies;python: implementation, version and PATH;process: application process info like: threads, open files, connections, context switch and childrens PID;partitions: partitions usage;about: async_metrics version, project: url, issues and release pages.InstallationInstall and update using pip:pipinstall-Uasync_metricsUsageAIOHTTPfromaiohttpimportwebfromasync_metrics.ext.aiohttpimportsetup_async_metricsapp=web.Application()setup_async_metrics(app)web.run_app(app,host="0.0.0.0")FlaskfromflaskimportFlaskfromasync_metrics.ext.flaskimportsetup_async_metricsapp=Flask(__name__)setup_async_metrics(app)@app.route('/')defhello_world():return'Hello, World!'ExamplesClone the repository, install the dependencies and follow the following steps:AIOHTTPpythonexamples/aiohttp_example.pyFor web UI dashboard access:http://localhost:8080/async_metrics/dashboardFlaskFLASK_APP=examples/flask_example.pyflaskrunFor web UI dashboard access:http://localhost:5000/async_metrics/dashboardCLIInstallationpipinstallasync_metrics[cli]Usagepython-masync_metricsshow-h
Usage:python-masync_metricsshow[OPTIONS][ADDRESS]Options:--asyncioShowsummaryinformationaboutasyncenvironmen.--systemShowinformationaboutsystemenvironment.--depsShowapplicationsdependencies.--pythonShowinformationaboutcurrentpythonenvironment.--processShowsummaryinformationaboutapplicationprocess.--partitionsShowsummaryinformationaboutdiskpartition.--aboutShowinformationaboutasync_metrics.-h,--helpShowthismessageandexit.ADDRESScan be set via environment variableASYNC_METRICS_HOSTAcessing AIOHTTP example metrics:# default request URL: http://localhost:8080/async_metricspython-masync_metricsshow--systemAcessing Flask example metrics:python-masync_metricsshowhttp://localhost:5000/async_metrics--systemLinksLicense:Apache LicenseCode:https://github.com/amenezes/async_metricsIssue tracker:https://github.com/amenezes/async_metrics/issuesDocs:https://github.com/amenezes/async_metrics
Package: async-mgun
HTTP REST Client based on aiohttp with dynamic url building. Useful for microservices non-blocking communicationQuickstartfrommgunimportHttpClientimportasyncioclient=HttpClient('https://httpbin.org')asyncdefrequest():resp=awaitclient.anything.api.users[23].address.get({'q':'12'})print(resp.status)# 200print(resp.data['url'])# https://httpbin.org/anything/api/users/23/address?q=12loop=asyncio.get_event_loop()loop.run_until_complete(asyncio.wait([request()]))
Package: asyncmock
Awaitable mocks for async code.The package specifically only extendsmockand not any other part of unittest.NoteMock 4.0+ (included within Python 3.8+) now includes an awaitable mockmock.AsyncMock.
This is recommended for new projects.InstallationInstall usingpip:pipinstallasyncmockUsageAsync Mock is a drop in replacement for aMockobject eg:my_mock=AsyncMock()awaitmy_mock("foo",bar=123)my_mock.assert_called_with("foo",bar=123)This also works with nested methods:my_mock=AsyncMock()awaitmy_mock.my_method("foo",bar=123)my_mock.my_method.assert_called_with("foo",bar=123)Side effects and return values can also be awaited.Including a non-awaitable item:my_mock=AsyncMock()my_mock.my_method.not_async=Truemy_mock.my_method("foo",bar=123)Thenot_asyncoption can also be provided as an init argument. Thenot_asyncargument is not inherited by sub-mocks.pytest ExampleThese examples usepytestalong with thepytest-asyncioplugin.Generating an exception:@pytest.mark.asyncioasyncdeftest_raise_exception():my_mock=AsyncMock(side_effect=KeyError)withpytest.raises(KeyError):awaitmy_mock()my_mock.assert_called()
Package: async-moip
async_moipasyncio/aiohttp (Python3.5+) Moip API wrapper based onmoipproviding asyncronous requests.Usageimportasync_moipimportaiohttpimportasyncioasyncdefmain():moip=async_moip.Moip(environment='<production or sandbox',key='<key>',token='<token>')order=awaitmoip.get_order('ORD-W121212121')print(order)loop=asyncio.get_event_loop()loop.run_until_complete(main())Functionspost_customer(params)# create new customerget_customer(parameters)# get customer datapost_creditcard(customer_id,parameters)# add new credit card to customer accountdelete_creditcard(creditcard_id)# delete credit cardpost_order(parameters)# create a new orderget_order(order_id)# get order by idpost_payment(order_id,parameters)# create a paymentget_payment(payment_id)# get payment data by idcapture_payment(payment_id)# capture of a preauthorized paymentvoid_payment(payment_id)# cancel the capture of a preauthorized paymentaccount_exists(account_id)# check if account existsparams exampleshere
Package: asyncmongo
asyncmongo==========AsyncMongo is an asynchronous library for accessing mongowhich is built on the tornado ioloop.[![Build Status](https://travis-ci.org/bitly/asyncmongo.png?branch=master)](https://travis-ci.org/bitly/asyncmongo)Installation------------Installing: `pip install asyncmongo`Usage-----asyncmongo syntax strives to be similar to [pymongo](http://api.mongodb.org/python/current/api/pymongo/collection.html).import asyncmongoimport tornado.webclass Handler(tornado.web.RequestHandler):@propertydef db(self):if not hasattr(self, '_db'):self._db = asyncmongo.Client(pool_id='mydb', host='127.0.0.1', port=27017, maxcached=10, maxconnections=50, dbname='test')return self._db@tornado.web.asynchronousdef get(self):self.db.users.find({'username': self.current_user}, limit=1, callback=self._on_response)# or# conn = self.db.connection(collectionname="...", dbname="...")# conn.find(..., callback=self._on_response)def _on_response(self, response, error):if error:raise tornado.web.HTTPError(500)self.render('template', full_name=response['full_name'])About-----Some features are not currently implemented:* directly interfacing with indexes, dropping collections* retrieving results in batches instead of all at once(asyncmongo's nature means that no calls are blocking regardless of the number of results you are retrieving)* tailable cursors #15Requirements------------The following two python libraries are required* [pymongo](http://github.com/mongodb/mongo-python-driver) version 1.9+ for bson library* [tornado](http://github.com/facebook/tornado)Issues------Please report any issues via [github issues](https://github.com/bitly/asyncmongo/issues)
Package: asyncmongo_bufferx
asyncmongo==========AsyncMongo is an asynchronous library for accessing mongowhich is built on the tornado ioloop.[![Build Status](https://travis-ci.org/bitly/asyncmongo.png?branch=master)](https://travis-ci.org/bitly/asyncmongo)Installation------------Installing: `pip install asyncmongo`Usage-----asyncmongo syntax strives to be similar to [pymongo](http://api.mongodb.org/python/current/api/pymongo/collection.html).import asyncmongoimport tornado.webclass Handler(tornado.web.RequestHandler):@propertydef db(self):if not hasattr(self, '_db'):self._db = asyncmongo.Client(pool_id='mydb', host='127.0.0.1', port=27017, maxcached=10, maxconnections=50, dbname='test')return self._db@tornado.web.asynchronousdef get(self):self.db.users.find({'username': self.current_user}, limit=1, callback=self._on_response)# or# conn = self.db.connection(collectionname="...", dbname="...")# conn.find(..., callback=self._on_response)def _on_response(self, response, error):if error:raise tornado.web.HTTPError(500)self.render('template', full_name=response['full_name'])About-----Some features are not currently implemented:* directly interfacing with indexes, dropping collections* retrieving results in batches instead of all at once(asyncmongo's nature means that no calls are blocking regardless of the number of results you are retrieving)* tailable cursors #15Requirements------------The following two python libraries are required* [pymongo](http://github.com/mongodb/mongo-python-driver) version 1.9+ for bson library* [tornado](http://github.com/facebook/tornado)Issues------Please report any issues via [github issues](https://github.com/bitly/asyncmongo/issues)
Package: async-multiplexer
async_multiplexerasync_multiplexeris a TCP Multiplexer based onMplexprotocol, but simplified.
It is intended for creating mutiple streams in parallel
on top of a same TCP connection.Installationpipinstallasync-multiplexerUsageClientimportasynciofromasync_multiplexerimportopen_multiplexer_contextasyncdefecho_client():asyncwithopen_multiplexer_context("127.0.0.1",7777)asmultiplexer:stream_echo_1=awaitmultiplexer.multiplex("echo.1")stream_echo_2=awaitmultiplexer.multiplex("echo.2")awaitstream_echo_1.write(b"echo.1")awaitstream_echo_2.write(b"echo.2")if__name__=="__main__":asyncio.run(echo_client())Serverimportasynciofromasync_multiplexerimportbind_multiplex_listener_contextasyncdefhandler(stream):data=awaitstream.read()print(data)asyncdefecho_server():asyncwithbind_multiplex_listener_context("127.0.0.1",7777)aslistener:listener.set_handler("echo.1",handler)listener.set_handler("echo.2",handler)awaitasyncio.sleep(10)if__name__=="__main__":asyncio.run(echo_server())
Package: async-near
Near async rpc clientJsonProviderUse JsonProvider to process api calls to NEAR rpc noderpc_urlvaries by network:mainnethttps://rpc.mainnet.near.orgtestnethttps://rpc.testnet.near.orgbetanethttps://rpc.betanet.near.org(may be unstable)localnethttp://localhost:3030fromasync_near.providersimportJsonProviderjp=JsonProvider(rpc_url)res=jp.view_call(account_id,method_name,args,finality="optimistic")SignerUse Signer to sign or request to rpc nodefromasync_near.signerimportSigner,KeyPairkey=KeyPair(private_key)# create key pair (private-publish)signer=Signer(signer_account_id,key,)signer.sign(message)AccountUse Account to create and execute transactionsfromasync_near.signerimportSigner,KeyPairfromasync_near.providersimportJsonProviderfromasync_near.accountimportAccountacc=Account(JsonProvider("https://rpc.testnet.near.org"),Signer("example.testnet",KeyPair("ed25519:5sn12Kwd2TZn4A3...7979"),),)awaitacc.startup()Make contract callsbtc_amount=(awaitacc.view_function("btc_contract_id","available_btc",{})).resultawaitacc.function_call("btc_contract_id","ft_transfer_call",{"target_btc_address":"..."},)LicenseThis repository is distributed under the terms of both the MIT license and the Apache License (Version 2.0). See LICENSE and LICENSE-APACHE for details.
Package: asyncnetfsm
AsyncNetFSMAsynchronous multi-vendor library for interacting with network devicesSupport TelnetRequires:asyncioAsyncSSHPython >=3.5pyYAMLSupports:Cisco IOSCisco IOS XECisco IOS XRCisco ASACisco NX-OSCisco FTDHP Comware (like V1910 too)Fujitsu Blade SwitchesMikrotik RouterOSArista EOSJuniper JunOSAruba AOS 6.XAruba AOS 8.XTerminalFortinetExamples:Example of interacting with Cisco IOS devices:.. code-block:: pythonimport asyncio
import asyncnetfsm

async def task(param):
    async with asyncnetfsm.create(**param) as ios:
        # Testing sending simple command
        out = await ios.send_command("show ver")
        print(out)
        # Testing sending configuration set
        commands = ["line console 0", "exit"]
        out = await ios.send_config_set(commands)
        print(out)
        # Testing sending simple command with long output
        out = await ios.send_command("show run")
        print(out)
        # Testing interactive dialog
        out = await ios.send_command("conf", pattern=r'\[terminal\]\?', strip_command=False)
        out += await ios.send_command("term", strip_command=False)
        out += await ios.send_command("exit", strip_command=False, strip_prompt=False)
        print(out)


async def run():
    dev1 = { 'username' : 'user',
             'password' : 'pass',
             'device_type': 'cisco_ios',
             'ip': 'ip address',
    }
    dev2 = { 'username' : 'user',
             'password' : 'pass',
             'device_type': 'cisco_ios',
             'ip': 'ip address',
    }
    devices = [dev1, dev2]
    tasks = [task(dev) for dev in devices]
    await asyncio.wait(tasks)


loop = asyncio.get_event_loop()
loop.run_until_complete(run())
Package: asyncnewsapi
asyncnewsapiAn asyncio Python library to perform request againstNews API. It provides direct access to the endpoints defined in thedocumentation.Two classes are implemented, returning async iterators for the request results. Session will return an iterator through the results of a single request. Alternatively, Stream will return an infinite iterator, performing successive requests and continuing to iterate through the results. A minimal implementation can be as simple as:import asyncio

from asyncnewsapi import Session

async def main():
    async with Session() as api:
        async for article in api.top_headlines(language='en'):
            print(article['title'])

if __name__ == '__main__':
    asyncio.run(main())The API key should be provided as an environment variable named NEWSAPI_KEY:export NEWSAPI_KEY="..."Go to the NewsAPIwebsiteto create a free API key.This library is loosely based on / inspired bynewsapi-python, a requests based library by Matt Lisivick.InstallationUse pip to install this package, either directly from pypi:pip install asyncnewsapior after cloning from github:pip install .TestsUnit tests have been implemented using pytest. To run them, additional dependencies need be installed:pip install ".[test]"The tests can then be run using:python -m pytest -v tests/from the root of the repo (running it explicitly on the tests/ directory avoids interference with the venv folders).
Package: async-newtel
Async-NewTelNew-Tel simple async client based on httpx.Installationpipinstallasync-newtelUsageimportasync_newtelimportosAPI_KEY=os.environ.get('API_KEY')SIGNING_KEY=os.environ.get('SIGNING_KEY')number='+1234567890'code='1234'# Send email with context managerasyncwithasync_newtel.AsyncClient(api_key=API_KEY,signing_key=SIGNING_KEY)asclient:response=awaitclient.call(number,code)# Send email without context managerclient=simple_sendgrid.AsyncClient(api_key=API_KEY,signing_key=SIGNING_KEY)awaitclient.open()response=awaitclient.call(number,code)awaitclient.close()
Package: async-nookipedia
async-nookipediaAsync API wrapper for Nookipedia API utilizing theaiohttppackage.Installationasync-nookipedia can be installed via pip.pip install async-nookipediaDocumentationDocs can be found onreadthedocs.ioUsageimportasynciofromnookipediaimportNookipediaapi_key="API_KEY"asyncdefmain():api=Nookipedia(api_key=api_key,cached_api=True)villager=awaitapi.get_villager('marshal')print(villager.name)critter=awaitapi.get_critter('spider')print(critter.name)fossil=awaitapi.get_fossil('amber')print(fossil.name)loop=asyncio.get_event_loop()loop.run_until_complete(main())RequirementsPython >= 3.6aiohttppython-dateutilimportlib_metadataIssues and FeaturesIf you're having any issues or want additional features please create an Issue ongithub.