Saravanan666/pypi-org huggingface dataset:
Package: async-cloud-tasks
Async Cloud TasksUse Cloud Tasks to easily defer functions executions in your web applications 🍯Inspired bydjango-cloud-tasks, thanks to GeorgeLubaretsi 👏🏻👏🏻👏🏻IntegrateGoogle Cloud Taskswith web applications without the need to create an exclusive endpoint to handle tasks.
The package provides easy to use decorator to create task handlers.
App looks for tasks incloud_tasks.pyfiles in your installed applications and auto-registers them.PrerequisitesPython 3.7+Dependenciesgoogle-cloud-tasksSupportIMPORTANT: Now it is only giving support forDjangoframework.InstallationInstall the package from PyPipipinstallasync-cloud-tasksAddasync_cloud_taskstoINSTALLED_APPS:INSTALLED_APPS=(# ...'async_cloud_tasks',# ...)Add configuration to your settingsASYNC_CLOUD_TASKS={'gcp_location':'<GCP TASK QUEUE LOCATION>','gcp_project_name':'<GCP TASK QUEUE PROJECT NAME>','task_handler_root_url':'_tasks/','service_url':'<BASE SERVICE URL>','handler_secret':'<SECRET KEY TO BE USED FOR TASK HANDLER AUTHENTICATION>'}# This setting allows you to debug your cloud tasks by running actual task handler function locally# instead of sending them to the task queue. Default: FalseASYNC_CLOUD_TASKS_EXECUTE_LOCALLY=FalseAdd cloud task views to your urls.py (must resolve to the same url astask_handler_root_url)# urls.py# ...fromdjango.urlsimportpath,includefromasync_cloud_tasksimporturlsasdct_urlsurlpatterns=[# ...path('_tasks/',include(dct_urls)),]Quick start (only for Django)Simply import the task decorator and define the task insidecloud_tasks.pyin your app.
First parameter should always berequestwhich is populated after task is executed by Cloud Task service.You can get actual request coming from Cloud Task service by accessingrequest.requestin your task body and
additional attributes such as:request.task_id,request.request_headers# cloud_tasks.py# ...fromasync_cloud_tasks.decoratorsimporttask@task(queue='default')defexample_task(request,p1,p2):print(p1,p2)print(request.task_id)Pushing the task to the queue:frommy_app.cloud_tasksimportexample_taskexample_task(p1='1',p2='2').defer()It is also possible to run an actual function usingrunmethod ofCloudTaskWrapperobject instance that is returned after task is called (this can be useful for debugging):task=example_task(p1=i,p2=i)task.run()ReferencesCloudTasksClient
Package: async-connect.py
async-connect.py is the asynchronous version ofconnect.pyIf you want to report errors, bugs or typos you can join the discord guild listed next to the build shield.InstallingTo install the library, you can just run the following command:python3-mpipinstall-Uasync-connect.pyTo install the development version, do the following:python3-mpipinstall-Uhttps://github.com/GiovanniMCMXCIX/async-connect.py/archive/master.zip#egg=async-connect.py[performance]RequirementsPython 3.6+aiohttplibraryExtra RequirementsThis library contains an extra requirement that is nameperformancein other the library to work faster.
You can install it using the following command:python3-mpipinstall-Uasync-connect.py[performance]Note for usinguvloopon async-connect.py you need to parse it toconnect.Client()like so:importasyncioimportuvloopimportasync_connectasconnectasyncio.set_event_loop_policy(uvloop.EventLoopPolicy())loop=asyncio.get_event_loop()client=connect.Client(loop=loop)# rest of your code hereExampleimportasync_connectasconnectasyncdefget_release():releases=awaitclient.search_release('friends')print('Found the following:')forreleaseinreleases:print('{0.title}by{0.artists}[{0.catalog_id}] was released on{0.release_date}''and has{1}track(s)'.format(release,len(awaitrelease.tracks.values())))if__name__=="__main__":client=connect.Client()client.loop.run_until_complete(get_release())
Package: async-couch
Async-CouchResourcesDocumentationThis is simple asynchronous python CouchDB client that works with
aiohttp, httpx and able to be adopted easily to any other http client.Requirements:= Python 3.7Allowed http clientaiohttphttpxHow to installpipinstallasync-couchGet Startedimportasynciofromasync_couchimportget_couch_clientfromasync_couch.http_clientsimportHttpxCouchClientasyncdefexample(client,doc_id:str):awaitclient.db_create('test_index')awaitclient.doc_create_or_update('test_index',doc_id,dict(val=1))response=awaitclient.doc_get('test_index',response.model._id)assertresponse.model._id==doc_idawaitclient.attachment_upload('test_index',response.model._id,'attachment_name','text/plain',b'\0')if__name__=='__main__':loop=asyncio.get_event_loop()client=get_couch_client(request_adapter=HttpxCouchClient)loop.run_until_complete(example(client,'document_name'))ToDoRest endpointsAiohttp adapter
Package: async-covid
Async CovidBased on Ahmednafies' COVIDmodule.DescriptionAn async Python package to get information regarding the novel corona virus provided
by Johns Hopkins university and worldometers.infoDocumentation not ready yet, but everything is shown in this README file.Requirementspython >= 3.6How to installpip install async-covidDependenciespydantic
asyncio
aiohttpHow to useExampleimportasynciofromasync_covidimportCovidasyncdefmain():print(awaitcovid.get_data())if__name__==__main__:covid=COVID()loop=asyncio.get_event_loop()loop.run_until_complete(main())loop.close()John Hopkins University APIGet All Dataawaitcovid.get_data()Result[CovidModel<id=175,country=US,confirmed=7554434,active=4342532,deaths=211905,recovered=2999895,latitude=40.0,longitude=-100.0,last_update=1602163423000>,CovidModel<id=14,country=Bangladesh,confirmed=374592,active=80816,deaths=5460,recovered=288316,latitude=23.685,longitude=90.3563,last_update=1602163423000>,...]List CountriesThis comes in handy when you need to know the available names of countries
when usingget_status_by_country_name, eg. "The Republic of Moldova" or just "Moldova"
So use this when you need to know the country exact name that you can use.awaitcovid.list_countries()Result[CountryModel<id=175,name=US>,CountryModel<id=80,name=India>,...]Get Status By Country IDawaitcovid.get_status_by_country_id(14)ResultCovidModel<id=14,country=Bangladesh,confirmed=374592,active=80816,deaths=5460,recovered=288316,latitude=23.685,longitude=90.3563,last_update=1602163423000>Get Status By Country Nameawaitcovid.get_status_by_country_name("bangladesh")ResultCovidModel<id=14,country=Bangladesh,confirmed=374592,active=80816,deaths=5460,recovered=288316,latitude=23.685,longitude=90.3563,last_update=1602163423000>Get Total Active casesawaitcovid.get_total_active_cases()Get Total Confirmed casesawaitcovid.get_total_confirmed_cases()Get Total Recovered casesawaitcovid.get_total_recovered()Get Total Deathsawaitcovid.get_total_deaths()Getting data from Worldometers.infocovid=Covid(source="worldometers")Get Dataawaitcovid.get_data()Result[CovidModel<country=NorthAmerica,confirmed=9332106,new_cases=10355,deaths=322513,recovered=6101706,active=2907887,critical=17932,new_deaths=512,total_tests=0,total_tests_per_million=0,total_cases_per_million=0,total_deaths_per_million=0,population=0>...]Get Status By Country Nameawaitcovid.get_status_by_country_name("india")ResultCovidModel<country=India,confirmed=6835655,new_cases=2667,deaths=105554,recovered=5827704,active=902397,critical=8944,new_deaths=0,total_tests=83465975>List Countriescountries=awaitcovid.list_countries()Result['china','italy','usa','spain','germany',...]Get Total Active casesactive=awaitcovid.get_total_active_cases()Get Total Confirmed casesconfirmed=awaitcovid.get_total_confirmed_cases()Get Total Recovered casesrecovered=awaitcovid.get_total_recovered()Get Total Deathsdeaths=awaitcovid.get_total_deaths()
Package: async-cron
async_cronthis repo is influenced by schedule.we supply a async scheduler and async function supportyou can easily integrate this lib to you async program,with no blockingInstallpip install async-cronUsage examplesimportasynciofromasync_cron.jobimportCronJobfromasync_cron.scheduleimportSchedulerasyncdeftest(*args,**kwargs):print(args,kwargs)deftt(*args,**kwargs):print(args,kwargs)msh=Scheduler(locale="zh_CN")myjob=CronJob(name='test',run_total=3).every(5).second.go(test,(1,2,3),name=123)job2=CronJob(name='exact',tolerance=100).at("2019-01-15 16:12").go(tt,(5),age=99)job3=CronJob(name='very_hour').every().hour.at(":44").go(tt,(5),age=99)job3=CronJob(name='hour').every().hour.at(":00").go(tt,(5),age=99)job4=CronJob(name='minute').every(1).minute.go(tt,(5),age=99)job5=CronJob(name='weekday').weekday(2).at("11:18").go(tt,(5),age=99)job6=CronJob(name='monthday').monthday(16).at("11:22").go(tt,(5),age=99)job7=CronJob(name='monthday').every(5).monthday(16).at("11:22").go(tt,(5),age=99)msh.add_job(myjob)msh.add_job(job2)msh.add_job(job3)msh.add_job(job4)msh.add_job(job5)msh.add_job(job6)msh.add_job(job7)# jobload is only a special job,who gen jobs from config# below means, this job load will check every 1 second for cron updates# if any updates found,new job will be add to scheduler# you dont have the direct way to delete jobs# but you can modify the crons total_times to 0 or 1 to delete it# by default,FileJobLoader use MultiThread,you can use MultiProcess by add# thread=Falsef_cron=FileJobLoader(name='f_cron',file_path='t_cron',log_path='.',thread=False)fjob=CronJob(name='fjob',run_total=1).every(1).second.go(f_cron.run,msh)msh.add_job(fjob)loop=asyncio.get_event_loop()try:loop.run_until_complete(msh.start())exceptKeyboardInterrupt:print('exit')cron file useage:parameter separate by blank.in item separate by commacronnamejobenvrun_times*/1,*,*,*,*test/bin/python,tt.pyaa=123,bb=34510example as follow:common cron*/1,*,*,*,*test /bin/python,tt.py aa=123,bb=345 1delete cron*/1,*,*,*,*test /bin/python,tt.py aa=123,bb=345 0cron only support:*,10,*/10format. which fulfills mostly screenLicenseThe async_cron is offered under MIT license.
Package: async-cse
async-cseAsyncio API wrapper for theGoogle Custom Search JSON API.InstallationWant stable releases?pip3 install -U async_cseLiving on the edge? Want hotfixes?pip3 install -U git+https://github.com/crrapi/async-cseUsageimportasync_cseclient=async_cse.Search("Your API Key")# create the Search client (uses Google by default!)results=awaitclient.search("Python",safesearch=False)# returns a list of async_cse.Result objectsfirst_result=results[0]# Grab the first resultprint(first_result.title,first_result.description,first_result.url,first_result.image_url)# Title, snippet, URL, and Image URL (if specified)awaitclient.close()# Run this when cleaning up.Getting image resultsTo get image results with the default engine, useimage_search=Truewhen searching, like so:awaitclient.search("Python",safesearch=False,image_search=True)# returns a list of async_cse.Result objectsCustom search enginesTo use Search objects with a custom search engine, provide the ID of the search engine.async_cse.Search("Your API Key",engine_id="015786823554162166929:mywctwj8es4")SafeSearchSafeSearch can also be turned off by settingsafesearch=Falsewhen using thesearch()method.Getting an API keyYou can get an API key by goinghereand scrolling down to theAPI keysection.(New in 0.3.0) API Key ShufflingKey shuffling may be used as a fail-safe for keys that run out of requests, effectively giving you +100 requests for each key passed.Just pass a list of keys when instantiating yourSearchclient.Here's a demonstration of this:importasync_cseclient=async_cse.Search(["API Key 1","API Key 2","API Key 3"])# Multiple keys as a listawaitclient.search("Python")# Uh oh, one of these keys doesn't work! Trying again with another...Whenasync-csedetects a non-working key, it will remove it from its internal list and retry the search.
Package: asynccsv
Async CSV LoggerThis module is a async csv logger that helps you log performance of your algorithm.DescriptionThis module is intented to be a csv logger which will write to file async-ly.With the hope to have minimum performance impact on benchmarking your algorithm (i.e. I/O blocking to write to disk), this is especially useful for logging performance at each iteration/time-step. Internally, it utilise threading to async write to file.There are two way to initialise and use the logger.Installpip install asynccsv1. Recommended way (with block)importtimeimportdatetimefromasynccsvimportAsyncCSVLoggerwithAsyncCSVLogger('path_of_your_log.csv')aslogger:# csv titleslogger.write(['Time','Accuracy','Num of nodes'])# do your other stuff# ......foriinrange(10):# perform calculation# ....# write results to filelogger.write([datetime.datetime.now().strftime("%S.%f"),acc,num_nodes])time.sleep(0.5)2. The normal wayimporttimefromasynccsvimportAsyncCSVLoggerclassMyAwesomeAlgorithm():def__init__(self):# with the 'log_timestamp' flag it will automatically log timestampself.logger=AsyncCSVLogger('path_of_your_log.csv',log_timestamp=True)self.logger.write(['Time','Accuracy','Num of nodes'])defrun(self):# perform calculation# ...logger.write([acc,num_nodes])time.sleep(0.5)if__name__=='__main__':awesome=MyAwesomeAlgorithm()foriinrange(10):awesome.run()# You SHOULD run this to properly close the threading and force# everything to be written to disk# This is automatically done by the 'with' block in previous exampleawesome.logger.close()With both methods, the final content ofpath_of_your_log.csvwill look something like:"Time","Accuracy","Num of nodes"
"57.689359","92.5","11"
"58.189979","93.5","12"
"58.690520","94.22","13"
"59.191268","93.5","15"
"59.692062","92.2","17"
"00.192850","92.4","22"
"00.693661","94.8","26"
"01.194634","96.6","27"
"01.695368","94.1","30"
"02.196014","97.5","42"
Package: async-customerio
async-customerio is a lightweight asynchronous client to interact with CustomerIOFree software: MIT licenseRequires: Python 3.7+FeaturesFully asyncInterface preserved as Official Python ClientcustomeriohasSend push notificationSend messagesInstallationpipinstallasync-customerioGetting startedimportasynciofromasync_customerioimportAsyncCustomerIO,Regionsasyncdefmain():site_id="Some-id-gotten-from-CustomerIO"api_key="Some-key-gotten-from-CustomerIO"cio=AsyncCustomerIO(site_id,api_key,region=Regions.US)awaitcio.identify(id=5,email="customer@example.com",first_name="John",last_name="Doh",subscription_plan="premium",)awaitcio.track(customer_id=5,name="product.purchased",product_sku="XYZ-12345",price=23.45)if__name__=="__main__":asyncio.run(main())InstantiatingAsyncCustomerIOobjectCreate an instance of the client with yourCustomer.io credentials.fromasync_customerioimportAsyncCustomerIO,Regionscio=AsyncCustomerIO(site_id,api_key,region=Regions.US)regionis optional and takes one of two values —Regions.USorRegions.EU. If you do not specify your region, we assume
that your account is based in the US (Regions.US). If your account is based in the EU and you do not provide the correct region
(Regions.EU), we'll route requests to our EU data centers accordingly, however, this may cause data to be logged in the US.Securely verify requestsdocfromasync_customerioimportvalidate_signaturedefmain():webhook_signing_key=("755781b5e03a973f3405a85474d5a032a60fd56fabaad66039b12eadd83955fa")x_cio_timestamp=1692633432# header  valuex_cio_signature="d7c655389bb364d3e8bdbb6ec18a7f1b6cf91f39bba647554ada78aa61de37b9"# header valuebody=b'{"key": "value"}'ifvalidate_signature(signing_key=webhook_signing_key,timestamp=x_cio_timestamp,request_body=body,signature=x_cio_signature,):print("Request is sent from CustomerIO")else:print("Malicious request received")if__name__=="__main__":main()Licenseasync-customeriois offered under the MIT license.Source codeThe latest developer version is available in a GitHub repository:https://github.com/healthjoy/async-customerio
Package: asyncdagpi
asyncdagpiPowerful Asynchronous Wrapper for dagpidagpi.xyzInstallationpipinstallasyncdagpiData APISome endpoints like WTP, PickupLine and Logo will return Objects while Waifu will return a Dictionary. Everything else will return a string.fromasyncdagpiimportClientdagpi=Client("dagpi token")# For WTP Objectwtp=awaitdagpi.wtp()#For Roastroast=awaitdagpi.roast()Image ManipulationAll Image endpoints return an Image object. This has many properties that can be useful for developers. For Basic implementations are displayedDiscord.pyfromdiscord.extimportcommandsimportdiscordfromasyncdagpiimportClient,ImageFeaturesbot=commands.Bot(command_prefix="!")dagpi=Client("dagpi token")@bot.command()asyncdefpixel(ctx,member:discord.Member):url=str(member.display_avatar.with_format("png").with_size(1024))img=awaitdagpi.image_process(ImageFeatures.pixel(),url)file=discord.File(fp=img.image,filename=f"pixel.{img.format}")awaitctx.send(file=file)Pycordfromdiscord.extimportcommandsimportdiscordfromasyncdagpiimportClient,ImageFeaturesbot=discord.Bot()dagpi=Client("dagpi token")@bot.slash_command(guild_ids=[...])asyncdefpixel(ctx,member:discord.Member=None):# Passing a default value makes the argument optionaluser=memberorctx.authorurl=str(member.display_avatar.with_format("png").with_size(1024))img=awaitdagpi.image_process(ImageFeatures.pixel(),url)file=discord.File(fp=img.image,filename=f"pixel.{img.format}")Writing To FilefromasyncdagpiimportClient,ImageFeaturesdagpi=Client("dagpi token")img=awaitdagpi.image_process(ImageFeatures.pixel(),"https://dagbot-is.the-be.st/logo.png")#it will auto chose the right format and write to current directoryimg.write("pixel")#will create pixel.png in this casePython PillowfromasyncdagpiimportImageFeatures,ClientfromPILimportImagedagpi=Client("dagpi token")img=awaitdagpi.image_process(ImageFeatures.pixel(),"https://dagbot-is.the-be.st/logo.png")im=Image.open(img.image)Kwargs ExamplefromasyncdagpiimportImageFeatures,Clientdagpi=Client("dagpi token")img=awaitdagpi.image_process(ImageFeatures.tweet(),"https://dagbot-is.the-be.st/logo.png",text="This is asyncdagpi tweeting live from dagpi.xyz!",username="Asyncdagpi")For More Thorough Examples and Feature list read the documentationDocsDagpi Docs
Package: asyncdagreq
unofficial DagpiWrapperAsync Wrapper for DagpiOFFICIAL DAGPI WEBSITEOFFICIAL GITHUBREPOAuthor: Ali™ AKA Ali-TM-originalJust A small project to imporve my skills in Object Oriented
Programming, inspired from my previous discord.py canny commandNOT READY FOR USE YETtasks remaining:[STRIKEOUT:1>Error Detection]2>.Testing
3>.Get this up and running on pypiCURRENT STATE : FunctionalUsage with discord.py (till now)super simpleRoastfrom asyncdagreq import Client
import json

object = Client.Asyncdagreq('your token')

@bot.command()
async def roast(ctx):
    roast = await object.roast()
    x = roast.decode("utf-8")
    j = json.loads(x)
    await ctx.send(j['roast'])USING IMAGE METHODSfrom asyncdagreq import Client
import json

object = Client.Asyncdagreq('your token')

@bot.command()
async def captcha(ctx):
    url = str(ctx.message.author.avatar_url_as(format="png", static_format="png", size=1024))
    img = await object.captcha(str(url), "hello")
    file = discord.File(img, "pixel.png")
    await ctx.send(file=file)
Package: async-dali
This is a python package that facilitates reading from and control over aDALI (IEC 62386)protocol bus using a USB adapter such as theTridonic USBadapter.The intention for this package is that it will be used to add DALI support toHome AssistantApproachDALI uses a short addressing scheme, assigning every device on the bus a number between 0 and 63 inclusive.  But these addresses can change if a re-address operation is performed.  Instead, when a device is created by this library, it determines a unique identifier by concatenating three pieces of information:The DeviceGTINThe device's serial numberThe logical enpoint number. A single device might house more than one gear endpoint. For example, aTridonic 4 channel relayadvertises itself as 4 separate devices, but each one will have the same GTIN and serial number.All of this information is loaded in from memory bank 0 of the device (seethis articlefor more details.).  The unique Id isn't particularly human readable, but it will remain static for the lifetime of that device.when dealing with devices, you should always use theunique_idproperty to refer to devices.  That way they'll still work if a re-address is done or the device is moved to another bus.UsageAll useage starts with the Bus Transciever.  This is the component that interfaces to USB and will send/receive commands.  This class exclusively uses asyncio.Drivers can be explicitly opened using the constructor, or scanned for usingscan_for_dali_transcievers()which will return a list of all auto-discovered drivers.These drivers are also intended to pick up commands that are issued by other devices on the bus.  This is important to keep any visible state displayed to a user in sync with what has happened, without having to do a lot of polling (which will use up more power).  to listen to events on the bus, calladd_message_callback()on the bus transciever.  However, if you just want to send commands and get responses back, you don't need to use the callback system.Examplefromasync_daliimportTridonicDaliimportasyncioasyncdeftestit():busses=TridonicDali.scan_for_transcievers()iflen(busses)==0:raiseException("No DALI transciever found")print("Opening first discovered bus",busses[0])asyncwithbusses[0]asbus:print("Scanning for gear")gear=awaitbus.scan_for_gear()iflen(gear)==0:raiseException("No gear found on the bus")g=gear[0]print("Toggling",g.unique_id)# Toggle the light on then off againawaitg.on()awaitasyncio.sleep(2)awaitg.off()print("Done")if__name__=="__main__":loop=asyncio.new_event_loop()asyncio.set_event_loop(loop)loop.run_until_complete(testit())loop.close()
Package: async-dash
Async Dashasync-dashis an async port ofPlotly Dashlibrary, created by replacing its flask
backend with its async counterpartquart.It started with my need to be able to create realtime dashboards withdash, specifically with event-driven
architecture. Usingasync-dashwith components fromdash-extensionssuch as WebSocket, EventSource, etc. you can create truly events based or realtime dashboards.Table Of ContentsInstallationUsageMotivationCaveatsAlternativesKnown IssuesTODOInstallationpipinstallasync-dashUsagefromasync_dashimportDashfromdashimporthtml,dccSimple Exampleimportasyncioimportrandomfromasync_dashimportDashfromdashimporthtml,Output,Input,dccfromdash_extensionsimportWebSocketfromquartimportwebsocket,jsonapp=Dash(__name__)app.layout=html.Div([WebSocket(id="ws"),dcc.Graph(id="graph")])app.clientside_callback("""function(msg) {if (msg) {const data = JSON.parse(msg.data);return {data: [{y: data, type: "scatter"}]};} else {return {};}}""",Output("graph","figure"),[Input("ws","message")],)@app.server.websocket("/ws")asyncdefws():whileTrue:output=json.dumps([random.randint(200,1000)for_inrange(6)])awaitwebsocket.send(output)awaitasyncio.sleep(1)if__name__=="__main__":app.run_server()MotivationIn addition to all the advantages of writing async code,async-dashenables you to:run truly asynchronous callbacksuse websockets, server sent events, etc. without needing to monkey patch the Python standard libraryusequart/fastapi/starletteframeworks with
your dash apps side by sideuse HTTP/2 (especially server push) if you use it HTTP/2 enabled server such
ashypercorn.CaveatsI'm maintaining this library as a proof of concept for now. It should not be used for production. You can see the
deviation fromdashhere.If you do decide to use it, I'd love to hear your feedback.Alternativesdash-devicesdash-devicesis another async port based onquart. It's capable of using websockets even for callbacks, which makes
it way faster than either ofdashorasync-dash. However, the library stands outdated at the time this document was
last updated.PS:async-dashis highly inspired by thedash-devices. Difference being thatasync-dashtries to followdashas close as possible.Known IssuesException handling in callbacks indebug modeis broken. So its disabled internally.TODOWrite examples/articles showcasing the use cases for asynchronousdash.Gather reviews and feedback from the Dash Community.