package
stringlengths 1
122
| pacakge-description
stringlengths 0
1.3M
|
---|---|
aiovodafone | aiovodafonePython library to control Vodafone StationInstallationInstall this via pip (or your favourite package manager):pip install aiovodafoneContributors ✨Thanks goes to these wonderful people (emoji key):This project follows theall-contributorsspecification. Contributions of any kind welcome!CreditsThis package was created withCopierand thebrowniebroke/pypackage-templateproject template. |
aiovotifier | Aio-VotifierAn asynchronous MInecraft server votifier client in PythonExample Usage:fromaiovotifierimportVotifierClientimportasyncioasyncdefmain():client=VotifierClient("127.0.0.1",8192,"testservicename","token/rsa key")# VotifierClient.vote(...) automatically determines the protocol and key formatawaitclient.vote("username","user address")awaitclient.vote("user2")awaitclient.v1_vote("username","user address")# only supports v1 protocolawaitclient.nu_vote("username","user address")# only supports NuVotifier/v2 protocolasyncio.run(main())Documentationclassaiovotifier.VotifierClient(host:str, port:int, service_name:str, secret:str)Arguments:host: str-The hostname or IP of the votifier serverport: int-The port of the votifier server, commonly 8192service_name: str-The name of the service that sends the votesecret: str-The public RSA key or the token found inconfig.ymlMethods:vote(username: str, user_address: str = "127.0.0.1")-sends a vote to the votifier server, automatically detects and handles the protocol and type of secretv1_vote(username: str, user_address: str = "127.0.0.1")-sends a Votifier v1 vote to a votifier v1 servernu_vote(username: str, user_address: str = "127.0.0.1") -> dict-sends a NuVotifier / v2 vote to a NuVotifier server, returns the response from the serverclassaiovotifier.VotifierHeader(header:bytes, version:str, token:str= None)Arguments:header: bytes-The header received from the votifier serverversion: str-The version of the votifier serverchallenge: str = None-The challenge, included only if the votifier server is v2/NuVotifierMethods:@classmethod parse(header: bytes)-Returns a newVotifierHeader, parsed from the input bytesfunctionaiovotifier.votifier_v1_vote(r:asyncio.StreamReader, w:asyncio.StreamWriter, service_name:str, username:str, user_address:str, key:cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey)Sends a Votifier v1 vote to a Votifier v1 serverfunctionaiovotifier.nuvotifier_vote(r:asyncio.StreamReader, w:asyncio.StreamWriter, service_name:str, username:str, user_address:str, token:str, challenge:str) ->dictSends a NuVotifier / v2 vote to a NuVotifier serverexceptionaiovotifier.VotifierErrorBase class that all votifier exceptions derive fromexceptionaiovotifier.VotifierHeaderErrorRaised when the header from the votifier server is invalidexceptionaiovotifier.UnsupportedVersionErrorRaised when the votifier version is unsupportedexceptionaiovotifier.NuVotifierResponseErrorRaised when the response from the votifier server contains a status that is not OKCreditsaiovotifier was based off the code and documentation belowhttps://github.com/ano95/votifier2-pyhttps://www.npmjs.com/package/votifier-client/v/0.1.0?activeTab=dependentshttps://github.com/vexsoftware/votifierhttps://github.com/NuVotifier/NuVotifier/wiki/Technical-QA |
aiovty | DescriptionInstallationUsageDescriptionaiovtyis an asynchronous implementation of the VTY protocol.InstallationInstall the last released version usingpip:python3-mpipinstall--user-UaiovtyOr install the latest version from sources:[email protected]:matan1008/aiovty.gitcdaiovty
python3-mpipinstall--user-U-e.UsageTo create a client, you need to supply the server's prompt name (e.g.'Router'):fromaiovtyimportAioVtyClientvty=AioVtyClient('Router')Then you can connect giving address:connection_string=awaitvty.connect('127.0.0.1',23)Note that connecting returns the "connection string", which is the data sent before the first prompt.After connection you can send your command:command_response=awaitvty.command(b'show ip')You can also enter enabled mode:awaitvty.enable()And initialize a configure terminal:awaitvty.configure_terminal()awaitvty.command(b'router rip')print(vty.node)# Prints `config-router` |
aiowallhaven | aiowallhavenaiowallhaven is an asynchronous API wrapper for popular
wallpaper hosting site wallhaven.cc.Basic Usage:import asyncio
from aiowallhaven import WallHavenAPI
wallhaven = WallHavenAPI("Your-API-key")
async def wallpaper_details():
request = await wallhaven.get_wallpaper("5758y8")
print(request)
loop = asyncio.get_event_loop()
loop.run_until_complete(wallpaper_details())PrerequisitesThe following dependencies are required:Python 3.10aiohttp libraryaiolimiter libraryInstallation$ pip install aiowallhavenDocumentationThe documentation is available atreadthedocs.io.Licenseaiowallhaven is developed and distributed under the MIT
license. |
aiowamp | aiowampClient library for the WAMP protocol.ExamplesSee theexamples/directory for more. |
aiowaqi | Python: WAQIAsynchronous Python client for the WAQI API.AboutThis package allows you to request data about air quality around the world.InstallationpipinstallaiowaqiUsageimportasynciofromaiowaqiimportWAQIClientasyncdefmain()->None:"""Show example of fetching air quality for Utrecht."""asyncwithWAQIClient()asclient:client.authenticate("token")air_quality=awaitclient.get_by_city("utrecht")print(air_quality)if__name__=="__main__":asyncio.run(main())Changelog & ReleasesThis repository keeps a change log usingGitHub's releasesfunctionality. The format of the log is based onKeep a Changelog.Releases are based onSemantic Versioning, and use the format
ofMAJOR.MINOR.PATCH. In a nutshell, the version will be incremented
based on the following:MAJOR: Incompatible or major changes.MINOR: Backwards-compatible new features and enhancements.PATCH: Backwards-compatible bugfixes and package updates.ContributingThis is an active open-source project. We are always open to people who want to
use the code or contribute to it.We've set up a separate document for ourcontribution guidelines.Thank you for being involved! :heart_eyes:Setting up development environmentThis Python project is fully managed using thePoetrydependency manager. But also relies on the use of NodeJS for certain checks during development.You need at least:Python 3.11+PoetryNodeJS 12+ (including NPM)To install all packages, including all development requirements:npminstall
poetryinstallAs this repository uses thepre-commitframework, all changes
are linted and tested with each commit. You can run all checks and tests
manually, using the following command:poetryrunpre-commitrun--all-filesTo run just the Python tests:poetryrunpytestAuthors & contributorsThe content is byJoost Lekkerkerker.For a full list of all authors and contributors,
checkthe contributor's page.LicenseMIT LicenseCopyright (c) 2023 Joost LekkerkerkerPermission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. |
aiowatcher | Library to "watch" files in a directory and call a
callback function(filename, lines)every time one of the monitored files is recorded, in real time.In practical terms, this can be compared to UNIX'stail -F * .logcommand,
but instead of having lines printed in stdout, a Python function is called.Like tail, it is in charge of "watching" new files that are
created after startup and "unlock" those that are removed in the meantime.
This means that you will be able to "follow" and support rotating log files as well.Key FeaturesUses Asyncio for asynchronous reading and monitoring.The implementation chooses automatically depending on the compatibility of the system.Monitoring of several files in the same directory or just one.Asynchronous callback function.Getting startedAll code samples require Python 3.6+.Basic Usageimport asyncio
from aiowatcher import AIOWatcher
async def callback(filename, line):
print(line)
async def main():
lw = AIOWatcher('var', callback, extensions=['txt'])
await lw.init()
await lw.loop()
loop = asyncio.get_event_loop()
loop.run_until_complete(main())Non blockingimport asyncio
from aiowatcher import AIOWatcher
async def callback(filename, line):
print(line)
async def main():
lw = AIOWatcher('var', callback, extensions=['txt'])
while True:
await lw.loop(blocking=False)
await asyncio.sleep(0.1)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())Tailimport asyncio
from aiowatcher import AIOWatcher
async def callback(filename, lines):
for line in lines:
print(line[:-1])
async def main():
lw = AIOWatcher('var', callback, extensions=['txt'])
await lw.tail(3)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())Licenseaiowatcheris offered under the Apache 2 license.Source codeThe latest version of the developer is available on a GitHub repository:https://github.com/py-paulo/aiowatcher.gitChangelog0.0.5 (22-09-2020)FeaturesnewAIOWatcher().tailfunction to readNlines from a file and return as list.BugfixesAIOWatcher.readlines()returns a list instead of a string. |
aio-watts-vision | TODO: Rewrite me. Append your package’s long description.StatusRequirementsPython 3.7 overFeaturesToDo: Rewrite me.Setup$ python -m pip install --user aio-watts-vision
or
(venv)$ python -m pip install aio-watts-visionUsageToDo: Rewrite me.$ python
>>> import aio_watts_vision
>>> aio_watts_vision.sample.hello()
'hello'
>>>ChangeLog0.1.0 (2022-08-12)Initial release. |
aiowatttime | 🌎 aiowatttime: an asyncio-based, Python3 library for WattTime emissions dataaiowatttimeis a Python 3, asyncio-friendly library for interacting withWattTimeemissions data.Python VersionsInstallationUsageContributingPython Versionsaiowatttimeis currently supported on:Python 3.10Python 3.11Python 3.12InstallationpipinstallaiowatttimeUsageGetting an API KeySimply clone this repo and run the included interactive script:$script/registerNote that WattTime offers three plans: Visitors, Analyst, and Pro. The type you use
will determine which elements of this library are available to use. You can read more
detailshere.Creating and Using a ClientTheClientis the primary method of interacting with the API:importasynciofromaiowatttimeimportClientasyncdefmain()->None:client=awaitClient.login("<USERNAME>","<PASSWORD>")# ...asyncio.run(main())By default, the library creates a new connection to the API with each coroutine. If
you are calling a large number of coroutines (or merely want to squeeze out every second
of runtime savings possible), anaiohttpClientSessioncan be used for
connection pooling:importasynciofromaiohttpimportClientSessionfromaiowatttimeimportClientasyncdefmain()->None:asyncwithClientSession()assession:client=awaitClient.login("<USERNAME>","<PASSWORD>",session=session)# ...asyncio.run(main())Programmatically Requesting a Password Resetawaitclient.async_request_password_reset()Getting Emissions DataGrid RegionIt may be useful to first get the "grid region" (i.e., geographical info) for the area
you care about:awaitclient.emissions.async_get_grid_region("<LATITUDE>","<LONGITUDE>")# >>> { "id": 263, "abbrev": "PJM_NJ", "name": "PJM New Jersey" }Getting emissions data will require either your latitude/longitudeorthe "balancing
authority abbreviation" (PJM_NJin the example above).Realtime Dataawaitclient.emissions.async_get_realtime_emissions("<LATITUDE>","<LONGITUDE>")# >>> { "freq": "300", "ba": "CAISO_NORTH", "percent": "53", "moer": "850.743982", ... }Forecasted Dataawaitclient.emissions.async_get_forecasted_emissions("<BA_ABBREVATION>")# >>> [ { "generated_at": "2021-08-05T09:05:00+00:00", "forecast": [...] } ]You can also get the forecasted data using a specific start and enddatetime.datetime:fromdatetimeimportdatetimeawaitclient.emissions.async_get_forecasted_emissions("<BA_ABBREVATION>",start_datetime=datetime(2021,1,1),end_datetime=datetime(2021,2,1),)# >>> [ { "generated_at": "2021-08-05T09:05:00+00:00", "forecast": [...] } ]Historical Dataawaitclient.emissions.async_get_historical_emissions("<LATITUDE>","<LONGITUDE>")# >>> [ { "point_time": "2019-02-21T00:15:00.000Z", "value": 844, ... } ]You can also get the historical data using a specific start and enddatetime.datetime:fromdatetimeimportdatetimeawaitclient.emissions.async_get_historical_emissions("<LATITUDE>","<LONGITUDE>",start_datetime=datetime(2021,1,1),end_datetime=datetime(2021,2,1),)# >>> [ { "point_time": "2019-02-21T00:15:00.000Z", "value": 844, ... } ]Retry LogicBy default,aiowatttimewill handle expired access tokens for you. When a token expires,
the library will attempt the following sequence 3 times:Request a new tokenPause for 1 second (to be respectful of the API rate limiting)Execute the original request againBoth the number of retries and the delay between retries can be configured when
instantiating a client:importasynciofromaiohttpimportClientSessionfromaiowatttimeimportClientasyncdefmain()->None:asyncwithClientSession()assession:client=awaitClient.async_login("user","password",session=session,# Make 7 retry attempts:request_retries=7,# Delay 4 seconds between attempts:request_retry_delay=4,)asyncio.run(main())As always, an invalid username/password combination will immediately throw an exception.Custom LoggerBy default,aiowatttimeprovides its own logger. If you should wish to use your own, you
can pass it to the client during instantiation:importasyncioimportloggingfromaiohttpimportClientSessionfromaiowatttimeimportClientCUSTOM_LOGGER=logging.getLogger("my_custom_logger")asyncdefmain()->None:asyncwithClientSession()assession:client=awaitClient.async_login("user","password",session=session,logger=logger,)asyncio.run(main())ContributingThanks to all ofour contributorsso far!Check for open features/bugsorinitiate a discussion on one.Fork the repository.(optional, but highly recommended) Create a virtual environment:python3 -m venv .venv(optional, but highly recommended) Enter the virtual environment:source ./.venv/bin/activateInstall the dev environment:script/setupCode your new feature or bug fix on a new branch.Write tests that cover your new functionality.Run tests and ensure 100% code coverage:poetry run pytest --cov aiowatttime testsUpdateREADME.mdwith any new documentation.Submit a pull request! |
aiowc | Asynchronous Python wrapper for WooCommerce REST API.Gives you asynchronous access to the REST API.
Based onaiohttpandwc-api-python.PRs are highly appreciated!Installationpip install aiowcorpip install"git+https://github.com/vakochetkov/aiowc"Getting startedGenerate API credentialsImport aiowc:fromaiowcimportAPI,APISessionSet API parameters:wcapi=API(url="https://example.com",consumer_key="ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",consumer_secret="cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",version="wc/v3",timeout=30)Make request with aiohttp session:asyncdefmain():asyncwithAPISession(wcapi)assession:res=awaitsession.get('products/categories',params={'per_page':5})json=awaitres.json()print(json)loop=asyncio.get_event_loop()loop.run_until_complete(main())Options and request types:Fully compatible withwc-api-python |
aioweb | Webserver using the asyncio(pep3156) modules. |
aio.web | This package has been moved toaio.web.server(pypi) |
aioweb3 | No description available on PyPI. |
aiowebdav | aiowebdavPackage aiowebdav based onhttps://github.com/designerror/webdav-client-pythonbut usesaiohttpinstead ofrequests.
It provides easy way to work with WebDAV-servers.Installation$pipinstallaiowebdavSample Usageimportasynciofromaiowebdav.clientimportClientoptions={'webdav_hostname':"https://webdav.server.ru",'webdav_login':"login",'webdav_password':"password","disable_check":True}asyncdefmain():client=Client(options)client.verify=False# To not check SSL certificates (Default = True)client.execute_request("mkdir",'directory_name')asyncio.run(main())Webdav APIWebdav API is a set of webdav actions of work with cloud storage. This set includes the following actions:check,free,info,list,mkdir,clean,copy,move,download,upload,publishandunpublish.Configuring the clientRequired key is host name or IP address of the WevDAV-server with param namewebdav_hostname.For authentication in WebDAV server usewebdav_login,webdav_password.For an anonymous login do not specify auth properties.fromaiowebdav.clientimportClientoptions={'webdav_hostname':"https://webdav.server.ru",'webdav_login':"login",'webdav_password':"password"}client=Client(options)If your server does not supportHEADmethod or there are other reasons to override default WebDAV methods for actions use a dictionary optionwebdav_override_methods.
The key should be in the following list:check,free,info,list,mkdir,clean,copy,move,download,upload,publishandunpublish. The value should a string name of WebDAV method, for exampleGET.fromaiowebdav.clientimportClientoptions={'webdav_hostname':"https://webdav.server.ru",'webdav_login':"login",'webdav_password':"password",'webdav_override_methods':{'check':'GET'}}client=Client(options)For configuring a requests timeout you can use an optionwebdav_timeoutwith int value in seconds, by default the timeout is set to 30 seconds.fromaiowebdav.clientimportClientoptions={'webdav_hostname':"https://webdav.server.ru",'webdav_login':"login",'webdav_password':"password",'webdav_timeout':30}client=Client(options)When a proxy server you need to specify settings to connect through it.fromaiowebdav.clientimportClientoptions={'webdav_hostname':"https://webdav.server.ru",'webdav_login':"w_login",'webdav_password':"w_password",'webdav_proxy':"http://127.0.0.1:8080",'webdav_proxy_auth':"xxx",}client=Client(options)If you want to use the certificate path to certificate and private key is defined as follows:fromaiowebdav.clientimportClientoptions={'webdav_hostname':"https://webdav.server.ru",'webdav_login':"w_login",'webdav_password':"w_password",'webdav_ssl':'sslcontext'}client=Client(options)Or you want to limit the speed or turn on verbose mode:options={...'recv_speed':3000000,'send_speed':3000000,'verbose':True}client=Client(options)recv_speed: rate limit data download speed in Bytes per second. Defaults to unlimited speed.send_speed: rate limit data upload speed in Bytes per second. Defaults to unlimited speed.verbose: set verbose mode on/off. By default verbose mode is off.Also if your server does not supportcheckit is possible to disable it:options={...'disable_check':True}client=Client(options)By default, checking of remote resources is enabled.For configuring chunk size of content downloading usechunk_sizeparam, by default it is65536options={...'chunk_size':65536}client=Client(options)Asynchronous methods# Checking existence of the resourceawaitclient.check("dir1/file1")awaitclient.check("dir1")# Get information about the resourceawaitclient.info("dir1/file1")awaitclient.info("dir1/")# Check free spacefree_size=awaitclient.free()# Get a list of resourcesfiles1=awaitclient.list()files2=awaitclient.list("dir1")files3=awaitclient.list("dir1",get_info=True)# returns a list of dictionaries with files details# Create directoryawaitclient.mkdir("dir1/dir2")# Delete resourceawaitclient.clean("dir1/dir2")# Copy resourceawaitclient.copy(remote_path_from="dir1/file1",remote_path_to="dir2/file1")awaitclient.copy(remote_path_from="dir2",remote_path_to="dir3")# Move resourceawaitclient.move(remote_path_from="dir1/file1",remote_path_to="dir2/file1")awaitclient.move(remote_path_from="dir2",remote_path_to="dir3")# Download a resourceawaitclient.download(remote_path="dir1/file1",local_path="~/Downloads/file1")awaitclient.download(remote_path="dir1/dir2/",local_path="~/Downloads/dir2/")# Upload resourceawaitclient.upload(remote_path="dir1/file1",local_path="~/Documents/file1")awaitclient.upload(remote_path="dir1/dir2/",local_path="~/Documents/dir2/")# Publish the resourcelink=awaitclient.publish("dir1/file1")link=awaitclient.publish("dir2")# Unpublish resourceawaitclient.unpublish("dir1/file1")awaitclient.unpublish("dir2")# Exception handlingfromaiowebdav.exceptionsimportWebDavExceptiontry:...exceptWebDavExceptionasexception:...# Get the missing filesawaitclient.pull(remote_directory='dir1',local_directory='~/Documents/dir1')# Send missing filesawaitclient.push(remote_directory='dir1',local_directory='~/Documents/dir1')# Unload resourcekwargs={'remote_path':"dir1/file1",'local_path':"~/Downloads/file1",'callback':callback}client.upload_async(**kwargs)kwargs={'remote_path':"dir1/dir2/",'local_path':"~/Downloads/dir2/",'callback':callback}client.upload_async(**kwargs)Resource APIResource API using the concept of OOP that enables cloud-level resources.# Get a resourceres1=client.resource("dir1/file1")# Work with the resourceawaitres1.rename("file2")awaitres1.move("dir1/file2")awaitres1.copy("dir2/file1")info=awaitres1.info()awaitres1.read_from(buffer)awaitres1.read(local_path="~/Documents/file1")awaitres1.write_to(buffer)awaitres1.write(local_path="~/Downloads/file1")For ContributorsPrepare development environmentInstall docker on your development machineStart WebDAV server for testing by following commands from the project's root folder or change path toconfdir in second command to correct:dockerpullbytemark/webdav
dockerrun-d--namewebdav-eAUTH_TYPE=Basic-eUSERNAME=alice-ePASSWORD=secret1234-vconf:/usr/local/apache2/conf-p8585:80bytemark/webdavCode conventionPlease check your code according PEP8 Style guides.Run testsCheck that webdav container is started on your local machineExecute following command in the project's root folder:python-munittestdiscover-stestsPrepare a Pull RequestPlease use this check list before creating PR:You code should be formatted according PEP8All tests should successfully passYour changes shouldn't change previous default behaviour, exclude defectsAll changes are covered by tests |
aiowebhdfs | aiowebhdfsI know, nobody usesHadoopanymore, but for those who do, here is a library that handles large files withasyncfeatures for web requests using thehttpxlibrary andaiofilesfor streaming data fromHDFSFeaturesImplements retries and timeout windows withretry_asyncfromopnieuwlibraryImplements streaming through theaiofileslibraryImplments async requests through thehttpxlibraryFully tested for core subset of operations in WebHDFSv3.2.1CREATE = Write FilefromaiowebhdfsimportWebHdfsAsyncClientclient=WebHdfsAsyncClient(host='namenode.local',port=8443,user='spark',kerberos_token=token)awaitclient.create('c:\\temp\\bigfile.txt','/data/agg/bigfile.txt',overwrite=False)OPEN = Read FilefromaiowebhdfsimportWebHdfsAsyncClientclient=WebHdfsAsyncClient(host='namenode.local',port=8443,user='spark',kerberos_token=token)awaitclient.open('/data/agg/bigfile.txt')ContentofthefileGETFILESTATUS = File InfofromaiowebhdfsimportWebHdfsAsyncClientclient=WebHdfsAsyncClient(host='namenode.local',port=8443,user='spark',kerberos_token=token)awaitclient.get_file_status('/data/agg/bigfile.txt'){"FileStatus":{"accessTime":0,"blockSize":0,"group":"supergroup","length":0,//inbytes,zerofordirectories"modificationTime":1320173277227,"owner":"webuser","pathSuffix":"","permission":"777","replication":0,"type":"DIRECTORY"//enum{FILE,DIRECTORY}}}LISTSTATUS = List DirectoryfromaiowebhdfsimportWebHdfsAsyncClientclient=WebHdfsAsyncClient(host='namenode.local',port=8443,user='spark',kerberos_token=token)awaitclient.list_directory('/tmp'){"FileStatuses":{"FileStatus":[{"accessTime":1320171722771,"blockSize":33554432,"group":"supergroup","length":24930,"modificationTime":1320171722771,"owner":"webuser","pathSuffix":"a.patch","permission":"644","replication":1,"type":"FILE"},{"accessTime":0,"blockSize":0,"group":"supergroup","length":0,"modificationTime":1320895981256,"owner":"szetszwo","pathSuffix":"bar","permission":"711","replication":0,"type":"DIRECTORY"},...]}}GETCONTENTSUMMARY = Summary of DirectoryfromaiowebhdfsimportWebHdfsAsyncClientclient=WebHdfsAsyncClient(host='namenode.local',port=8443,user='spark',kerberos_token=token)awaitclient.list_directory('/tmp'){"FileStatuses":{"FileStatus":[{"accessTime":1320171722771,"blockSize":33554432,"group":"supergroup","length":24930,"modificationTime":1320171722771,"owner":"webuser","pathSuffix":"a.patch","permission":"644","replication":1,"type":"FILE"},{"accessTime":0,"blockSize":0,"group":"supergroup","length":0,"modificationTime":1320895981256,"owner":"szetszwo","pathSuffix":"bar","permission":"711","replication":0,"type":"DIRECTORY"},...]}} |
aiowebostv | aiowebostvPython library to control LG webOS based TV devices.Based on:aiopylgtvlibrary athttps://github.com/bendavid/aiopylgtvbscpylgtvlibrary athttps://github.com/chros73/bscpylgtvRequirementsPython >= 3.9InstallpipinstallaiowebostvInstall from SourceRun the following command inside this folderpipinstall--upgrade.ExamplesBasic Example:importasynciofromaiowebostvimportWebOsClientHOST="192.168.1.39"# For first time pairing set key to NoneCLIENT_KEY="140cce792ae045920e14da4daa414582"asyncdefmain():"""Basic webOS client example."""client=WebOsClient(HOST,CLIENT_KEY)awaitclient.connect()# Store this key for future useprint(f"Client key:{client.client_key}")apps=awaitclient.get_apps_all()forappinapps:print(app)awaitclient.disconnect()if__name__=="__main__":asyncio.run(main())Subscribed State Updates Example:importasynciofromaiowebostvimportWebOsClientHOST="192.168.1.39"# For first time pairing set key to NoneCLIENT_KEY="140cce792ae045920e14da4daa414582"asyncdefon_state_change(client):"""State changed callback."""print("State changed:")print(f"System info:{client.system_info}")print(f"Software info:{client.software_info}")print(f"Hello info:{client.hello_info}")print(f"Channel info:{client.channel_info}")print(f"Apps:{client.apps}")print(f"Inputs:{client.inputs}")print(f"Powered on:{client.power_state}")print(f"App Id:{client.current_app_id}")print(f"Channels:{client.channels}")print(f"Current channel:{client.current_channel}")print(f"Muted:{client.muted}")print(f"Volume:{client.volume}")print(f"Sound output:{client.sound_output}")asyncdefmain():"""Subscribed State Updates Example."""client=WebOsClient(HOST,CLIENT_KEY)awaitclient.register_state_update_callback(on_state_change)awaitclient.connect()# Store this key for future useprint(f"Client key:{client.client_key}")# Change something using the remote during sleep period to get updatesawaitasyncio.sleep(30)awaitclient.disconnect()if__name__=="__main__":asyncio.run(main())Examples can be found in theexamplesfolder |
aio.web.page | Web page templates for theaioasyncio frameworkBuild statusInstallationRequires python >= 3.4Install with:pipinstallaio.web.pageQuick start - hello world web pageSave the following into a file “hello.conf”[aio]modules=aio.web.server[server/my_server]factory=aio.web.server.factoryport=8080[web/my_server]template_dirs=templates[web/my_server/my_route]match=/route=my_example.route_handlerAnd save the following into a file named “my_example.py”[email protected]('example_page.html')deftemplate_handler(request):return{"message":"Hello template world"}@aio.web.server.routedefroute_handler(request,config):return(yield fromtemplate_handler(request))And the following into a file named “templates/example_page.html”<html><body>{{ message }}</body></html>Run with the aio run commandaiorun-chello.confaio.web.page usageaio.web.page provides templates and fragments for building web pagesLets set up a test to run a server and request a web page>>> from aio.app.runner import runner
>>> import aio.testing
>>> import aiohttp>>> @aio.testing.run_forever(sleep=1)
... def run_web_server(config, request_page="http://localhost:7070"):
... yield from runner(['run'], config_string=config)
...
... def call_web_server():
... result = yield from (
... yield from aiohttp.request(
... "GET", request_page)).read()
... aio.web.server.clear()
...
... print(result.decode())
...
... return call_web_serverTemplatesAn @aio.web.server.route handler can defer to other templates, for example according to the matched path.>>> example_config = """
... [aio]
... log_level = CRITICAL
... modules = aio.web.server
... aio.web.server.tests
...
... [server/server_name]
... factory: aio.web.server.factory
... port: 7070
...
... [web/server_name/route_name]
... match = /{path:.*}
... route = aio.web.page.tests._example_route_handler
... """Lets create a couple of template handlers>>> import aio.web.page>>> @aio.web.page.template("test_template.html")
... def template_handler_1(request):
... return {
... 'message': "Hello, world from template handler 1"}Template handlers can return a response object, in which case the template is not rendered>>> @aio.web.page.template("test_template.html")
... def template_handler_2(request):
... return aiohttp.web.Response(
... body=b"Hello, world from template handler 2")And lets set up a route handler which will defer to a template accordingly>>> import aio.web.server>>> @aio.web.server.route
... def route_handler(request, config):
... path = request.match_info['path']
...
... if path == "path1":
... return (yield from template_handler_1(request))
...
... elif path == "path2":
... return (yield from template_handler_2(request))
...
... raise aiohttp.web.HTTPNotFoundAnd make it importable>>> import aio.web.page.tests
>>> aio.web.page.tests._example_route_handler = route_handlerCalling the server at /path1 we get the templated handler>>> run_web_server(
... example_config,
... request_page="http://localhost:7070/path1")
<html>
<body>
Hello, world from template handler 1
</body>
</html>And calling on /path2 we get the response without the template>>> run_web_server(
... example_config,
... request_page="http://localhost:7070/path2")
Hello, world from template handler 2Templates must always specify a template, even if they dont use it>>> try:
... @aio.web.page.template
... def template_handler(request, test_list):
... return {'test_list': test_list}
... except Exception as e:
... print(repr(e))
TypeError('Template decorator must specify template: <function template_handler ...>',)Templates can take arbitrary arguments>>> @aio.web.page.template("test_template.html")
... def template_handler(request, foo, bar):
... return {
... 'message': "Hello, world with %s and %s" % (foo, bar)}>>> @aio.web.server.route
... def route_handler(request, config):
... return (yield from(template_handler(request, "spam", "tuesday")))
>>> aio.web.page.tests._example_route_handler = route_handler>>> run_web_server(example_config)
<html>
<body>
Hello, world with spam and tuesday
</body>
</html>The first argument to a template should always be a request object>>> @aio.web.page.template("test_template.html")
... def template_handler(foo, bar):
... return {
... 'message': "Hello, world with %s and %s" % (foo, bar)}>>> @aio.web.server.route
... def route_handler(request, config):
... try:
... return (yield from(template_handler("spam", "tuesday")))
... except TypeError as e:
... return aiohttp.web.Response(body=repr(e).encode())
>>> aio.web.page.tests._example_route_handler = route_handler>>> run_web_server(example_config)
TypeError("Template handler (<function template_handler at ...>) should be called with a request object, got: <class 'str'> spam",)FragmentsFragments render a snippet of html for embedding in other templates.Fragments can specify a template and return a context object to render it withA fragment can take an arbitrary number of arguments>>> @aio.web.page.fragment("fragments/test_fragment.html")
... def fragment_handler(request, foo, bar):
... return {"test_list": [foo, bar]}>>> @aio.web.page.template("test_template.html")
... def template_handler(request):
... return {'message': (yield from fragment_handler(request, "eggs", "thursday"))}>>> @aio.web.server.route
... def route_handler(request, config):
... return (yield from(template_handler(request)))
>>> aio.web.page.tests._example_route_handler = route_handler>>> run_web_server(example_config)
<html>
<body>
<ul>
<li>eggs</li><li>thursday</li>
</ul>
</body>
</html>The first argument to a fragment should always be an aiohttp.web.Request object>>> @aio.web.page.fragment("fragments/test_fragment.html")
... def fragment_handler(foo, bar):
... return {"test_list": [foo, bar]}>>> @aio.web.page.template("test_template.html")
... def template_handler(request):
... try:
... message = (yield from(fragment_handler("eggs", "thursday")))
... except Exception as e:
... message = repr(e)
... return {'message': message}>>> @aio.web.server.route
... def route_handler(request, config):
... return (yield from(template_handler(request)))
>>> aio.web.page.tests._example_route_handler = route_handler>>> run_web_server(example_config)
<html>
<body>
TypeError("Fragment handler (<function fragment_handler ...>) should be called with a request object, got: <class 'str'> eggs",)
</body>
</html>Fragments do not need to specify a template>>> @aio.web.page.fragment
... def fragment_handler(request):
... return "Hello from fragment">>> @aio.web.page.template("test_template.html")
... def template_handler(request):
... return {'message': (yield from fragment_handler(request))}>>> @aio.web.server.route
... def route_handler(request, config):
... return (yield from(template_handler(request)))
>>> aio.web.page.tests._example_route_handler = route_handler>>> run_web_server(example_config)
<html>
<body>
Hello from fragment
</body>
</html>If a fragment doesnt specify a template, it must return a string>>> @aio.web.page.fragment
... def fragment_handler(request):
... return {"foo": "bar"}>>> @aio.web.page.template("test_template.html")
... def template_handler(request):
... try:
... fragment = yield from fragment_handler(request)
... except Exception as e:
... fragment = repr(e)
... return {'message': fragment}>>> @aio.web.server.route
... def route_handler(request, config):
... return (yield from(template_handler(request)))
>>> aio.web.page.tests._example_route_handler = route_handler>>> run_web_server(example_config)
<html>
<body>
TypeError('Fragment handler (<function fragment_handler at ...>) should specify a template or return a string',)
</body>
</html>Fragments should only return strings or context dictionaries, and should not return an aiohttp.web.Response object.>>> @aio.web.page.fragment("fragments/test_fragment.html")
... def fragment_handler(request):
... return aiohttp.web.Response(body=b"Fragments should not return Response objects")>>> @aio.web.page.template("test_template.html")
... def template_handler(request):
... try:
... fragment = yield from fragment_handler(request)
... except Exception as e:
... fragment = repr(e)
... return {'message': fragment}>>> @aio.web.server.route
... def route_handler(request, config):
... return (yield from(template_handler(request)))
>>> aio.web.page.tests._example_route_handler = route_handler>>> run_web_server(example_config)
<html>
<body>
TypeError("Fragment handler (<function fragment_handler ...>) should return a string or context dictionary, got: <class 'aiohttp.web_reqrep.Response'> <Response OK not started>",)
</body>
</html> |
aiowebrtc | WebRTC (Real-Time Communication) uses a variety of peer to peer protocols
for audio, video, and data streaming. |
aio.web.server | Web server for theaioasyncio frameworkBuild statusInstallationRequires python >= 3.4Install with:pipinstallaio.web.serverQuick start - Hello world web serverCreate a web server that says helloSave the following into a file “hello.conf”[aio]modules=aio.web.server[server/my_server]factory=aio.web.server.factoryport=8080[web/my_server/my_route]match=/route=my_example.handlerAnd save the following into a file named my_example.pyimportaiohttpimportaio.web.server@aio.web.server.routedefhandler(request,config):returnaiohttp.web.Response(body=b"Hello, web world")Run with the aio run commandaiorun-chello.confWeb server configurationWeb server definitions are in the following format, where SERVER_NAME corresponds to the server/SERVER_NAME[web/SERVER_NAME]So for example you might have the following[server/my_server]factory=aio.web.server.factoryport=8080[web/my_server]modules=${aio:modules}some.web.moduleRoute configurationRoute definitions are in defined in sections with the following format[web/SERVER_NAME/ROUTE_NAME]So an example server configuation with a route defined for the path / might be[aio]modules=aio.web.server[server/my_server]factory=aio.web.server.factoryport=8080[web/my_server/my_route]match=/route=my.route.handleraio.web.server usageConfigurationTo set up the web server, we need to:add “aio.web.server” to aio:modules initialize the web serveradd a “server/SERVERNAME” section to create the http serveradd a “web/SERVERNAME/ROUTENAME” to create a routeLets create a basic web server configuration>>> web_server_config = """
... [aio]
... log_level = ERROR
... modules = aio.web.server
...
... [server/server_name]
... factory = aio.web.server.factory
... port = 7070
...
... [web/server_name/route_name]
... match = /
... route = aio.web.server.tests._example_handler
... """Now lets create a route and make it importable>>> import aiohttp
>>> import aio.web.server>>> @aio.web.server.route
... def route_handler(route):
... return aiohttp.web.Response(body=b"Hello, web world")>>> import aio.web.server.tests
>>> aio.web.server.tests._example_handler = route_handlerLets set up a test to run the server and request a web page>>> from aio.app.runner import runner
>>> import aio.testing>>> @aio.testing.run_forever(sleep=1)
... def run_web_server(config, request_page="http://localhost:7070"):
... runner(['run'], config_string=config)
...
... def call_web_server():
... result = yield from (
... yield from aiohttp.request(
... "GET", request_page)).read()
...
... print(result.decode())
...
... return call_web_serverAnd run the test>>> run_web_server(web_server_config)
Hello, web worldWe can access the aiohttp web app by name>>> import aio.web.server
>>> web_app = aio.web.server.apps['server_name']
>>> web_app
<Application>>>> web_app['name']
'server_name'And we can access the jinja environment for the web app>>> import aiohttp_jinja2
>>> jinja_env = aiohttp_jinja2.get_env(web_app)
>>> jinja_env
<jinja2.environment.Environment object ...>We dont have any templates registered yet>>> jinja_env.list_templates()
[]Let’s clear the web apps, this will also call aio.app.clear()>>> aio.web.server.clear()
>>> aio.web.server.apps
{}>>> print(aio.app.config, aio.app.signals)
None NoneWeb app modulesBy default template resources are registered for any modules listed in aio:modules>>> config = """
... [aio]
... modules = aio.web.server
... aio.web.server.tests
...
... [server/server_name]
... factory = aio.web.server.factory
... port = 7070
... """Lets create a test to run the server and print the list of installed jinja templates>>> @aio.testing.run_forever(sleep=1)
... def run_server_print_templates(config_string):
... runner(['run'], config_string=config_string)
...
... def print_templates():
... web_app = aio.web.server.apps['server_name']
... print(
... [x for x in
... aiohttp_jinja2.get_env(
... web_app).list_templates(extensions=["html"])])
... aio.web.server.clear()
...
... return print_templatesThe aio.web.server.tests module has 2 html templates>>> run_server_print_templates(config)
['fragments/test_fragment.html', 'test_template.html']We can set the modules for all web apps in the aio/web:modules optionThis will override the setting in aio:modules>>> config = """
... [aio]
... modules = aio.web.server
... aio.web.server.tests
...
... [aio/web]
... modules = aio.web.server
...
... [server/server_name]
... factory = aio.web.server.factory
... port = 7070
... """>>> run_server_print_templates(config)
[]Or you can set the modules in the web/SERVER_NAME:modules option.This will override the setting in both aio/web:modules and aio:modules>>> config = """
... [aio]
... modules = aio.web.server
... aio.web.server.tests
...
... [aio/web]
... modules = aio.web.server
...
... [web/server_name]
... modules = aio.web.server.tests
...
... [server/server_name]
... factory = aio.web.server.factory
... port = 7070
... """>>> run_server_print_templates(config)
['fragments/test_fragment.html', 'test_template.html']Routes>>> config_template = """
... [aio]
... modules = aio.web.server
... aio.web.server.tests
... log_level: ERROR
...
... [server/server_name]
... factory: aio.web.server.factory
... port: 7070
...
... [web/server_name/route_name]
... match = /
... route = aio.web.server.tests._example_route_handler
... """Route functions must be decorated with aio.server.route, and receive a aio.server.Route objectThe route object has a request property and a config property containing the routes configuration>>> @aio.web.server.route("test_template.html")
... def route_handler(route):
... return {
... 'message': 'Hello, world at %s from match(%s) handled by: %s' % (
... route.request.path, route.config['match'], route.config['route'])}>>> aio.web.server.tests._example_route_handler = route_handler>>> run_web_server(config_template)
<html>
<body>
Hello, world at / from match(/) handled by: aio.web.server.tests._example_route_handler
</body>
</html>>>> aio.web.server.clear()Static directoryThe web/SERVER_NAMEsection takes a static_url and a static_dir option for hosting static files>>> config_static = """
... [aio]
... log_level: ERROR
... modules = aio.web.server
...
... [server/test]
... factory: aio.web.server.factory
... port: 7070
...
... [web/test]
... static_url: /static
... static_dir: %s
... """>>> import os
>>> import tempfileLets create a temporary directory and add a css file to it>>> with tempfile.TemporaryDirectory() as tmp:
... with open(os.path.join(tmp, "test.css"), 'w') as cssfile:
... result = cssfile.write("body {background: black}")
...
... run_web_server(
... config_static % tmp,
... request_page="http://localhost:7070/static/test.css")
body {background: black}>>> aio.web.server.clear()Template filtersYou can configure jinja filters by adding them to the aio/web:filters option>>> config = """
... [aio]
... log_level: ERROR
... modules = aio.web.server
...
... [server/server_name]
... factory: aio.web.server.factory
... port: 7070
...
... [aio/web]
... filters = example_filter aio.web.server.tests._example_filter
... """The filter isnotcalled in a coroutine>>> def filter(value, *la):
... return value>>> aio.web.server.tests._example_filter = filter>>> @aio.testing.run_forever(sleep=1)
... def run_server_check_filter(config_string):
... runner(['run'], config_string=config_string)
...
... def check_filter():
... web_app = aio.web.server.apps['server_name']
... env = aiohttp_jinja2.get_env(web_app)
...
... if "example_filter" in env.filters.keys():
... print("example_filter is in the jinja environment!")
...
... return check_filter>>> run_server_check_filter(config)
example_filter is in the jinja environment!>>> aio.web.server.clear()You can also add filters to the the web/server_name section, this will override the setting in aio/web>>> config = """
... [aio]
... log_level: ERROR
... modules = aio.web.server
...
... [server/server_name]
... factory: aio.web.server.factory
... port: 7070
...
... [aio/web]
... filters = example_filter aio.web.server.tests._example_filter
...
... [web/server_name]
... filters = example_filter_2 aio.web.server.tests._example_filter
... """>>> @aio.testing.run_forever(sleep=1)
... def run_server_check_filter(config_string):
... runner(['run'], config_string=config_string)
...
... def check_filter():
... web_app = aio.web.server.apps['server_name']
... env = aiohttp_jinja2.get_env(web_app)
...
... if "example_filter" not in env.filters.keys():
... print("example_filter is not in the jinja environment!")
...
... if "example_filter_2" in env.filters.keys():
... print("example_filter_2 is in the jinja environment!")
...
... return check_filter>>> run_server_check_filter(config)
example_filter is not in the jinja environment!
example_filter_2 is in the jinja environment!>>> aio.web.server.clear() |
aiowebsocket | Seehttps://github.com/asyncins/aiowebsocket |
aiowebsocketclient | alphaOfficial Documentation |
aiowebthing | aiowebthingWhat isaiowebthing?aiowebthingis a library for the Web of Things protocol in Python Asyncio. This library is derived of webthing-python project (supporting Tornado) but adapted for Starlette (based on Uvicorn for better performance).additional featuresadditional_routes -- list of additional routes add to the serveradditional_middlewares -- list of additional middlewares add to the serveradditional_on_startup -- list of additional starup event handlers add to the serveradditional_on_shutdown -- list of additional shutdown event handlers add to the serverthing.sync_property -- Sync a property value from cloud or mqtt broker etc, property set value with no action disclaim.thing.property_action -- addional action sync the property change to device.property.set_value(value, with_action=True) -- if with_action is True, Value instance should emitupdate, elsesyncAdd the property change observer to notify the Thing about a property change or do some additional action:self.value.on("update",lambda_:self.thing.property_notify(self))self.value.on("sync",lambda_:self.thing.property_notify(self))self.value.on("update",lambda_:self.thing.property_action(self))Installationaiowebthing can be installed via pip, as such:$ pip install aiowebthingRunning the Sample$ wget https://raw.githubusercontent.com/hidaris/aiowebthing/master/example/test.py$ uvicorn test:app --reloadThis starts a server and lets you search for it from your gateway through mDNS. To add it to your gateway, navigate to the Things page in the gateway's UI and click the + icon at the bottom right. If both are on the same network, the example thing will automatically appear.Example ImplementationIn this code-walkthrough we will set up a dimmable light and a humidity sensor (both using fake data, of course). Both working examples can be found in here.Dimmable Light
Imagine you have a dimmable light that you want to expose via the web of things API. The light can be turned on/off and the brightness can be set from 0% to 100%. Besides the name, description, and type, a Light is required to expose two properties:on: the state of the light, whether it is turned on or off
Setting this property via a PUT {"on": true/false} call to the REST API toggles
the light.brightness: the brightness level of the light from 0-100%
Setting this property via a PUT call to the REST API sets the brightness level of this light.
First we create a new Thing:fromwebthingimportThing,Property,ValueclassLight(Thing):type=['OnOffSwitch','Light'],description='A web connected lamp'super().__init__('urn:dev:ops:my-lamp-1234','My Lamp',)Now we can add the required properties.The on property reports and sets the on/off state of the light. For this, we need to have a Value object which holds the actual state and also a method to turn the light on/off. For our purposes, we just want to log the new state if the light is switched on/off.asyncdefbuild(self):on=Property('on',Value(True,lambdav:print('On-State is now',v)),metadata={'@type':'OnOffProperty','title':'On/Off','type':'boolean','description':'Whether the lamp is turned on',})awaitself.add_property(on)The brightness property reports the brightness level of the light and sets the level. Like before, instead of actually setting the level of a light, we just log the level.brightness=Property('brightness',Value(50,lambdav:print('Brightness is now',v)),metadata={'@type':'BrightnessProperty','title':'Brightness','type':'number','description':'The level of light from 0-100','minimum':0,'maximum':100,'unit':'percent',})awaitself.add_property(brightness)Now we can add our newly created thing to the server and start it:# If adding more than one thing, use MultipleThings() with a name.# In the single thing case, the thing's name will be broadcast.withbackground_thread_loop()asloop:app=WebThingServer(loop,Light).create()This will start the server, making the light available via the WoT REST API and announcing it as a discoverable resource on your local network via mDNS.Sensor
Let's now also connect a humidity sensor to the server we set up for our light.A MultiLevelSensor (a sensor that returns a level instead of just on/off) has one required property (besides the name, type, and optional description): level. We want to monitor this property and get notified if the value changes.First we create a new Thing:fromwebthingimportThing,Property,ValueclassLight(Thing):type=['MultiLevelSensor'],description='A web connected humidity sensor'super().__init__('urn:dev:ops:my-humidity-sensor-1234','My Humidity Sensor',)Then we create and add the appropriate property:level: tells us what the sensor is actually readingContrary to the light, the value cannot be set via an API call, as it wouldn't make much sense, to SET what a sensor is reading. Therefore, we are creating a readOnly property.asyncdefbuild(self):awaitself.add_property(Property('level',Value(0.0),metadata={'@type':'LevelProperty','title':'Humidity','type':'number','description':'The current humidity in %','minimum':0,'maximum':100,'unit':'percent','readOnly':True,}))returnselfNow we have a sensor that constantly reports 0%. To make it usable, we need a thread or some kind of input when the sensor has a new reading available. For this purpose we start a thread that queries the physical sensor every few seconds. For our purposes, it just calls a fake method.self.sensor_update_task=\get_event_loop().create_task(self.update_level())asyncdefupdate_level(self):try:whileTrue:awaitsleep(3)new_level=self.read_from_gpio()logging.debug('setting new humidity level:%s',new_level)awaitself.level.notify_of_external_update(new_level)exceptCancelledError:passThis will update our Value object with the sensor readings via the self.level.notify_of_external_update(read_from_gpio()) call. The Value object now notifies the property and the thing that the value has changed, which in turn notifies all websocket listeners. |
aiowechatpayv3 | 微信支付 API v3 Python SDK介绍异步版本微信支付包,fork自wechatpayv3微信支付接口 V3 版 python 库。文档完善中,暂时参考微信支付 API v3 文档。 |
aioweenect | aioweenectAsynchronous Python client for the weenect APIInstallation$pipinstallaioweenectUsagefromaioweenectimportAioWeenectimportasyncioUSER="<YOUR_USER>"PASSWORD="<YOUR_PASSWORD>"asyncdefmain():"""Show example how to get location of your tracker."""asyncwithAioWeenect(username=USER,password=PASSWORD)asaioweenect:trackers_response=awaitaioweenect.get_trackers()tracker_id=trackers_response["items"][0]["id"]tracker_name=trackers_response["items"][0]["name"]position_response=awaitaioweenect.get_position(tracker_id=tracker_id)lat=position_response[0]["latitude"]lon=position_response[0]["longitude"]last_message=position_response[0]["last_message"]print(f"Location for{tracker_name}: lat:{lat}, lon:{lon}. Last message received:{last_message}")if__name__=="__main__":loop=asyncio.get_event_loop()loop.run_until_complete(main()) |
aioweixin | No description available on PyPI. |
aiowerkzeug | aiowerkzeugLibrary to make werkzeug working with asyncio.ChangelogVersion 0.2.0Use Python 3.5 async syntax.New~keep_context_factory. It works like~context_coroutine,
but simple code.Async version of Local, LocalStack and LocalManager. They implement__release_local__method.FeaturesAsync versions of Local, LocalStack and LocalManager.Locals work on asyncio Tasks.werkzeug.local.Localorwerkzeug.local.LocalStackmust be patched
withaiowerkzeug.local.patch_localPatchedwerkzeug.local.Localorwerkzeug.local.LocalStackuse currentasyncio.tasks.Taskto determine context.Decorator factory to mark coroutines to run in a context. Useful for Flask. It allows to run corountines
in newasyncio.tasks.Taskinside a specific context.For example, in Flask to run coroutines in Application context it is possible to create a decorator like that:def_get_app_context():returncurrent_app.app_context()app_coroutine=partial(context_coroutine,ctx=_get_app_context)@app_coroutinedeffoo_bar():print(current_app.debug)@flask_app.route('/')defcaller():asyncio.ensure_future(foo_bar())Asyncio HTTP server runner with reload$pythonaiowerkzeug/serving.py--reloadapp_test.appTODOForm parserDebug middlewareStatic files middleware |
aiowerobot | 一个简单的异步公众号框架介绍代码fork自WeRoBot,修改成基于sanic的异步框架文档点我Installationpip install aiowerobotSimple usesfromaiowerobotimportAioWeRoBotrobot=AioWeRoBot(app_id='',app_secret='',token='')@robot.handlerasyncdefhello(message):return'Hello World!'config={'host':'0.0.0.0','port':8099}robot.run(**config) |
aiowhatsapp | aiowhatsappA whatsapp client library for python utilizing theWhatsApp Business Cloud API.Installation$pipinstallaiowhatsappUsageTODOContributingInterested in contributing? Check out the contributing guidelines. Please note that this project is released with a Code of Conduct. By contributing to this project, you agree to abide by its terms.Licenseaiowhatsappwas created by Solomon Olatunji. It is licensed under the terms of the MIT license. |
aiowhois | aiowhoisAsyncio-based WHOIS supportinglegacyandRDAPprotocols.>>>importaiowhois>>>resolv=aiowhois.Whois(timeout=10)>>>parsed_whois=awaitresolv.query(my_domain)Why aiowhois?TODO |
aiowialon | aiowialonWialon Remote API async clientInstallpip install aiowialonConnection and Loginfromaiowialonimportconnecttoken="WIALON_REMOTE_API_ACCESS_TOKEN"asyncwithconnect(token)assession:print(session.username)Environment Variables |
aio-wiki | aio_wikiAsyncio client for interacting with wikimedia APIsInstallation instructions:pipinstallaio_wikiUsage:fromaio_wikiimportGraphClientclient=GraphClient()Noteaio_wiki is not affiliated or endorsed by any of the web services it interacts with. |
aio_windows_patch | version: 0.0.1status: devauthor: hszemail:[email protected] python version so far has poorly supported windows. One of the most troubling things isloop.add_signal_handlercan not deal with the signal on windows.This project is asyncio’s patch which can deal with problem ,It’s fromhttps://codereview.appspot.com/119990043/.One day python will fix this problem. Then I will delete this program.keywords:asyncio,patchFeatureloop.add_signal_handler can deal with the signal on windowsExampleimportaio_windows_patchasasyncio....Installpython-mpip install aio_windows_patch |
aiowinreg | No description available on PyPI. |
aiowinrm | UNKNOWN |
aiowintest | Win-Test (http://win-test.com) is a tool used for Ham Radio Contesting.This is a partial implementation of the protocol used by Win-Test to
synchronize QSOs, gab (chat) messages, contest score, and other information
over a local IP network.The authors of this package are not affiliated in any way with the Win-Test
developers.InstallationInstall using pip:pipinstallaiowintestDocumentationPlease seehttps://aiowintest.readthedocs.io/AuthorsHans Insulander, SM0UTY, <[email protected]> |
aiowire | aiowire - A simple event loop using asyncioThis package implements aEventLoopclass
that manages concurrent coroutines.It is based on the principles of functional
reactive programming and draws inspiration
from Haskell’sControl.Wirelibrary.In particular, every co-routine started by the event loop is aWire.Wire-s either returnNone, indicating they’re done, or anotherWire.An example helps explain the idea:from aiowire import EventLoop
event = 0
async def show_event(ev) -> Optional[Wire]:
print("Running...")
event += 1
await asyncio.sleep(event*0.15)
print(f"Event {event}")
if event < 5:
return Wire(show_event)
return None
async with EventLoop(timeout=1) as event:
event.start(show_event)
event.start(show_event)We start up an event loop and drop in two wires.
Each runs, then returns theshow_eventfunction.
The event loop runs those functions next… and so on.But since this isn’t functional programming. The wires
have access to the event loop, and can start more
tasks. Easy, right?What can I do with it?What if you have a server that’s spawning programs,
working with sockets, and managing timeouts? Drop
in one wire for each program, one polling on socket I/O,
and another acting as a timer (as above).Some canonical task types that do these include:asyncio.create_subprocess_exec # run a program
asyncio.sleep # awake the loop after a given time lapse
zmq.asyncio.Poller.poll # awake the loop after I/O on socket/file
aiowire.Poller # Wire-y interface to zmq.asyncio.PollerThink about each wire as a finite state machine.
For example,flowchart LR
R[Ready] --> N{New Task?};
N -- Yes --> W[Working];
W --> C{Complete?};
C -- Yes --> R;can be implemented like so:async def ready(ev : EventLoop, info : X) -> Optional[Wire]:
if info.new_task():
do_working_action()
return Wire(working, info) # move to working state
# Return a sequence of 2 wires:
return Call(asyncio.sleep, 1.0) >> Wire(ready, info)
async def working(ev : EventLoop, info : X) -> Wire:
if info.complete():
do_complete_action()
return Wire(ready, info)
await asyncio.sleep(0.5) # directly sleep a bit
return Wire(working, info)Note how your sockets can launch programs, and your program
results can start/stop sockets, and everyone can start
background tasks.Poller?ThePollerclass lets you schedule callbacks in response
to socket or file-descriptor activity. Of course, the callbacks
are wires, and run concurrently.Poller is also a Wire, created as,Poller(dictionary mapping sockets / fd-s to callback wires).You add it to your event loop as usual:# ... create sock from zmq.asyncio.Context
async def echo(ev):
await sock.send( await sock.recv() )
todo = { 0: Call(print, "received input on sys.stdin"),
sock: Wire(echo)
}
async with EventLoop() as ev:
ev.start( Poller(todo) )Tell me moreYes, youcouldjust send async functions taking one
argument toEventLoop.start, but where’s the fun in
writing closures everywhere?To take it to the next level, aiowire comes with aWireconvenience class that lets you writeWire-s expressively.
The following class extensions help you make Wire-s out of common
programming idioms:Wire(w): acts like an identity over “async func(ev):” functionsRepeat(w, n): repeat wirewn times in a rowForever(w): repeat forever – likeRepeat(w) * infinityCall(fn, *args, **kargs): call fn (normal or async),
ignore the return, and exitConsider, for example, printing 4 alarms separated by some time interval:from aiowire import EventLoop, Call
prog = ( Call(asyncio.sleep, 0.1) >> Call(print, 'beep\a') ) * 4
async with EventLoop() as ev:
ev.start(prog)Referenceshttps://pyzmq.readthedocs.io/en/latest/api/zmq.html#pollerhttps://pythontic.com/modules/select/pollhttps://blog.tomecek.net/post/non-blocking-stdin-in-python/ |
aiowirecard | aiowirecardAsyncio wirecard API wrapper based onmoipproviding asyncronous requests.Usage$exportWIRECARD_KEY=<your_wirecard_key>
$exportWIRECARD_TOKEN=<your_wirecard_token>importasyncioimportjsonimportosimportrandomimportaiowirecardasyncdefmain():wirecard=aiowirecard.Wirecard(environment='sandbox',key=os.environ['WIRECARD_KEY'],token=os.environ['WIRECARD_TOKEN'])print('Creating customer...')customer={"ownId":"%0.11d"%random.randint(0,99999999999),"fullname":"Maria Oliveira","email":"[email protected]","birthDate":"1980-5-10","taxDocument":{"type":"CPF","number":"%0.11d"%random.randint(0,99999999999)},"phone":{"countryCode":"55","areaCode":"11","number":"22226842"},"shippingAddress":{"city":"Rio de Janeiro","district":"Ipanema","street":"Avenida Atlântica","streetNumber":"60","zipCode":"02446000","state":"RJ","country":"BRA"},"fundingInstrument":{"method":"CREDIT_CARD","creditCard":{"expirationMonth":"06","expirationYear":"22","number":"6362970000457013","cvc":"123","holder":{"fullname":"Maria Oliveira","birthdate":"1980-05-10","taxDocument":{"type":"CPF","number":"10013390023"},"billingAddress":{"city":"Rio de Janeiro","district":"Copacabana","street":"Rua Raimundo Corrêa","streetNumber":"1200","zipCode":"05246200","state":"RJ","country":"BRA"},"phone":{"countryCode":"55","areaCode":"11","number":"22226842"}}}}}print('Customer data: ',customer)create_user=awaitwirecard.post_customer(parameters=customer)user_id=json.loads(create_user)['id']print('Customer id: ',user_id)get_user=awaitwirecard.get_customer(user_id)print('Customer info:',get_user)order={"ownId":"%0.11d"%random.randint(0,99999999999),"amount":{"currency":"BRL","subtotals":{"shipping":1500}},"items":[{"product":"Descrição do pedido","category":"CLOTHING","quantity":1,"detail":"Camiseta estampada branca","price":9500}],"customer":{"id":user_id}}new_order=awaitwirecard.post_order(order)print('Creating an order... ')order_id=json.loads(new_order)['id']print('Order id: ',order_id)order=awaitwirecard.get_order(order_id)print('Getting order info: ',order)loop=asyncio.get_event_loop()loop.run_until_complete(main())Functionspost_customer(parameters)# 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 |
aiowiserbyfeller | Wiser by Feller API Async Python LibraryUse your Wiser by Feller smart light switches, cover controls and scene buttons in your python project.Beware:This integration implementsWiser by Fellerand notWiser by Schneider Electric, which is a competing Smart Home platform (and is not compatible). It es even more confusing, as Feller (the company) is a local subsidiary of Schneider Electric, catering only to the Swiss market.FunctionalityDevicesWiser by Feller devices always consist of two parts: The control front and the base module. There are switching base modules (for light switches and cover controllers) and non-switching base modules (for scene buttons and secondary controls).Because the functionality changes when the same base module is used with a different front, the combination of the two is considered an unique device.Devices are connected with each other by a proprietaryK+ bus system. One (and only one) device acts as a WLAN gateway (called µGateway) to interface with the system.Status LEDsEach front features a configurable RGB LED edge for their buttons. Normally you would configure those in theWiser Home app. They can be configured in color and brightness. For buttons controlling a load, there can be two different brightnesses: One for if the load is on and one for if it is off. For others (e.g. scene buttons) there can only be one brightness, as there is no logical "on" state.Note:Due to the implementation on the devices, the status light is not suited for fast updating, as multiple slow API calls are necessary.Known issuesAs of right now, the µGateway API only supports Rest and Websockets. MQTT is implemented,but only for the proprietary app.Note: device names are in German because manufacturer does not have an English online presence. |
aioWiserHeatAPI | Drayton Wiser Hub API Async v1.5.6This repository contains a simple API which queries the Drayton Wiser Heating sysystem used in the UK.The API functionality provides the following functionality to control the wiser heating system for 1,2 and 3 channel heat hubs
The API also supports Smart Plugs and initial basic functionality for Shutter and LightsRequirementsRequires a minimum of Python v3.10Installation1. Find your HeatHub Secret keyReferencehttps://it.knightnet.org.uk/kb/nr-qa/drayton-wiser-heating-control/#controlling-the-systemPress the setup button on your HeatHub, the light will start flashing
Look for the Wi-Fi network (SSID) called‘WiserHeatXXXXXX’where XXXXXX is last 6 digits of the MAC addressConnect to the network from a Windows/Linux/Mac/Android/iPhone machineExecute the secret url :-)Open a browser to urlhttp://192.168.8.1/secretThis will return a string which is your system secret, store this somewhere. If you are running the test script simply put this value , with the ip address of the hub, in your wiserkeys.paramsPress the setup button on the HeatHub again and it will go back to normal operationsCopy the secret and save it somewhere.3. Find Your HEATHUB IPUsing your router, or something else, identify the IP address of your HeatHub, it usually identifies itself as the same ID as theWiserHeatXXXXXXAlternatively see the test_api_discovery.py file for how to use the api to discover your hub4. Add values in you params.py to run testsCreate a file called params.py and place two lines, one with the wiser IP or hostname and the other with the secret key.
e.g.HOST="192.168.0.22"
KEY="ABCDCDCDCCCDCDC"5. Run the sampleTo help understand the api simply look at the test sample codetests/test_api_properties.py,tests/test_api_methods.pyortests/test_api_discovery.pyand the fully commented code.6. DocumentationDocumentation available ininfo.mdin the docs directory and within comments in the codeChangelogv1.5.6Added improved error handling for json decode errorsv1.5.5Added addtional v2 hub attributes and switchesv1.5.4Fixed issue whereby json conversion errors due to control characters in stringv1.5.2Revert to aiohttp and fix errors with v3.9.x that caused move to httpxv1.5.1Fix nuances with httpxv1.5.0Move to httpx instead of aiohttpv1.4.0Add PowerTagE supportAdd new v2 hub cloud parametersAdd new v2 hub capabilities infoAdd v2 hub equipment data to relevant devicesAdd tilt support for shuttersFix issue where non ASCII chars removedv1.3.9Fix for hub firmware bug whereby Away Mode Affects HotWater is turned off when cancelling overrides if no overrides exist.v1.3.8Correct relative modulation level opentherm parameter magnitudev1.3.7Amend battery to return None for voltage and percent if battery data not present1.3.6Add new status classFix error if passive mode room device offlinev1.3.5Correct async error in extra_configv1.3.4Current temperature now returns none for room if TRV signal lost.v1.3.3Fixed issue in passive mode so that it works with 3 channel hub and different rooms on different channelsv1.3.2Fixed issue ot maintaining some parameters after hub updateImproved handling of extra config json errorsAmended current_target_temp to use DisplayedSetPoint instead of CurrentSetPoint as this displays incorrectly in Eco mode1.3.1Away mode overrides passive mode functions1.3.0Rework passive mode functionality (may break previous code if using passive mode)1.2.2Improve logic defining is_passive_mode property1.2.1Code refactoringAdded is_passive_mode propertyCorrected bug in passive mode automation to determine target temp1.2.0Breaking Change - changes to passive mode from on or off to disabled, passive manual and passive follow scheduleSupport boost in passive modeAdd additional opentherm parametersFix not clearing overrides when enabling passive mode1.1.1Fix issue setting on/off schedule - issue #3491.1.0Added room passive mode automation control1.0.2Fixed error in boost_all_rooms using old temp validation type (no longer supported)Fixed error in validating temps from yaml file1.0.1Added endpoint parameter to set_opentherm_parameter1.0.0Moved to stable build versionAmended timeout error textImproved error handling for setting schedulesAdded temp sensor support for heating actuatorAdded support for network diagnosticsAdded support for non standard portAdd boiler parameters to openthermSupport setting opentherm parameters0.1.8Add url to exception messagesFix for unicode decode error0.1.7Fixed error intiallising WiserUFHController classMade python3.9 compatible0.1.6Remove debuggin print linesRemove session close on endpoint error0.1.5Add ALL as special day option in schedule file for setting schedules from file0.1.4Fix incorrect id used for schedule assignment in electrical devices0.1.3Fixed issue in schedule.get_by_name0.1.2Fixed calling wrong enpoint id for lights and shutters0.1.0Initial asyncio release |
aiowithings | Python: WithingsAsynchronous Python client for Withings.AboutThis package allows you to fetch data from Withings.InstallationpipinstallaiowithingsChangelog & ReleasesThis repository keeps a change log usingGitHub's releasesfunctionality. The format of the log is based onKeep a Changelog.Releases are based onSemantic Versioning, and use the format
ofMAJOR.MINOR.PATCH. In a nutshell, the version will be incremented
based on the following:MAJOR: Incompatible or major changes.MINOR: Backwards-compatible new features and enhancements.PATCH: Backwards-compatible bugfixes and package updates.ContributingThis is an active open-source project. We are always open to people who want to
use the code or contribute to it.We've set up a separate document for ourcontribution guidelines.Thank you for being involved! :heart_eyes:Setting up development environmentThis Python project is fully managed using thePoetrydependency manager. But also relies on the use of NodeJS for certain checks during development.You need at least:Python 3.11+PoetryNodeJS 12+ (including NPM)To install all packages, including all development requirements:npminstall
poetryinstallAs this repository uses thepre-commitframework, all changes
are linted and tested with each commit. You can run all checks and tests
manually, using the following command:poetryrunpre-commitrun--all-filesTo run just the Python tests:poetryrunpytestAuthors & contributorsThe content is byJoost Lekkerkerker.For a full list of all authors and contributors,
checkthe contributor's page.LicenseMIT LicenseCopyright (c) 2023-2024 Joost LekkerkerkerPermission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. |
aiowmi | Python WMIWindows Management Interface connector using asyncio for the Python language.Supports:NTLM AuthenticationWMI Query (IWbemServices_ExecQuery)Parsing of basic WMI Objects (int/float/str/datetime/array/references)Optimized queries using the SmartEnum implementationTodo:Kerberos AuthenticationAsync WMI Query (IWbemServices_ExecQueryAsync)Other DCOM/RPC/WMI calls?Support for WMI Methods?Improve documentationUsageThe example below covers most of what is suppored by this library:importasyncioimportloggingimporttimefromaiowmi.connectionimportConnectionfromaiowmi.queryimportQueryasyncdefmain():host='10.0.0.1'# ip address or hostname or fqdnusername='username'password='password'domain=''# optional domain name# Query has a default namespace 'root/cimv2'queries=(Query('SELECT * FROM Win32_OperatingSystem',namespace='root/cimv2'),Query('SELECT * FROM Win32_NetworkAdapter'),Query('SELECT * FROM Win32_LoggedOnUser'),Query('SELECT * FROM Win32_PnpEntity'),Query('SELECT Caption, Description, InstallDate, InstallDate2, ''InstallLocation, InstallSource, InstallState, Language, ''LocalPackage, Name, PackageCache, PackageCode, PackageName, ''ProductID, RegCompany, RegOwner, SKUNumber, Transforms, ''URLInfoAbout, URLUpdateInfo, Vendor, Version ''FROM Win32_Product'),Query('SELECT Name, DiskReadsPersec, DiskWritesPersec ''FROM Win32_PerfFormattedData_PerfDisk_LogicalDisk'),)start=time.time()conn=Connection(host,username,password,domain=domain)service=Noneawaitconn.connect()try:service=awaitconn.negotiate_ntlm()forqueryinqueries:print(f"""################################################################################ Start Query:{query.query}###############################################################################""")asyncwithquery.context(conn,service)asqc:asyncforpropsinqc.results():# Function `get_properties(..)` accepts a few keyword# arguments:## ignore_defaults:# Ignore default values. Set missing values to None# if a value does not exist in the current class.# ignore_defaults will always be True if# ignore_missing is set to True.# ignore_missing:# If set to True, values missing in the current class# will not be part of the result.# load_qualifiers:# Load the qualifiers of the properties. If False,# the property qualifier_set will have the offset# in the heap where the qualifiers are stored.#forname,propinprops.items():print(name,'\n\t',prop.value)ifprop.is_reference():# References can easy be queried using the# get_reference(..) function. The function accepts# a keyword argument `filter_props=[..]` with an# optional list of properties to query. If omitted,# the function returns all (*) properties.res=awaitprop.get_reference(conn,service)ref_props=res.get_properties(ignore_missing=True)forname,propinref_props.items():print('\t\t',name,'\n\t\t\t',prop.value)print(f"""----------------------------------- End Item ----------------------------------""")finally:ifservice:service.close()conn.close()end=time.time()print('done in ',end-start)if__name__=='__main__':logger=logging.getLogger()logger.setLevel(logging.DEBUG)ch=logging.StreamHandler()ch.setLevel(logging.DEBUG)formatter=logging.Formatter(fmt='[%(levelname)1.1s%(asctime)s%(module)s:%(lineno)d] '+'%(message)s',datefmt='%y%m%d%H:%M:%S',style='%')ch.setFormatter(formatter)asyncio.run(main()) |
aiowolfram | No description available on PyPI. |
aioworker | aioworkerA Python worker running overasyncioRequirementspython 3.8+InstallationpipinstallaioworkerUsageimportasynciofromaioworkerimportService,Workerasyncdeftask_1(loop):whileTrue:print('Hello world')awaitasyncio.sleep(2)if__name__=='__main__':# Run the server using 1 worker processes.Worker(tasks=[task_1]).run(workers=1)or run tasks and the webserverimportasynciofromaioworkerimportService,Workerasyncdefsleeping(loop):whileTrue:print('Sleeping for 2 seconds...')awaitasyncio.sleep(2)asyncdefon_client_connect(reader,writer):"""Read up tp 300 bytes of TCP. This could be parsed usign the HTTP protocol for example"""data=awaitreader.read(300)print(f'TCP Server data received:{data}\n')writer.write(data)awaitwriter.drain()writer.close()if__name__=='__main__':# Run the server using 1 worker processes.Worker(tasks=[sleeping],web_server_config={'client_connected_cb':on_client_connect,},)).run(workers=1)How to stop the workerctrl+cDefault valuesVariableDefaultTCP server host0.0.0.0TPC server port8888ExamplesHello worldTCP ServerKafka ConsumerDevelopmentClone this repoRunpoetry installTest using./scripts/testLint automatically using./scripts/lint |
aioworkerpool | UNKNOWN |
aioworkers | Easy configurable workers based on asyncioFree software: Apache Software License 2.0Required: Python >=3.7, optionalpyyaml,uvloop,httptools,yarl,crontab,setproctitle,msgpack,bson,jupyter.Documentation:https://aioworkers.readthedocs.io.FeaturesSpecify abstract class for communication between componentsConfiguration subsystemDevelopmentCheck code:hatchrunlint:allFormat code:hatchrunlint:fmtRun tests:hatchrunpytestRun tests with coverage:hatchruncovHistory0.27.0 (2023-08-11)Drop incorrect stubgen (#202)Method URI.with_host keep auth (#203)Add methods AsyncPath.is_dir/is_file (#205)Fix cmd from cython (#210)0.26 (2023-07-21)AsyncPath.unlink with missing_ok (#197)AsyncPath.rmtree and rmdir (#198)0.25 (2023-07-19)Fix option ++groups and add ++group (#192)Option –version (#193)Improve and fix AsyncPath and add AbstractFileSystem (#195)0.24.1 (2023-07-10)Fix using optional formatter and output (#188)0.24 (2023-07-08)Improve SocketServer.cleanup (#177)Web server support keep-alive (#179)Option –config/-c one value on key (#182)Option ++group/+g one value on key (#183)Cli support –output and –formatter for format results (#186)Use name in iter_entry_points (#187) |
aioworkers-aiohttp | The package to integration aioworkers with aiohttpFeaturesBuilding of the routing from config like swaggerStart aiohttp project with multiprocessing modeExamplehttp:port:8080access_log:format:%a %t "%r" %s %b "%{Referer}i" "%{User-Agent}i"app:routes:-mymodule.route_table-mymodule.routeresources:/html:static:static/html/css:static:path:static/cssapi:prefix:/apipets:/pet/{pet_id}:get:tags:[Pet]handler:mymodule.mycorodescription:Info about petparameters:-name:pet_idin:pathtype:integerminimum:0responses:200:description:OK400:description:Validation error404:description:Not foundDevelopmentCheck code:hatchrunlint:allFormat code:hatchrunlint:fmtRun tests:hatchrunpytestRun tests with coverage:hatchruncov |
aioworkers-amqp | No description available on PyPI. |
aioworkers-boto | Aioworkers BotoTable of ContentsInstallationUseLicenseInstallationpip install aioworkers-botoUses3:cls:aioworkers_boto.storage.Storagebucket:mybucketpath:subdir/subsubdirconnection:endpoint_url:https://...aws_secret_access_key:'&124323453456789'aws_access_key_id:key-idregion_name:us-east-1format:jsonawaitcontext.s3.set(key,data)# save datad=awaitcontext.s3.get(key)# get dataawaitcontext.s3.set(key,None)# deleteLicenseaioworkers-botois distributed under the terms of theApache-2.0license. |
aioworkers-consul | aioworkers-consulAboutIntegration withHashicorp Consul.Useconsul:host:localhost:8500# optionalservice:# optionalname:mytags:-workerDevelopmentCheck code:hatchrunlint:allFormat code:hatchrunlint:fmtRun tests:hatchrunpytestRun tests with coverage:hatchruncov |
aioworkers-databases | aioworkers-databasesaioworkers plugin fordatabases.UsageAdd your database config to aioworkersconfig.yaml:db:cls:aioworkers_databases.database.Databasedsn:sqlite:///db.sqlitelogging:version:1disable_existing_loggers:falseroot:level:ERRORhandlers:[console]handlers:console:level:DEBUGclass:logging.StreamHandlerloggers:aioworkers_databases:level:ERRORhandlers:[console]propagate:trueRunaioworkers:aioworkers-cconfig.yaml-iCreateContextfor this config and use your db via context:awaitcontext.db.execute('CREATE TABLE some_table (id INT);')DevelopmentInstall requirements:poetryinstallRun tests:pytest |
aioworkers-ipc | No description available on PyPI. |
aioworkers-loki | aioworkers-lokiAboutIntegration withgrafana loki.
Works onpython-logging-lokiUselogging:version:1root:handlers:[loki]handlers:loki:host:localhost:3100DevelopmentInstall dev requirements:poetryinstallRun linters:make |
aioworkers-mongo | aioworkers-mongoMongo plugin foraioworkers.UsageConnectionAdd this to aioworkers config.yaml:mongo:cls:aioworkers_mongo.base.Connectoruri:'mongodb://localhost:27017/'You can get access to mongo anywhere via context:docs=[docasyncfordocincontext.mongo.db.collection.find({})]Extended client configmongo:cls:aioworkers_mongo.base.Connectorclient:host:'localhost'port:27017DevelopmentRun Mongo DB:dockerrun--rm-p27017:27017--namemongo-dmongoInstall dev requirements:poetryinstallActivate env:..venv/bin/activateRun tests:pytest |
aioworkers-orm | aioworkers-ormAn aioworkers plugin forormto addorm.Modelavailable viaaioworkers.core.context.Context.Features:Attach model by class reference.Create model by specification.DevelopmentInstall dev requirements:poetryinstallRun tests:pytest |
aioworkers-pg | aioworkers-pgAsyncpg plugin foraioworkers.UsageConnectionAdd this to aioworkers config.yaml:db:cls:aioworkers_pg.base.Connectordsn:postgresql:///testYou can get access to postgres anywhere via context:awaitcontext.db.execute('CREATE TABLE users(id serial PRIMARY KEY, name text)')awaitcontext.db.execute(users.insert().values(name='Bob'))Connection additionaldb:cls:aioworkers_pg.base.Connectordsn:postgresql:///testpool:min_size:1max_size:100Storagestorage:cls:aioworkers_pg.storage.RoStoragedsn:postgresql:///testtable:mytable# optional instead custom sqlkey:idget:SELECT * FROM mytable WHERE id = :id# optional custom sqlformat:dict# or rowDevelopmentInstall dev requirements:poetryinstallRun postgres:dockerrun--rm-p5432:5432--namepostgres-ePOSTGRES_PASSWORD=postgres-ePOSTGRES_DB=test-dpostgresRun tests:pytest |
aioworkers-prometheus | Usemetric:registry:aioworkersnamespace:aioworkers_test_metricmetrics:my_counter:type:countername:test_counterdocumentation:Counter for testsmy_histogram:type:histogramname:test_histogramdocumentation:Histogram for testsbuckets:[30,90,100,200,400,800]Use in codecontext.metric.my_counter.inc()context.metric.my_histogram.observe(542)withcontext.metric.my_histogram.time():awaitasyncio.sleep(1)Add global labels to default registry to expositionprometheus:registry:aioworkerslabels:env:prodServe port 8000 for prometheusprometheus:port:8000registry:aioworkersPush to graphite localhost:9090prometheus:registry:aioworkersgraphite:address:localhost:9090interval:1mprefix:aioworkers.testDevelopmentInstall dev requirements:pipenvinstall--dev--skip-lockRun tests:pipenvrunpytest |
aioworkers-redis | Redis plugin foraioworkers.FeaturesWorks onaioredisQueue based onRPUSH,BLPOP,LLEN,LRANGEZQueue based onZADD,ZRANGE,ZCARD,ZRANGE,ZREM,EVALTimestampZQueue based ZQueueStorage based onSET,GETHashStorage based onHSET,HGET,HDEL,HMSET,HMGET,HGETALLHyperLogLogStorage based onPFADD,PFMERGE,PFCOUNTUsageAdd this to aioworkers config.yaml:redis:cls:aioworkers_redis.base.Connectorprefix:appconnection:host:localhostport:6379maxsize:20queue:cls:aioworkers_redis.queue.Queueconnection:.redisformat:jsonkey:queueYou can work with redis queue like this:awaitcontext.queue.put({'a':1})d=awaitcontext.queue.get() |
aioworkers-sentry | aioworkers plugin to work with Sentry. Creates Sentry client and handler according configuration
and setup logging.UsageInstall plugin:pipinstallaioworkers-sentryAdd to your config:sentry:dsn:<your sentry dsn>release:1.0.0environment:DEVintegrations:-sentry_sdk.integrations.aiohttp.AioHttpIntegrationDevelopmentCheck code:hatchrunlint:allFormat code:hatchrunlint:fmtRun tests:hatchrunpytestRun tests with coverage:hatchruncov |
aioworkers-tg | Plugin to work withTelegraminaioworkers.Features:Telegram user.Telegram channels.Telegram groups.UsageInstall it with pip:pipinstallaioworkers-tgCreate entity of bot in aioworkers config:bot:cls:'aioworkers_tg.bot.TelegramBot'api_token:'1234567890'You can use it directly from context:awaitcontext.bot.channel('@yourchannel').send_text("Hello from channel!")Also it is possible to create chat instance and send messages directly:chat:cls:'aioworkers_tg.chat.TelegramChat'bot:'bot'# reference to created botgroup_id:'11111'awaitcontext.chat.send_text("Hello!") |
aioworldline | Unofficial Worldline portal data retrieving client |
aiowowapi | aiowowapi docsAn asynchronous client library for interacting with the World of Warcraft API endpoints using theasync/awaitsyntax.Installing# Linux/OSXpython3-mpipinstall-Uaiowowapi# Windowspython-mpipinstall-UaiowowapiCurrent FeaturesRetail Game Data API SupportRetail Profile API SupportClassic Game Data API SupportRate limitingRequest retriesQoL WoW-Specific functions (Money -> Gold/Silver/Copper, Armoury link parser, etc)TODOAdd caching for certain requests (e.g. character profile)Greater test coverageRequirementsaiohttpPython 3.8+ExamplefromaiowowapiimportWowApiasyncdefmain():asyncwithWowApi('<ID>','<SECRET>','us',request_debugging=True)asClient:print(awaitClient.Retail.Profile.get_character_profile_status('illidan','adalyia'))Linksaiowowapi’s DocumentationBlizzard’s API DocumentationRegister a Blizzard API ClientBlizzard’s API ForumsIMPORTANTThis project is not affiliated with or endorsed byBlizzard Entertainment& all data is retrieved from official Blizzard / World of Warcraft APIs.Terms found here. Additionally this project was created primarily for use with Discord Bots & other async applications with inspiration fromthis projectbylockwooddev. |
aiowrap | Assume that you have some existing libraries with blocking methods:def foo_sync(x, a, b):
"""Some existing library methods. Sleeps for x seconds and returns a + b."""
time.sleep(x)
return a + bAnd you are writing a program in Python3’sasyncioframework. To use the
blocking library, one way is to use a thread pool. This library provides
another option:# Wraps foo_sync() into foo_async() to use in asyncio framework.
time.sleep = aiowrap.wrap_async(asyncio.sleep)
foo_async = aiowrap.wrap_sync(foo_sync)Now you have an asynchronous, non-blocking version of the method, you can call
it inside your favourite coroutine:async def main():
print(await foo_async(1, 2, 3))The source code of this example can be found atexample/sleep.py. |
aiowrpr | # aiowrpr
Toolkit to simplify work with aiohttp module# features
* Built-in swagger specification (provides by [aiohttp-apispec](#https://aiohttp-apispec.readthedocs.io/en/latest/));
* Marshmallow schemes for requests and responses;
* Versioning of API; |
aiowsgi | Require python 2.7, 3.3+Source:https://github.com/gawel/aiowsgi/Docs:https://aiowsgi.readthedocs.org/You like it ? =>https://www.gittip.com/gawel/ |
aiowstunnel | No description available on PyPI. |
aiowwlln | ⚡️ aiowwlln: A simple Python3 wrapper for WWLLNaiowwllnis a simple,asyncio-driven Python library for retrieving information on
lightning strikes fromthe World Wide Lightning Location Network (WWLLNN).NOTE:This library is built on an unofficial API; therefore, it may stop working at
any time.InstallationpipinstallaiowwllnPython Versionsaiowwllnis currently supported on:Python 3.6Python 3.7Python 3.8Usageaiowwllnstarts within anaiohttpClientSession:importasynciofromaiohttpimportClientSessionfromaiowwllnimportClientasyncdefmain()->None:"""Create the aiohttp session and run the example."""asyncwithClientSession()aswebsession:# YOUR CODE HEREasyncio.get_event_loop().run_until_complete(main())Create a client, initialize it, then get to it:importasynciofromdatetimeimportdatetimefromaiohttpimportClientSessionfromaiowwllnimportClientasyncdefmain()->None:"""Create the aiohttp session and run the example."""asyncwithClientSession()aswebsession:client=aiowwlln.Client(websession)# Create a client and get all strike data – by default, data is cached for# 60 seconds (be a responsible data citizen!):client=Client(websession)awaitclient.dump()# If you want to increase the cache to 24 hours, go for it:client=Client(websession,cache_seconds=60*60*24)awaitclient.dump()# Get strike data within a 50 km radius around a set of coordinates (note that# the cache still applies):awaitclient.within_radius(56.1621538,92.2333561,50,unit="metric")# Get strike data within a 10 mile radius around a set of coordinates (note that# the cache still applies):awaitclient.within_radius(56.1621538,92.2333561,10,unit="imperial")# Get strike data within a 50 km radius around a set of coordinates _and_# within the last 10 minutes:awaitclient.within_radius(56.1621538,92.2333561,50,unit="metric",window=timedelta(minutes=10))asyncio.get_event_loop().run_until_complete(main())ContributingCheck for open features/bugsorinitiate a discussion on one.Fork the repository.(optional, but highly recommended) Create a virtual environment:python3 -m venv .venv(optional, but highly recommended) Enter the virtual environment:source ./venv/bin/activateInstall the dev environment:script/setupCode your new feature or bug fix.Write tests that cover your new functionality.Run tests and ensure 100% code coverage:script/testUpdateREADME.mdwith any new documentation.Add yourself toAUTHORS.md.Submit a pull request! |
aio_wx_widgets | aio_wx_widgetsWx python app structure using MVC model. Work in progress, adding widgets when I need them.
See the demo folder for usage.Features:Add widgets using context managers.Two-way or one-way Property binding from controller properties to the view.Proper Margins and alignment of itemsThe example below is a bit outdated, but gives a rough idea. Please see the demo for more.```python
# Use a context manager for container types like a group or grid.
# A group is a container with a label and a sizer inside. Inside
# this sizer widgets, or other containers can be placed.
with self.add(Group("A labelled container.")) as group:
group.add(Text(text="A horizontal grid."))
with group.add(Grid()) as grd:
# the binding binds to an attribute defined in the controller
# the weight determines how much space a specific item should consume
# with respect to the other members of the container.
grd.add(IntEntry(binding=self.bind("value_1")), weight=6, margin=3)
grd.add(IntEntry(binding=self.bind("value_1")), weight=4, margin=3)
grd.add(IntEntry(binding=self.bind("value_1")), weight=4, margin=3)
```
```python
vert_grid.add(
Text(text="Center aligned text with a large margin."),
margin=(10, 10, 30, 5), # (left,right,top,below)
align_horizontal=AlignHorizontal.center,)
```InstallationCreate a virtual env, activate it andpip install aio_wx_widgetsRunning the demoInstall the libary as described above.clone the repo.from the activated virtualenv:python -m demo |
aiox | Currently not working |
aioxiaomi | aioxiaomiaioxiaomi is a Python 3/asyncio library to control Xiaomi Yeelight LED lightbulbs over your LAN.[](https://pypi.python.org/pypi/aioiotprov)
[](https://lbesson.mit-licen)
[](h
ttps://github.com/psf/black)InstallationWe are on PyPi sopip3 install aioxiaomior
python3 -m pip install aioxiaomiHow to useEssentially, you create an object with at least 2 methods:- register
- unregisterYou then start the XiaomiDiscovery task in asyncio with a callback that will create and .activate() any new bulb.
Upon connection with the bulb, it will register itself with the parent. All the method communicating with the bulb
can be passed a callback function to react to the bulb response. The callback should take 2 parameters:- a light object
- the response messageCheckoutmain.py to see how it works.In essence, the test program is thisclass bulbs():
""" A simple class with a register and unregister methods
"""
def __init__(self):
self.bulbs=[]
self.pending_bulbs = []
def register(self,bulb):
self.bulbs.append(bulb)
try:
self.pending_bulbs.remove(bulb)
except:
pass
def unregister(self,bulb):
idx=0
for x in list([ y.bulb_id for y in self.bulbs]):
if x == bulb.bulb_id:
del(self.bulbs[idx])
break
idx+=1
def new_bulb(self, sender, **kwargs):
newbulb = aiox.XiaomiBulb(aio.get_event_loop(),kwargs['headers'],self)
found = False
for x in self.bulbs:
if x.bulb_id == newbulb.bulb_id:
found = True
break
if not found:
for x in self.pending_bulbs:
if x.bulb_id == newbulb.bulb_id:
found = True
break
if not found:
newbulb.activate()
else:
del(newbulb)
def readin():
"""Reading from stdin and displaying menu"""
selection = sys.stdin.readline().strip("\n")
DoSomething()
MyBulbs= bulbs()
loop = aio.get_event_loop()
coro = aiox.start_xiaomi_discovery(MyBulbs.new_bulb)
transp, server = loop.run_until_complete(coro)
try:
loop.add_reader(sys.stdin,readin)
server.broadcast(2)
loop.run_forever()
except:
pass
finally:
server.cancel()
loop.remove_reader(sys.stdin)
loop.close()Other things worth noting:- Whilst XiaomiDiscover uses UDP broadcast, the bulbs are
connected with Unicast TCP
- Xiaomi allows only about 1 command per second per connection. To counter that,
one can start more than one connection to a bulb. There is a limit of
4 connections per bulb, but given that there can only be 144 command per minute
per bulb, only 2 connections can be handled without starting to overload the bulb.
Use .set_connection(x) before activate to set the number of connections
- aioxiaomi ensure that there is at most 1 command per second per connection. To do so
it keeps a buffer of messages and pace the sending (using round-robin if there is more
then one connection). The buffer can thus become quite big. To control this, one can
specify a maximum buffer length and what to do with messages that comes when the buffer
is full. Use set_queue_limit(length,policy) to control.
length is the maximum number of commands waiting to be sent
policy defines what to do with the extra packets:
drop: just drop them
head: queue them but discard the head of the queue
random: queue the message then discard a random element of the queue
adapt: switch to the so-called "music mode" and dump all the messages.
After 5 secs inactivity, the "music mode" is cancelled
- The socket connecting to a bulb is not closed unless the bulb is deemed to have
gone the way of the Dodo.
- I only have "Color" model, so I could not test with other types
of bulbs |
aio-xiq | Extreme Cloud IQ - Python3 AsyncIO ClientThis repository contains a Python3 asyncio based client library for interacting
with the Extreme Cloud IQ system (XIQ).Note that Extreme does provide their own Python SDK client, which can be found
in the reference section below.Installationpipinstallaio-xiqThis XIQ asyncio python client is a subclass from httpx.AsyncClient.QuickStartBefore using the API you must either have an existing token or login with your user-name + password
credentials. You can either pass these values into the client constructor, or use these environment variables:XIQ_USER - the login user-nameXIQ_PASSWORD = the login password-- or --
* XIQ_TOKEN - an existing API tokenUsername + PasswordIf you are using your login credentials you must execute thelogin()method to obtain an access
token.fromaioxiqimportXiqClientasyncwithXiqClient(xiq_user='[email protected]',xiq_password='notarealpassword')asapi:awaitapi.login()devices=awaitapi.fetch_devices()API TokenYou can create an API token via the XIQ portal by nagivating to the Global
Settings page (found under your User profile near the top-right), and then
selecting the "API Token Management" option on the left sidebar.When using the API Token approach, you can use the client diretly without having
to perform the login function.fromaioxiqimportXiqClient# presume that XIQ_TOKEN environment variable is set with an existing token.# you can immediately use the API without login.asyncwithXiqClient()asapi:devices=api.fetch_devices()ReferencesExtreme Developer PortalExtreme XIQ API Online Docts, SwaggerExtreme XIQ APIs Github repoExtreme XIQ Python SDK Github repo |
aioxlsxstream | aioxlsxstreamGenerate the xlsx file on fly without storing entire file in memory.
Generated excel workbook contain only one sheet. All data writes as strings.Installationpip install aioxlsxstreamRequirementsPython 3.8+Simple exapmleimportaioxlsxstreamimportasyncioasyncdefmain():asyncdefrows_generaor():asyncdefrow_cells_generator(row):forcolinrange(5):yieldrow*5+colforrowinrange(10):yieldrow_cells_generator(row)xlsx_file=aioxlsxstream.XlsxFile()xlsx_file.write_sheet(rows_generaor())withopen("example.xlsx","wb")asf:asyncfordatainxlsx_file:f.write(data)asyncio.run(main())aiohttp Examplefromaiohttpimportweb,hdrsimportaioxlsxstreamasyncdefrows_generaor():asyncdefrow_cells_generator(row):forcolinrange(5):yieldrow*5+colforrowinrange(10):yieldrow_cells_generator(row)asyncdefhandle(request):filename="example.xlsx"response=web.StreamResponse(status=200,headers={hdrs.CONTENT_TYPE:"application/octet-stream",hdrs.CONTENT_DISPOSITION:(f"attachment; "f'filename="{filename}"; '),},)awaitresponse.prepare(request)xlsx_file=aioxlsxstream.XlsxFile()# or CsvFile("csv") or CsvFile("tsv")xlsx_file.write_sheet(rows_generaor())asyncfordatainxlsx_file:awaitresponse.write(data)returnresponseapp=web.Application()app.add_routes([web.get('/',handle)])if__name__=='__main__':web.run_app(app) |
aioxmlrpc | Asyncio version of the standard libxmlrpcCurrently onlyaioxmlrpc.client, which works likexmlrpc.clientbut
with coroutine is implemented.Fill free to fork me if you want to implement the server part.aioxmlrpcis based onhttpxfor the transport, and just patch
the necessary from the python standard library to get it working.Installationaioxmlrpc is available on PyPI, it can simply be installed with your favorite
tool, example with pip here.pip install aioxmlrpcGetting StartedThis example show how to print the current version of the Gandi XML-RPC api.import asyncio
from aioxmlrpc.client import ServerProxy
@asyncio.coroutine
def print_gandi_api_version():
api = ServerProxy('https://rpc.gandi.net/xmlrpc/')
result = yield from api.version.info()
print(result)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(print_gandi_api_version())
loop.stop()Run the examplepoetry run examples/gandi_api_version.py |
aioxmpp | … is a pure-python XMPP library using theasynciostandard library module from Python 3.4 (andavailable as a third-party module to Python 3.3).FeaturesNativeStream Management (XEP-0198)support for robustness against
transient network failures (such as switching between wireless and wired
networks).Powerful declarative-style definition of XEP-based and custom protocols. Most
of the time, you will not get in contact with raw XML or character data, even
when implementing a new protocol.Secure by default: TLS is required by default, as well as certificate
validation. Certificate or public key pinning can be used, if needed.Support forRFC 6121 (Instant Messaging and Presence)roster and presence management, along
withXEP-0045 (Multi-User Chats)for your human-to-human needs.Support forXEP-0060 (Publish-Subscribe)andXEP-0050 (Ad-Hoc Commands)for your machine-to-machine
needs.Several other XEPs, such asXEP-0115(including native support for
the reading and writing thecapsdb) andXEP-0131.APIs suitable for both one-shot scripts and long-running multi-account
clients.Well-tested and modular codebase: aioxmpp is developed in test-driven
style and in addition to that, many modules are automatedly tested againstProsodyandejabberd,
two popular XMPP servers.There is more and there’s yet more to come! Check out the list of supported XEPs
in theofficial documentationandopen GitHub issues tagged as enhancementfor things which are planned and read on below on how to contribute.DocumentationTheaioxmppAPI is thoroughly documented using Sphinx. Check out theofficial documentationfor aquick startand theAPI reference.DependenciesPython ≥ 3.4 (or Python = 3.3 with tulip and enum34)DNSPythonlxmlsortedcollectionstzlocal(for i18n support)pyOpenSSLpyasn1andpyasn1_modulesaiosasl(≥ 0.3 forANONYMOUSsupport)multidictaioopenssltyping(Python < 3.5 only)ContributingIf you consider contributing to aioxmpp, you can do so, even without a GitHub
account. There are several ways to get in touch with the aioxmpp developer(s):The development mailing list. Feel
free to subscribe and post, but be polite and adhere to theNetiquette
(RFC 1855). Pull requests posted to
the mailing list are also welcome!The development MUC [email protected]. Pull requests
announced in the MUC are also welcome! Note that the MUC is set persistent,
but nevertheless there may not always be people around. If in doubt, use the
mailing list instead.Open or comment on an issue or post a pull request onGitHub.No idea what to do, but still want to get your hands dirty? Check out the list
of‘help wanted’ issues on GitHubor ask in the MUC or on the mailing list. The issues tagged as ‘help wanted’ are
usually of narrow scope, aimed at beginners.Be sure to read thedocs/CONTRIBUTING.rstfor some hints on how to
author your contribution.Security issuesIf you believe that a bug you found in aioxmpp has security implications,
you are welcome to notify me privately. To do so, send a mail toJonas Schäfer, encrypted using the GPG public key
0xE5EDE5AC679E300F (Fingerprint AA5A 78FF 508D 8CF4 F355 F682 E5ED E5AC 679E
300F).If you prefer to disclose security issues immediately, you can do so at any of
the places listed above.More details can be found in theSECURITY.mdfile.Change logThechange logis included in theofficial documentation. |
aioxnat | No description available on PyPI. |
aioxrpy | aioxrpyRipple blockchain library for Python.FeaturesAsync JSON-RPC client.Signing and verifying transactions using private and public keys.Support for signing transactions with multiple keys.Serializer and deserializer for Ripple objects.InstallationLibrary is available on PyPi, you can simply install it usingpip.$ pip install aioxrpyUsageKeysSigning and verifying transactions, as well as generating new accounts is done throughRippleKeyclass.from aioxrpy.keys import RippleKey
# New key
key = RippleKey()
# From public key
key = RippleKey(public_key=b'public key')
# From master seed
key = RippleKey(private_key='seed')
# From private key
key = RippleKey(private_key=b'private key')Such key can be converted to Account ID and public key.Submitting transactionsRPC client provides a helper which signs and submits transaction. As a first
argument it takes a transaction dict. The second one is aRippleKeyinstance
used for signing this transaction.from aioxrpy.rpc import RippleJsonRpc
rpc = RippleJsonRpc(url)
await rpc.sign_and_submit(
{
'Account': account,
'TransactionType': RippleTransactionType.Payment,
'Amount': decimals.xrp_to_drops(200),
'Destination': destination,
'Fee': 10
},
signer
)Multi-signed transactionsRPC client provides a helper which signs and submits transaction using multiple
keys. As a second argument, it expects a list ofRippleKeyinstances. Please
don't forget that each signer increases transaction fees.from aioxrpy.rpc import RippleJsonRpc
rpc = RippleJsonRpc(url)
await rpc.multisign_and_submit(
{
'Account': account,
'TransactionType': RippleTransactionType.Payment,
'Amount': decimals.xrp_to_drops(200),
'Destination': destination,
'Fee': 30
},
[signer_1, signer_2]
)DocumentationDocs and usage examples are availablehere.Unit testingTo run unit tests, you need to bootstrap a Rippled regtest node first. Use the provideddocker-compose.ymlfile.$ docker-compose up -d |
aioyagmail | aioyagmail -- Yet Another GMAIL/SMTP client, using AsyncIOThe goal here is to make it as simple and painless as possible to send emails using asyncio.In the end, your code will look something like this:importasynciofromaioyagmailimportAIOSMTPloop=asyncio.get_event_loop()asyncdefsend_single():# walks you through oauth2 process if no file at this locationasyncwithAIOSMTP(oauth2_file="~/oauth2_gmail.json")asyag:awaityag.send(to="[email protected]",subject="hi")asyncdefsend_multi():asyncwithAIOSMTP(oauth2_file="~/oauth2_gmail.json")asyag:# Runs asynchronously!awaitasyncio.gather(yag.send(subject="1"),yag.send(subject="2"),yag.send(subject="3"))loop.run_until_complete(send_single())loop.run_until_complete(send_multi())Username and passwordIt is possible like inyagmailto use username and password, but this is not actively encouraged anymore.
Seehttps://github.com/kootenpv/yagmail#username-and-passwordhow to do it.For more informationHave a look atyagmail. Any issue NOT related to async should be posted there (or found out about).Word of cautionWatch out that gmail does not block you for spamming. Using async you could potentially be sending emails too rapidly.DonateIf you likeaioyagmail, feel free (no pun intended) to donate any amount you'd like :-) |
aio_yamlconfig | .. image:: https://img.shields.io/pypi/v/aio_yamlconfig.svg:target: https://pypi.org/project/aio_yamlconfig.. image:: https://img.shields.io/travis/rrader/aio_yamlconfig/master.svg:target: http://travis-ci.org/rrader/aio_yamlconfig.. image:: https://img.shields.io/pypi/pyversions/aio_yamlconfig.svg.. image:: https://img.shields.io/pypi/dm/aio_yamlconfig.svgaio_yamlconfig========Quick Start------------------Install from PYPI:.. code:: shellpip install aio_yamlconfigOR (less popular) via setup.py:.. code:: shellpython -m setup installYAML configuration parser with validation using `Trafaret <http://trafaret.readthedocs.org/en/latest/>`_.In the easiest setup without config validation, configure your ``aiohttp`` application with:.. code:: python:number-lines:CONFIG_FILE = os.path.join(os.path.dirname(__file__), "config.yaml")loop.run_until_complete(aio_yamlconfig.setup(app,config_files=[CONFIG_FILE],base_dir=os.path.dirname(__file__)))Assume you have ``config.yaml``:.. code:: yaml:number-lines:DEBUG: TrueTEMPLATES_DIR: !BaseDir path/to/templatesThen you can access your config as:.. code:: python:number-lines:if app.config['DEBUG']:print('some debug information')Notice the ``!BaseDir`` tag. ``aio_yamlconfig`` can do some config transformations for you, in this case it will prependthe base directory (passed as ``base_dir`` to ``setup()``) to your path. The variable ``app.config['TEMPLATES_DIR']`` will containthe full path to directory with your templates.Validation--------------------To validate your config we use the great library Trafaret. You can read more about it `in the docs <http://trafaret.readthedocs.org/en/latest/>`_.Here I'll give you a simple example of its usage.Let's write the validator for ``config.yaml`` above. We'd like to ensure that ``DEBUG`` value is boolean, and thatdirectory of the path ``TEMPLATES_DIR`` really exists:.. code:: python:number-lines:import trafaret as tfrom aio_yamlconfig.trafarets import ExistingDirectoryCONFIG_TRAFARET = t.Dict({t.Key('TEMPLATES_DIR'): ExistingDirectory,t.Key('DEBUG'): t.Bool})To enable such validation pass the ``trafaret_validator`` to ``setup()`` function:.. code:: python:number-lines:loop.run_until_complete(aio_yamlconfig.setup(app,config_files=[CONFIG_FILE],trafaret_validator=CONFIG_TRAFARET,base_dir=os.path.dirname(__file__))) |
aio-yampush | This is a security placeholder package.
If you want to claim this name for legitimate purposes,
please contact us [email protected]@yandex-team.ru |
aio-yandex-translate | aio_yandex_translateAsync yandex.translate api wrapper for pythonExample of usageimportasynciofromaio_yandex_translate.translatorimportTranslatorkey="TOKEN"asyncdefmain():text='Hello world'print(text)t=Translator(key)r=awaitt.translate(text,to_language='ru')print(r)loop=asyncio.get_event_loop()loop.run_until_complete(main())If you need to use proxiesimportasynciofromaio_yandex_translate.translatorimportTranslatorkey="TOKEN"asyncdefmain():text='Hello world't=Translator(key,proxy="http://user:[email protected]:1080")r=awaitt.translate(text,to_language='ru')print(r)loop=asyncio.get_event_loop()loop.run_until_complete(main())Seeaiohttp-proxy, it should also support socks proxiesChanging proxies on the goimportasynciofromaio_yandex_translate.translatorimportTranslatorkey="TOKEN"asyncdefmain():text='Hello world't=Translator(key,proxy="http://user:[email protected]:1080")r=awaitt.translate(text,to_language='ru')t.proxy="http://user:password@localhost:1080"r=awaitt.translate(text,to_language='ru')print(r)loop=asyncio.get_event_loop()loop.run_until_complete(main())Detecting languageasyncdefmain():text='Hello world't=Translator(key,proxy="http://user:[email protected]:1080")r=awaitt.detect_lang(text)print(r)loop=asyncio.get_event_loop()loop.run_until_complete(main())To add a new hint you should use the functionadd_hintwith passedlangparameter and in return you'll get bool value representing if it was addedTo remove lang from hints:fromaio_yandex_translate.translatorimportTranslatorkey="TOKEN"translator=Translator(key)translator.add_hint("en")translator.hints.remove("en")Explaining some detailsTo get to exceptions that module can throw you may go
to Translator.exc and see classes of exceptions (TranslatorError is base)The code is really short but i hope it will help you! |
aioyeelight | aioxiaomiaioxiaomi is a Python 3/asyncio library to control Xiaomi Yeelight LED lightbulbs over your LAN.InstallationWe are on PyPi sopip3 install aioxiaomior
python3 -m pip install aioyeelightEncryption KeyTHis library uses the MIHome binary protocol as described byOpenMiHomeThis means you must acquire the envryption key that is generated during provisioning.The easiest way is to provision the bulbs withaioiotprov.How to useEssentially, you create an object with at least 2 methods:- register
- unregisterYou then use start_yeelight_discovery, to search for light bulbs with a callback that will create and .activate() any new bulb.
Upon connection with the bulb, it will register itself with the parent. All the method communicating with the bulb
can be passed a callback function to react to the bulb response. The callback should take 1 parameters:- the response messageCheckoutmain.py to see how it works.In essence, the test program is thistokenlist = { <mac>: <secret token>}
class bulbs():
""" A simple class with a register and unregister methods
"""
def __init__(self):
self.bulbs=[]
self.pending_bulbs = []
def register(self,bulb):
self.bulbs.append(bulb)
try:
self.pending_bulbs.remove(bulb)
except:
pass
def unregister(self,bulb):
idx=0
for x in list([ y.bulb_id for y in self.bulbs]):
if x == bulb.bulb_id:
del(self.bulbs[idx])
break
idx+=1
def new_bulb(self, info):
if "light" in info["name"] and info["mac"] in tokenlist:
newbulb = aiox.YeelightBulb(
aio.get_event_loop(),
tokenlist[info["mac"]],
info["address"],
info["mac"],
self,
)
found = False
for x in self.bulbs:
if x.bulb_id == newbulb.bulb_id:
found = True
break
if not found:
for x in self.pending_bulbs:
if x.bulb_id == newbulb.bulb_id:
found = True
break
if not found:
newbulb.activate()
else:
del(newbulb)
def readin():
"""Reading from stdin and displaying menu"""
selection = sys.stdin.readline().strip("\n")
DoSomething()
MyBulbs= bulbs()
loop = aio.get_event_loop()
zc, browser = aiox.start_yeelight_discovery(MyBulbs.new_bulb)
try:
loop.add_reader(sys.stdin,readin)
loop.run_forever()
except:
pass
finally:
browser.cancel()
loop.run_until_complete(zc.close())
MyBulbs.close()
loop.remove_reader(sys.stdin)
loop.close()Other things worth noting:Discovery is done usingaiozeroconfYeelights allows only about 1 command per second per connection. To counter that,one can start more than one connection to a bulb. There is a limit of 4 connections per bulb, but given that there can only be 144 command per minute per bulb, only 2 connections can be handled without starting to overload the bulb. Use .set_connection(x) before activate to set the number of connectionsaioyeelight ensure that there is at most 1 command per second per connection. To do so it keeps a buffer of messages and pace the sending (using round-robin if there is more then one connection). The buffer can thus become quite big.aioyeelight will ping a bulb with a 'hello' message. This appears to be necessary for the bulb to keep responding.I only have "Color" model, so I could not test with other types of bulbs |
aioymaps | aioymapsis an asynchronous library provides API to fetch json information
about transport stops from Yandex MapsRequirementsaioymapsrequires python 3.5 or higher due to async/await syntax and aiohttp
libraryInstallationUse pip to install the library:pip install aioymapsOr install manually.sudo python ./setup.py installUsagefrom aioymaps import YandexMapsRequester
requester = YandexMapsRequester()
data = await requester.get_stop_info('stop__10067199')
print(data)Or you can use it in your shell:python -m aioymaps -s group__219 |
aioynab | YNABAPI client implemented using python 3 asyncio.Installaioynab can easily be installed using pip and python >= 3.5.3:$pipinstallaioynabQuick StartFirst create a personal access token in yourYNAB account.
Create a client with that value like the example below.importasynciofromaioynab.clientimportClientloop=asyncio.get_event_loop()client=Client('ynab-personal-access-token')budgets=loop.run_until_complete(client.budgets()))budget_id=budgets['budgets'][0]['budget_id']accounts=loop.run_until_complete(client.accounts(budget_id))account_id=accounts['accounts'][0]['account_id']transactions=loop.run_until_complete(client.account_transactions(budget_id,account_id))DocumentationConsult thedocsfor further information. |
aioyookassa | 🔗 Links🎓Documentation:CLICK🖱️Developer contacts:🐦 DependenciesLibraryDescriptionaiohttpAsynchronous HTTP Client/Server for asyncio and Python.pydanticJSON Data Validator |
aioyoutube | AioyoutubeAboutUsageAboutAioyoutube is a Python async wrapper for youtube.com REST API.UsageNote:For use aioyoutube package, you must create youtube application
and generate API application key. You can do it
on https://console.developers.google.comInstall packagepip install aioyoutubeUse apiAll description of youtube api methods you can find onyoutube api page.
All api method names in package match with youtube api method names.Currently implemented methods:searchcommentscommentThreadschannelsplaylistItemsplaylistsvideosExapmple using youtube api method "search":importasynciofromaioyoutubeimportApiapi=Api()loop=asyncio.get_event_loop()search=api.search(key='your application key',text='search text')task=loop.create_task(search)result=loop.run_until_complete(task) |
aioyoyo | Aioyoyo
A port of oyoyo to Asyncio for Python 3.5Uses Asyncio instead of its original threading client. Creating an IRCClient instance will create the protocol instance.
To start the connection run IRCClient.connect(); (coroutine)Uses oyoyo from [illuminatedWax](https://github.com/illuminatedwax)’sPesterchum, slightly modified |
aioytmdesktopapi | YouTube Music Desktop Remote Control APIAsync IO API package forYouTube Music Desktop app.Installationpython3-mpipinstallaioytmdesktopapiContentsThis package contains theYtmDesktopclass which represents the API.
Check theAPI documentationto see what functionality is available and how to use it.Example usageCheckexample.pyfor a runnable example.asyncwithaiohttp.ClientSession()assession:asyncwithYtmDesktop(session,"192.168.1.123",password="PASSWORD")asytmdesktop:# Initialize first before using any of the functionalityawaitytmdesktop.initialize()# Print status of some attributesprint(f"{ytmdesktop.player.has_song=}")print(f"{ytmdesktop.player.is_paused=}")print(f"{ytmdesktop.track.author=}")print(f"{ytmdesktop.track.title=}")print(f"{ytmdesktop.track.album=}")# Pause the current trackawaitytmdesktop.send_command.track_pause()# Call `.update()` to update the internal state of the API with the state of the actual player instanceawaitytmdesktop.update()# Print updated stateprint(f"{ytmdesktop.player.is_paused=}")time.sleep(2)# Play the current trackawaitytmdesktop.send_command.track_play()# Call `.update()` to update the internal state of the API with the state of the actual player instanceawaitytmdesktop.update()# Print updated stateprint(f"{ytmdesktop.player.is_paused=}") |
aiozabbix | aiozabbixaiozabbixis a Python package that provides an asynchronous
interface to theZabbix API,
using aiohttp. It is based onPyZabbix.Example usageThe interface mimics PyZabbix as closely as possible:importasynciofromaiozabbiximportZabbixAPIasyncdefmain():zapi=ZabbixAPI('https://zabbixserver.example.com/zabbix')awaitzapi.login('zabbix user')hosts=awaitzapi.host.get(output=['host','hostid','name','status'])print(hosts)if__name__=='__main__':loop=asyncio.get_event_loop()loop.run_until_complete(main())loop.close()To customize the HTTP requests, for example to perform HTTP basic
authentication, you need to provide your ownaiohttp.ClientSession:importasyncioimportaiohttpfromaiozabbiximportZabbixAPIasyncdefmain():auth=aiohttp.BasicAuth('zabbix user',password='zabbix password')asyncwithaiohttp.ClientSession(auth=auth)assession:zapi=ZabbixAPI('https://zabbixserver.example.com/zabbix',client_session=session)awaitzapi.login('zabbix user')hosts=awaitzapi.host.get(output=['host','hostid','name','status'])print(hosts)if__name__=='__main__':loop=asyncio.get_event_loop()loop.run_until_complete(main())loop.close() |
aiozaneapi | Made for Python 3.6+.Website LinkExample:importaiozaneapi# Import the package so it can be used.client=aiozaneapi.Client('Token Here')# Instantiate the Client.try:image=awaitclient.magic('Image URL Here')# This will return a BytesIO object.exceptaiozaneapi.GatewayErroraserr:print(f'Error has occurred on the server-side.{err}')exceptaiozaneapi.UnauthorizedErroraserr:print(f'Error has occurred on the client-side.{err}')awaitclient.close()# Close the client unless you want aiohttp screaming at you. |
aioze | # aioZeaioZe is an aiohttp-based wrapper around the oZe ENT http API |
aiozello | aiozelloasync Zello Channel API client |
aiozeroconf | No description available on PyPI. |
aiozipkin | aiozipkinaiozipkinis Python 3.6+ module that adds distributed tracing capabilities
fromasyncioapplications with zipkin (http://zipkin.io) server instrumentation.zipkinis a distributed tracing system. It helps gather timing data needed
to troubleshoot latency problems in microservice architectures. It manages
both the collection and lookup of this data. Zipkin’s design is based on
the Google Dapper paper.Applications are instrumented withaiozipkinreport timing data tozipkin.
The Zipkin UI also presents a Dependency diagram showing how many traced
requests went through each application. If you are troubleshooting latency
problems or errors, you can filter or sort all traces based on the
application, length of trace, annotation, or timestamp.FeaturesDistributed tracing capabilities toasyncioapplications.Supportzipkinv2protocol.Easy to use API.Explicit context handling, no thread local variables.Can work withjaegerandstackdriverthrough zipkin compatible API.zipkin vocabularyBefore code lets learn importantzipkinvocabulary, for more detailed
information please visithttps://zipkin.io/pages/instrumentingSpanrepresents one specific method (RPC) callAnnotationstring data associated with a particular timestamp in spanTag- key and value associated with given spanTrace- collection of spans, related to serving particular requestSimple exampleimportasyncioimportaiozipkinasazasyncdefrun():# setup zipkin clientzipkin_address='http://127.0.0.1:9411/api/v2/spans'endpoint=az.create_endpoint("simple_service",ipv4="127.0.0.1",port=8080)tracer=awaitaz.create(zipkin_address,endpoint,sample_rate=1.0)# create and setup new tracewithtracer.new_trace(sampled=True)asspan:# give a name for the spanspan.name("Slow SQL")# tag with relevant informationspan.tag("span_type","root")# indicate that this is client spanspan.kind(az.CLIENT)# make timestamp and name it with START SQL queryspan.annotate("START SQL SELECT * FROM")# imitate long SQL queryawaitasyncio.sleep(0.1)# make other timestamp and name it "END SQL"span.annotate("END SQL")awaittracer.close()if__name__=="__main__":loop=asyncio.get_event_loop()loop.run_until_complete(run())aiohttp exampleaiozipkinincludesaiohttpserver instrumentation, for this createweb.Application()as usual and install aiozipkin plugin:importaiozipkinasazdefinit_app():host,port="127.0.0.1",8080app=web.Application()endpoint=az.create_endpoint("AIOHTTP_SERVER",ipv4=host,port=port)tracer=awaitaz.create(zipkin_address,endpoint,sample_rate=1.0)az.setup(app,tracer)That is it, plugin adds middleware that tries to fetch context from headers,
and create/join new trace. Optionally on client side you can add propagation
headers in order to force tracing and to see network latency between client and
server.importaiozipkinasazendpoint=az.create_endpoint("AIOHTTP_CLIENT")tracer=awaitaz.create(zipkin_address,endpoint)withtracer.new_trace()asspan:span.kind(az.CLIENT)headers=span.context.make_headers()host="http://127.0.0.1:8080/api/v1/posts/{}".format(i)resp=awaitsession.get(host,headers=headers)awaitresp.text()Documentationhttp://aiozipkin.readthedocs.io/InstallationInstallation process is simple, just:$ pip install aiozipkinSupport of other collectorsaiozipkincan work with any otherzipkincompatible service, currently we
tested it withjaegerandstackdriver.Jaeger supportjaegersupportszipkinspan format as result it is possible to useaiozipkinwithjaegerserver. You just need to specifyjaegerserver address and it
should work out of the box. Not need to run local zipkin server.
For more informations see tests andjaegerdocumentation.Stackdriver supportGooglestackdriversupportszipkinspan format as result it is possible to
useaiozipkinwith thisgoogleservice. In order to make this work you
need to setup zipkin service locally, that will send trace to the cloud. Seegooglecloud documentation how to setup make zipkin collector:RequirementsPython3.6+aiohttpCHANGES1.1.1 (2021-10-23)BugfixesFix unhandled AssertionError in aiohttp integration when unknown resource requested by the user.#400FixNoneTypeerror when usingSystemRoute.#4101.1.0 (2021-05-17)BugfixesExpect trace request context to be of SimpleNamespace type.#3851.0.0 (2020-11-06)BugfixesSupport Python 3.8 and Python 3.9#2590.7.1 (2020-09-20)BugfixesFixManifest.infile; addCHANGES.rstto the Source Tarball.0.7.0 (2020-07-17)FeaturesAdd support of AWS X-Ray trace id format.#2730.6.0 (2019-10-12)Add context var support for python3.7 aiohttp instrumentation #187Single header tracing support #189Add retries and batches to transport (thanks @konstantin-stepanov)Drop python3.5 support #238Use new typing syntax in codebase #2370.5.0 (2018-12-25)More strict typing configuration is used #147Fixed bunch of typos in code and docs #151 #153 (thanks @deejay1)Added interface for Transport #155 (thanks @deejay1)Added create_custom helper for easer tracer configuration #160 (thanks @deejay1)Added interface for Sampler #160 (thanks @deejay1)Added py.typed marker0.4.0 (2018-07-11)Add more coverage with typing #147Breaking change: typo send_inteval => send_interval #144 (thanks @gugu)Breaking change: do not append api/v2/spans to the zipkin dress #1500.3.0 (2018-06-13)Add support http.route tag for aiohttp #138Make zipkin address builder more permissive #141 (thanks @dsantosfff)0.2.0 (2018-03-03)Breaking change: az.create is coroutine now #114Added context manger for tracer object #114Added more mypy types #1170.1.1 (2018-01-26)Added new_child helper method #830.1.0 (2018-01-21)After few months of work and beta releases here are basic features:Initial release.Implemented zipkin v2 protocol with HTTP transportAdded jaeger supportAdded stackdriver supportAdded aiohttp server supportAdded aiohttp 3.0.0 client tracing supportAdded examples and demos |
aiozipstream | AioZipStreamThis is a fork ofZipStream. Simple python library for streaming ZIP files which are created dynamically, without using any temporary files.No temporary files, data is streamed directlySupporteddeflatecompression methodSmall memory usage, straming is realised using yield statementArchive structure is created on the fly, and all data can be created during streamFiles included into archive can be generated on the fly using Python generatorsAsynchronous AioZipStream and classic ZipStream are availableZip32 format compatible filesIndependent from python's standard ZipFile implementationAlmost no dependencies: onlyaiofilesin some circumstances (see AioZipStream section for details)Zip64 support is also planned in future (far future, because I never hitted 4GB file size limit ;-) )Required Python version:ZipStreamis compatible withPython 2.7.AioZipStreamrequirePython 3.6. For earlier versionsAioZipStreamis not available for import.Usage:List of files to archive is stored as list of dicts. Why dicts? Because there are possible additional parameters for each file, and more parameters are planned in future.Sample list of files to archive:files=[# file /tmp/file.dat will be added to archive under `file.dat` name.{'file':'/tmp/file.dat'},# same file as previous under own name: `completly_different.foo`# and will be compressed using `deflate` compression method{'file':'/tmp/file.dat','name':'completly_different.foo','compression':'deflate'}]It's time to stream / archive:zs=ZipStream(files)withopen("example.zip","wb")asfout:fordatainzs.stream():fout.write(data)Any iterable source of binary data can be used in place of regular files. Using generator as input for file must be represented bystreamfield instead offile, additionalnameparameter is also required.defsource_of_bytes():yieldb"123456789"yieldb"abcdefgh"yieldb"I am a binary data"files=[....# file will be generated dynamically under name my_data.bin{'stream':source_of_bytes(),'name':'my_data.bin'},]Keep in mind, that data should be served in chunks of reasonable size, because in case of using stream,ZipStreamclass is not able to split data by self.List of files to stream can be also generated on the fly, during streaming:importosfromzipstreamimportZipStreamdeffiles_to_stream_with_foo_in_name(dirname):# all files from selected firectoryforfinos.listdir(dirname):fp=os.path.join(dirname,f)ifos.path.isfile(fp):yield{'file':fp,'name':"foo_"+os.path.basename(fp)}# and our generator tooyield{'stream':source_of_bytes(),'name':'my_data.bin','compression':'deflate'}zs=ZipStream(files_to_stream_with_foo_in_name('\tmp\some-files'))Asynchronous AioZipStream:warning:To use asynchronous AioZipStream at least Python 3.6 version is required. AioZipStream is using asynchronous generator syntax, wchich is avilable from 3.6 version.To work with local files addtionalaiofileslibrary is required. If You plan to stream only dynamically generated content, thenaiofilesis not required.Seeaiofiles github repofor details aboutaiofiles.Sample of asynchronous zip streamingAny generator used to create data on the fly, must be defined asasync:asyncdefcontent_generator():yieldb'foo baz'asyncio.sleep(0.1)# we simulate little slow source of datadata=awaitremote_data_source()yieldbytes(data,'utf-8')# always remember to yield binary dataasyncio.sleep(0.5)yieldb"the end"Also zip streaming must be insideasyncfunction. Note usageaiofiles.openinstead ofopen, which is asynchronous and will not block event loop during disk access.fromzipstreamimportAioZipStreamasyncdefzip_async(zipname,files):aiozip=AioZipStream(files,chunksize=32768)asyncwithaiofiles.open(zipname,mode='wb')asz:asyncforchunkinaiozip.stream():awaitz.write(chunk)Here is going list of files to send:files=[{'file':'/tmp/car.jpeg'},{'file':'/tmp/aaa.mp3','name':'music.mp3'},{'stream':content_generator(),'name':'random_stuff.txt'}]Start asyncio loop and stream result to file:loop=asyncio.get_event_loop()loop.run_until_complete(zip_async('example.zip',files))loop.stop()ExamplesSeeexamplesdirectory for complete code and working examples of ZipStream and AioZipStream. |
aiozk | Asyncio zookeeper client (aiozk)Table of ContentsAsyncio zookeeper client (aiozk)StatusInstallationQuick ExampleRecipesCautionTestingRun testsTesting approachRecipes testingRun some tests directlyReferencesStatusHave no major bugs in client/session/connection, but recipes need more test
code to become more robust.Any help and interest are welcome 😀Installation$pipinstallaiozkQuick ExampleimportasynciofromaiozkimportZKClientasyncdefmain():zk=ZKClient('localhost')awaitzk.start()awaitzk.create('/foo',data=b'bazz',ephemeral=True)assertb'bazz'==awaitzk.get_data('/foo')awaitzk.close()asyncio.run(main())RecipesYou may use recipes, similar to zoonado, kazoo, and other libs:# assuming zk is aiozk.ZKClient# Lockasyncwithawaitzk.recipes.Lock('/path/to/lock').acquire():# ... Do some stuff ...pass# Barrierbarrier=zk.recipes.Barrier('/path/to/barrier)awaitbarrier.create()awaitbarrier.lift()awaitbarrier.wait()# DoubleBarrierdouble_barrier=zk.recipes.DoubleBarrier('/path/to/double/barrier',min_participants=4)awaitdouble_barrier.enter(timeout=0.5)# ... Do some stuff ...awaitdouble_barrier.leave(timeout=0.5)You can find full list of recipes provided by aiozk here:aiozk recipesTo understand ideas behind recipesplease read
thisandeven more
recipes here. Make sure
you're familiar with all recipes before doing something new by yourself,
especially when it involves more than few zookeeper calls.CautionDon't mix different type of recipes at the same znode path. For example,
creating a Lock and a DoubleBarrier object at the same path. It may cause
undefined behavior 😓TestingNB: please ensure that you're using recentdocker-composeversion. You can get it by runningpip install --user -U docker-composeRun tests# you should have access to docker
docker-compose build
./test-runner.shOr you can run tests with toxpip install --user tox tox-docker
toxTesting approachMost of tests are integration tests and running on real zookeeper instances.
We've chosenzookeeper 3.5version since it has an ability to dynamic reconfiguration and we're going to do all connecting/reconnecting/watches tests on zk docker cluster as this gives us the ability to restart any server and see what happens.# first terminal: launch zookeeper clusterdocker-composerm-fv&&docker-composebuildzk&&docker-composeup--scalezk=7zk_seedzk# it will launch cluster in this terminal and remain. last lines should be like this:zk_6|Servers:'server.1=172.23.0.9:2888:3888:participant;0.0.0.0:2181\nserver.2=172.23.0.2:2888:3888:participant;0.0.0.0:2181\nserver.3=172.23.0.3:2888:3888:participant;0.0.0.0:2181\nserver.4=172.23.0.4:2888:3888:participant;0.0.0.0:2181\nserver.5=172.23.0.5:2888:3888:participant;0.0.0.0:2181\nserver.6=172.23.0.7:2888:3888:participant;0.0.0.0:2181'zk_6|CONFIG:server.1=172.23.0.9:2888:3888:participant;0.0.0.0:2181
zk_6|server.2=172.23.0.2:2888:3888:participant;0.0.0.0:2181
zk_6|server.3=172.23.0.3:2888:3888:participant;0.0.0.0:2181
zk_6|server.4=172.23.0.4:2888:3888:participant;0.0.0.0:2181
zk_6|server.5=172.23.0.5:2888:3888:participant;0.0.0.0:2181
zk_6|server.6=172.23.0.7:2888:3888:participant;0.0.0.0:2181
zk_6|server.7=172.23.0.6:2888:3888:observer;0.0.0.0:2181
zk_6|zk_6|zk_6|Reconfiguring...
zk_6|ethernalloop
zk_7|Servers:'server.1=172.23.0.9:2888:3888:participant;0.0.0.0:2181\nserver.2=172.23.0.2:2888:3888:participant;0.0.0.0:2181\nserver.3=172.23.0.3:2888:3888:participant;0.0.0.0:2181\nserver.4=172.23.0.4:2888:3888:participant;0.0.0.0:2181\nserver.5=172.23.0.5:2888:3888:participant;0.0.0.0:2181\nserver.6=172.23.0.7:2888:3888:participant;0.0.0.0:2181\nserver.7=172.23.0.6:2888:3888:participant;0.0.0.0:2181'zk_7|CONFIG:server.1=172.23.0.9:2888:3888:participant;0.0.0.0:2181
zk_7|server.2=172.23.0.2:2888:3888:participant;0.0.0.0:2181
zk_7|server.3=172.23.0.3:2888:3888:participant;0.0.0.0:2181
zk_7|server.4=172.23.0.4:2888:3888:participant;0.0.0.0:2181
zk_7|server.5=172.23.0.5:2888:3888:participant;0.0.0.0:2181
zk_7|server.6=172.23.0.7:2888:3888:participant;0.0.0.0:2181
zk_7|server.7=172.23.0.6:2888:3888:participant;0.0.0.0:2181
zk_7|server.8=172.23.0.8:2888:3888:observer;0.0.0.0:2181
zk_7|zk_7|zk_7|Reconfiguring...
zk_7|ethernalloopRun tests in docker:docker-composerun--no-depsaiozk# last lines will be about testing results............lotoflinesommited........
.
----------------------------------------------------------------------
Ran3testsin1.059s
OKRun tests locally:# ZK_IP can be something from logs above, like: ZK_HOST=172.21.0.6:2181ZK_HOST=<ZK_IP>./venv/bin/pytestRecipes testingIt seems that usually recipes require several things to be tested:That recipe flow is working as expectedTimeouts: reproduce every timeout with meaningful values (timeout 0.5s and block for 0.6s)Run some tests directlyAnother way to run tests only which you are interested in quickly. Or this is
useful when you run tests under the other version of python.# Run zookeeper containerdockerrun-p2181:2181zookeeper# Run pytest directly at the development source treeexportZK_HOST=localhost
pytest-s--log-cli-level=DEBUGaiozk/test/test_barrier.pyReferencesIt is based onwglass/zoonadoimplementation |
aiozmq | asyncio (PEP 3156) support for ZeroMQ.The difference betweenaiozmqand vanillapyzmq(zmq.asyncio) is:zmq.asyncioworks only by replacing thebase event loopwith a custom one.
This approach works but has two disadvantages:zmq.asyncio.ZMQEventLoopcannot be combined with
other loop implementations (most notable is the ultra fastuvloop).It uses the internal ZMQ Poller which has fast ZMQ Sockets support
but isn’t intended to work fast with many (thousands) regular TCP sockets.In practice it means thatzmq.asynciois not recommended to be used with
web servers likeaiohttp.See alsohttps://github.com/zeromq/pyzmq/issues/894DocumentationSeehttp://aiozmq.readthedocs.orgSimple high-level client-server RPC example:importasyncioimportaiozmq.rpcclassServerHandler(aiozmq.rpc.AttrHandler):@aiozmq.rpc.methoddefremote_func(self,a:int,b:int)->int:returna+basyncdefgo():server=awaitaiozmq.rpc.serve_rpc(ServerHandler(),bind='tcp://127.0.0.1:5555')client=awaitaiozmq.rpc.connect_rpc(connect='tcp://127.0.0.1:5555')ret=awaitclient.call.remote_func(1,2)assert3==retserver.close()client.close()asyncio.run(go())Low-level request-reply example:importasyncioimportaiozmqimportzmqasyncdefgo():router=awaitaiozmq.create_zmq_stream(zmq.ROUTER,bind='tcp://127.0.0.1:*')addr=list(router.transport.bindings())[0]dealer=awaitaiozmq.create_zmq_stream(zmq.DEALER,connect=addr)foriinrange(10):msg=(b'data',b'ask',str(i).encode('utf-8'))dealer.write(msg)data=awaitrouter.read()router.write(data)answer=awaitdealer.read()print(answer)dealer.close()router.close()asyncio.run(go())Comparison to pyzmqzmq.asyncioprovides anasyncio compatible loopimplementation.But it’s based onzmq.Pollerwhich doesn’t work well with massive
non-zmq socket usage.E.g. if you build a web server for handling at least thousands of
parallel web requests (1000-5000)pyzmq’s internal poller will be slow.aiozmqworks with epoll natively, it doesn’t need a custom loop
implementation and cooperates pretty well withuvloopfor example.For details seehttps://github.com/zeromq/pyzmq/issues/894RequirementsPython3.6+pyzmq13.1+optional submoduleaiozmq.rpcrequiresmsgpack0.5+Licenseaiozmq is offered under the BSD license.CHANGES1.0.0 (2022-11-02)Support Python 3.9, 3.10, and 3.11 (thanks in part to Esben Sonne)Drop support for Python 3.5Remove support for using annotations as conversion functions0.9.0 (2020-01-25)Support Python 3.7 and 3.80.8.0 (2016-12-07)Respectevents_backlogparameter in zmq stream creation #860.7.1 (2015-09-20)Fix monitoring events implementationMake the library compatible with Python 3.50.7.0 (2015-07-31)Implement monitoring ZMQ events #50Do deeper lookup for inhereted classes #54Relax endpont check #56Implement monitoring events for stream api #520.6.1 (2015-05-19)Dynamically get list of pyzmq socket types0.6.0 (2015-02-14)Process asyncio specific exceptions as builtins.Add repr(exception) to rpc server call logs if anyAdd transport.get_write_buffer_limits() methodAdd __repr__ to transportAdd zmq_type to tr.get_extra_info()Add zmq streams0.5.2 (2014-10-09)Poll events after sending zmq message for eventless transport0.5.1 (2014-09-27)Fix loopless transport implementation.0.5.0 (2014-08-23)Support zmq devices in aiozmq.rpc.serve_rpc()Add loopless 0MQ transport0.4.1 (2014-07-03)Add exclude_log_exceptions parameter to rpc servers.0.4.0 (2014-05-28)Implement pause_reading/resume_reading methods in ZmqTransport.0.3.0 (2014-05-17)Add limited support for Windows.Fix unstable test execution, change ZmqEventLoop to use global
shared zmq.Context by default.Process cancellation on rpc servers and clients.0.2.0 (2014-04-18)msg in msg_received now is a list, not tupleAllow to send empty msg by trsansport.write()Add benchmarksDerive ServiceClosedError from aiozmq.rpc.Error, not ExceptionImplement logging from remote calls at server side (log_exceptions parameter).Optimize byte counting in ZmqTransport.0.1.3 (2014-04-10)Function default values are not passed to an annotaion.
Add check for libzmq version (should be >= 3.0)0.1.2 (2014-04-01)Function default values are not passed to an annotaion.0.1.1 (2014-03-31)Rename plural module names to single ones.0.1.0 (2014-03-30)Implement ZmqEventLoop withcreate_zmq_connectionmethod which operates
on zmq transport and protocol.Implement ZmqEventLoopPolicy.Introduce ZmqTransport and ZmqProtocol.Implement zmq.rpc with RPC, PUSHPULL and PUBSUB protocols. |
aiozmq-heartbeat | UNKNOWN |
aio-zmq-rpc | No description available on PyPI. |
aiozoom | AIOZOOMAiozoom is an async python library for interaction with Zoom APIRequirementsPython 3.9pipInstallationUnder console using pipIn the console, run the following command:pipinstall--upgradeaiozoomQuick startImport modulefromaiozoomimportZoomConfigure a ClientfromaiozoomimportZoomZoom.configure('JWT_TOKEN')Create a meetingimportasynciofromaiozoomimportZoomZoom.configure('JWT_TOKEN')asyncdefmain():zoom=Zoom()awaitzoom.create_meeting('[email protected]',{'title':'test'})loop=asyncio.get_event_loop()task=loop.create_task(main())loop.run_until_complete(task)loop.close()Available methods:create_meeting(email, body)get_meeting(meeting_id)stop_meeting(meeting_id)delete_meeting(meeting_id)update_meeting(meeting_id, body)get_meeting_participants(meeting_id)get_meeting_info(meeting_id)and more...Docs will be available soon... |
aiozyre | aiozyreasyncio-friendly Python bindings forZyre, an open-source framework for proximity-based peer-to-peer applications.InstallationpipinstallaiozyreTests run on both Linux and macOS for the following Python versions:CPython: 3.6.4, 3.7.0, 3.8.0PyPy: 7.2.0 (3.6.9)CPython 3.6.3 and lower are not supported due tothis bug.UsageSee theexample peer-to-peer chat client.ContributingPull requests are welcome, please file any issues you encounter.Changelogv1.1.5 (2020-07-22)Fix memory leak where zlist items were not being freedFix egg installation issue by passing zip_safe=Falsev1.1.4 (2020-05-23)HandleSILENTmessage |
aipack | AI Package본 패키지는 AI Package로써 딥러닝관련한 여러가지 유틸기능들을 포함합니다.자세한 사용법은 Git 페이지를 확인해주세요. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.