package
stringlengths 1
122
| pacakge-description
stringlengths 0
1.3M
|
---|---|
aioairzone | aioairzonePython library to control Airzone devices.RequirementsPython >= 3.11InstallpipinstallaioairzoneInstall from SourceRun the following command inside this folderpipinstall--upgrade.ExamplesExamples can be found in theexamplesfolderAPI Call examplesRun the following command to list all your Airzone Zones:curl -s --location --request POST "http://192.168.1.25:3000/api/v1/hvac" -d '{"systemID": 0, "zoneID": 0}' | jqRun the following command to list all your Airzone Systems:curl -s --location --request POST "http://192.168.1.25:3000/api/v1/hvac" -d '{"systemID": 127}' | jqRun the following command to fetch your Airzone Altherma parameters:curl -s --location --request POST "http://192.168.1.25:3000/api/v1/hvac" -d '{"systemID": 0}' | jqRun the following command to fetch your Airzone WebServer parameters:curl -s --location --request POST "http://192.168.1.25:3000/api/v1/webserver" | jqRun the following command to fetch a demo Airzone Zone:curl -s --location --request POST "http://192.168.1.25:3000/api/v1/demo" | jqRun the following command to fetch your Airzone LocalAPI version:curl -s --location --request POST "http://192.168.1.25:3000/api/v1/version" | jqRun the following command to fetch your Airzone LocalAPI integration driver:curl -s --location --request POST "http://192.168.1.25:3000/api/v1/integration" -d '{}' | jq |
aioairzone-cloud | aioairzone-cloudPython library to control Airzone Cloud devices.RequirementsPython >= 3.11Installpipinstallaioairzone-cloudInstall from SourceRun the following command inside this folderpipinstall--upgrade.ExamplesExamples can be found in theexamplesfolder |
aio-alf | aio-alf |build-status|===========aiohttp OAuth 2 Client---------------------`aio-alf` is a OAuth 2 Client base on the aiohttp's AsyncHTTPClientFeatures--------* Automatic token retrieving and renewing* Token expiration control* Automatic retry on status 401 (UNAUTHORIZED)Usage-----Initialize the client and use it as a AsyncHTTPClient object... code-block:: pythonfrom aioalf.client import Clientfrom aioalf.httpclient import HTTPRequestclient = Client(token_endpoint='http://example.com/token',client_id='client-id',client_secret='secret')resource_uri = 'http://example.com/resource'response = await client.request('POST',resource_uri,data='{"name": "alf"}',headers={'Content-Type': 'application/json'})Alternatively one can pass directly a string to the fetch client.. code-block:: python# ...response = await client.request('POST','http://example.com/resource',data='{"name": "alf"}',headers={'Content-Type': 'application/json'})Implicit Flow-------------Support for OAuth2 implict flow to enable it, call `use_implicit_flow` with a `TokenStorage`object and a port range, it defaults to the range (32000, 32009).Example:.. code-block:: pythonawait use_implicit_flow(TokenStorage(), (30000, 30009))async with Client(token_endpoint='https://token.endpoint',client_id='glBQ3nYU/8/kaVi/bIgXGA==',client_secret='') as client:response = await client.request('GET', 'http://example.com/resource')text = await response.text()print(response.status)The library has a really simple in memory token storage, you should subclass and overwriteits methods if you need to persist the token for a longer period.How it works?-------------Before any request the client tries to retrieve a token on the endpoint,expecting a JSON response with the ``access_token`` and ``expires_in`` keys.The client keeps the token until it is expired, according to the ``expires_in``value.After getting the token, the request is issued with a `Bearer authorizationheader <http://tools.ietf.org/html/draft-ietf-oauth-v2-31#section-7.1>`_:.. code-block::GET /resource/1 HTTP/1.1Host: example.comAuthorization: Bearer tokenIf the request fails with a 401 (UNAUTHORIZED) status, a new token is retrievedfrom the endpoint and the request is retried. This happens only once, if itfails again the error response is returned.Troubleshooting---------------In case of an error retrieving a token, the error response will be returned,the real request won't happen.Related projects----------------This project tries to be an adaptation to aiohttp of`alf <https://github.com/globocom/alf>`_.. |build-status| image:: https://secure.travis-ci.org/globocom/aio-alf.png?branch=master:target: https://travis-ci.org/globocom/aio-alf |
aioalfacrm | AIOAlfacrmaioalfacrm- is an asynchronous implementation for theAlfaCRM APIPackage is in developmentInstallation using pip$ pip install aioalfacrmExample:importasynciofromaioalfacrmimportAlfaClientfromaioalfacrm.entitiesimportLocationHOSTNAME='demo.s20.online'EMAIL='[email protected]'API_KEY='user-api-token'BRANCH_ID=1asyncdefmain():alfa_client=AlfaClient(hostname=HOSTNAME,email=EMAIL,api_key=API_KEY,branch_id=BRANCH_ID,)try:# Check auth (Optionaly)ifnotawaitalfa_client.check_auth():print('Authentification error')return# Get branchesbranches=awaitalfa_client.branch.list(page=0,count=20)# Edit branchforbranchinbranches:branch.name=f'{branch.name}- Edited'# Save branchawaitalfa_client.branch.save(branch)# Create locationlocation=Location(branch_id=1,is_active=True,name='New location',)awaitalfa_client.location.save(location)finally:# Close sessionawaitalfa_client.close()asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())# For Windowsasyncio.run(main())Paginator# Get all entitiesforpageinalfa_client.<object>.get_paginator():objects=page.itemsCustom fieldsTo work with custom fields, do the followingfromaioalfacrmimportentitiesfromaioalfacrmimportfieldsfromtypingimportOptional# Extend existing modelclassCustomCustomer(entities.Customer):custom_field:Optional[int]=fields.Integer()# For IDE init supportdef__init__(self,custom_field:Optional[int]=None,*args,**kwargs,):super(CustomCustomer,self).__init__(custom_field=custom_field,*args,**kwargs)# Create custom alfa client with new modelfromaioalfacrmimportAlfaClientfromaioalfacrmimportmanagersclassCustomAlfaClient(AlfaClient):def__init__(self,*args,**kwargs):super(CustomAlfaClient,self).__init__(*args,**kwargs)self.customer=managers.Customer(api_client=self.api_client,entity_class=CustomCustomer,)# Create custom alfa clientimportasyncioHOSTNAME='demo.s20.online'EMAIL='[email protected]'API_KEY='user-api-token'BRANCH_ID=1asyncdefmain():alfa_client=CustomAlfaClient(hostname=HOSTNAME,email=EMAIL,api_key=API_KEY,branch_id=BRANCH_ID)try:customers=awaitalfa_client.customer.list()forcustomerincustomers:print(customer.custom_field)finally:awaitalfa_client.close()asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())# For Windowsasyncio.run(main()) |
aioAlice | aioAliceAsyncIO library for Yandex Alice (Yandex Dialogs)Why?Work with classes, don't bother parsing JSONAuto answer to webhook even if you were not fast enough to create answer - there won't be a server error, but you'll get a logAuto response will not help if you are not using async IO. So consider not to use any long processing synchronous tasks inside handlersHandy handlers to match incoming commandsFinite-State MachineEasy images upload, easy answers generationInstallation# make sure you use virtual env and python 3.6+:python3.6-mvenvaliceenvsource./aliceenv/bin/activate
pipinstallpip-U
pipinstallsetuptools-U
pipinstalluvloop# uvloop if you wantpipinstallaioalice-U# Or install from GitHub:# pip install git+https://github.com/surik00/aioalice.git -U# or if you don't have git installed:# 1. download ZIP# 2. unarchive and go to dir# 3. run:pythonsetup.pyinstallQuick startHello alicedp=Dispatcher()@dp.request_handler()asyncdefhandle_all_requests(alice_request):returnalice_request.response('Hello world!')CardsAll examplesUpload image exampleBig Image Card exampleItems List Card exampleJSON serializingIf you want to use a faster json library, installrapidjsonorujson, it will be detected and used automaticallySkills using aioAliceThe Erundopel gameTesting and deploymentIn all examples the next configuration is used:WEBHOOK_URL_PATH='/my-alice-webhook/'# webhook endpointWEBAPP_HOST='localhost'# running on local machineWEBAPP_PORT=3001# we can use any port that is not use by other appsFor testing purposes you can usengrok, so set webhook tohttps://1a2b3c4d5e.ngrok.io/my-alice-webhook/(endpoint has to beWEBHOOK_URL_PATH, because WebApp expects to get updates only there), post has to beWEBAPP_PORT(in this example it is 3001)For production you can use Nginx, then edit Nginx configuration and add these lines inside theserverblock:location /my-alice-webhook/ { # WEBHOOK_URL_PATH
proxy_pass http://127.0.0.1:3001/; # addr to reach WebApp, in this case it is localhost and port is 3001
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
} |
aio-alipay-sdk-python | 在官方SDK的基础上,支持异步请求,仅重写了发起请求的方法The official Alipay SDK for Python.访问蚂蚁金服开放平台的官方SDK。LinksWebsite:https://open.alipay.com(官方)Website:https://github.com/Pig-Tong/aio-alipay-sdk-pythonIssues不管您在使用SDK的过程中遇到任何问题,欢迎前往支付宝开放社区发帖与支付宝工作人员和其他开发者一起交流。注:为了提高开发者问题的响应时效,github本身的issue功能已关闭,支付宝开放社区中发帖的问题,通常会在2小时内响应。Installationpip3 installaio-alipay-sdk-pythonExample#!/usr/bin/env python# -*- coding: utf-8 -*-importloggingimporttracebackfromalipay.aop.api.AlipayClientConfigimportAlipayClientConfigfromalipay.aop.api.DefaultAlipayClientimportDefaultAlipayClientfromalipay.aop.api.FileItemimportFileItemfromalipay.aop.api.domain.AlipayTradeAppPayModelimportAlipayTradeAppPayModelfromalipay.aop.api.domain.AlipayTradePagePayModelimportAlipayTradePagePayModelfromalipay.aop.api.domain.AlipayTradePayModelimportAlipayTradePayModelfromalipay.aop.api.domain.GoodsDetailimportGoodsDetailfromalipay.aop.api.domain.SettleDetailInfoimportSettleDetailInfofromalipay.aop.api.domain.SettleInfoimportSettleInfofromalipay.aop.api.domain.SubMerchantimportSubMerchantfromalipay.aop.api.request.AlipayOfflineMaterialImageUploadRequestimportAlipayOfflineMaterialImageUploadRequestfromalipay.aop.api.request.AlipayTradeAppPayRequestimportAlipayTradeAppPayRequestfromalipay.aop.api.request.AlipayTradePagePayRequestimportAlipayTradePagePayRequestfromalipay.aop.api.request.AlipayTradePayRequestimportAlipayTradePayRequestfromalipay.aop.api.response.AlipayOfflineMaterialImageUploadResponseimportAlipayOfflineMaterialImageUploadResponsefromalipay.aop.api.response.AlipayTradePayResponseimportAlipayTradePayResponsefromaio_alipay.AioAlipayClientimportAioAlipayClientlogging.basicConfig(level=logging.INFO,format='%(asctime)s%(levelname)s%(message)s',filemode='a',)logger=logging.getLogger('')if__name__=='__main__':"""
设置配置,包括支付宝网关地址、app_id、应用私钥、支付宝公钥等,其他配置值可以查看AlipayClientConfig的定义。
"""alipay_client_config=AlipayClientConfig()alipay_client_config.server_url='https://openapi.alipay.com/gateway.do'alipay_client_config.app_id='[your app_id]'alipay_client_config.app_private_key='[your app private key]'alipay_client_config.alipay_public_key='[alipay public key]'"""
得到客户端对象。
注意,一个alipay_client_config对象对应一个DefaultAlipayClient,定义DefaultAlipayClient对象后,alipay_client_config不得修改,如果想使用不同的配置,请定义不同的DefaultAlipayClient。
logger参数用于打印日志,不传则不打印,建议传递。
"""client=AioAlipayClient(alipay_client_config=alipay_client_config,logger=logger)"""
系统接口示例:alipay.trade.pay
"""# 对照接口文档,构造请求对象model=AlipayTradePayModel()model.auth_code="282877775259787048"model.body="Iphone6 16G"goods_list=list()goods1=GoodsDetail()goods1.goods_id="apple-01"goods1.goods_name="ipad"goods1.price=10goods1.quantity=1goods_list.append(goods1)model.goods_detail=goods_listmodel.operator_id="yx_001"model.out_trade_no="20180510AB014"model.product_code="FACE_TO_FACE_PAYMENT"model.scene="bar_code"model.store_id=""model.subject="huabeitest"model.timeout_express="90m"model.total_amount=1request=AlipayTradePayRequest(biz_model=model)# 如果有auth_token、app_auth_token等其他公共参数,放在udf_params中# udf_params = dict()# from alipay.aop.api.constant.ParamConstants import *# udf_params[P_APP_AUTH_TOKEN] = "xxxxxxx"# request.udf_params = udf_params# 执行请求,执行过程中如果发生异常,会抛出,请打印异常栈response_content=Nonetry:response_content=awaitclient.execute(request)exceptExceptionase:print(traceback.format_exc())ifnotresponse_content:print("failed execute")else:response=AlipayTradePayResponse()# 解析响应结果response.parse_response_content(response_content)print(response.body)ifresponse.is_success():# 如果业务成功,则通过respnse属性获取需要的值print("get response trade_no:"+response.trade_no)else:# 如果业务失败,则从错误码中可以得知错误情况,具体错误码信息可以查看接口文档print(response.code+","+response.msg+","+response.sub_code+","+response.sub_msg)"""
带文件的系统接口示例:alipay.offline.material.image.upload
"""# 如果没有找到对应Model类,则直接使用Request类,属性在Request类中request=AlipayOfflineMaterialImageUploadRequest()request.image_name="我的店"request.image_type="jpg"# 设置文件参数f=open("/Users/foo/Downloads/IMG.jpg","rb")request.image_content=FileItem(file_name="IMG.jpg",file_content=f.read())f.close()response_content=Nonetry:response_content=awaitclient.execute(request)exceptExceptionase:print(traceback.format_exc())ifnotresponse_content:print("failed execute")else:response=AlipayOfflineMaterialImageUploadResponse()response.parse_response_content(response_content)ifresponse.is_success():print("get response image_url:"+response.image_url)else:print(response.code+","+response.msg+","+response.sub_code+","+response.sub_msg)"""
页面接口示例:alipay.trade.page.pay
"""# 对照接口文档,构造请求对象model=AlipayTradePagePayModel()model.out_trade_no="pay201805020000226"model.total_amount=50model.subject="测试"model.body="支付宝测试"model.product_code="FAST_INSTANT_TRADE_PAY"settle_detail_info=SettleDetailInfo()settle_detail_info.amount=50settle_detail_info.trans_in_type="userId"settle_detail_info.trans_in="2088302300165604"settle_detail_infos=list()settle_detail_infos.append(settle_detail_info)settle_info=SettleInfo()settle_info.settle_detail_infos=settle_detail_infosmodel.settle_info=settle_infosub_merchant=SubMerchant()sub_merchant.merchant_id="2088301300153242"model.sub_merchant=sub_merchantrequest=AlipayTradePagePayRequest(biz_model=model)# 得到构造的请求,如果http_method是GET,则是一个带完成请求参数的url,如果http_method是POST,则是一段HTML表单片段response=client.page_execute(request,http_method="GET")print("alipay.trade.page.pay response:"+response)"""
构造唤起支付宝客户端支付时传递的请求串示例:alipay.trade.app.pay
"""model=AlipayTradeAppPayModel()model.timeout_express="90m"model.total_amount="9.00"model.seller_id="2088301194649043"model.product_code="QUICK_MSECURITY_PAY"model.body="Iphone6 16G"model.subject="iphone"model.out_trade_no="201800000001201"request=AlipayTradeAppPayRequest(biz_model=model)response=client.sdk_execute(request)print("alipay.trade.app.pay response:"+response) |
aioambient | 🌤 aioambient: An async library for Ambient Weather Personal Weather Stationsaioambientis a Python3, asyncio-driven library that interfaces with both the REST and
Websocket APIs provided byAmbient Weather.InstallationPython VersionsAPI and Application KeysUsageContributingInstallationpipinstallaioambientPython Versionsaioambientis currently supported on:Python 3.10Python 3.11Python 3.12API and Application KeysUtilizingaioambientrequires both an Application Key and an API Key from Ambient
Weather. You can generate both from the Profile page in yourAmbient Weather Dashboard.UsageREST APIimportasynciofromdatetimeimportdatefromaiohttpimportClientSessionfromaioambientimportAPIasyncdefmain()->None:"""Create the aiohttp session and run the example."""api=API("<YOUR APPLICATION KEY>","<YOUR API KEY>")# Get all devices in an account:awaitapi.get_devices()# Get all stored readings from a device:awaitapi.get_device_details("<DEVICE MAC ADDRESS>")# Get all stored readings from a device (starting at a datetime):awaitapi.get_device_details("<DEVICE MAC ADDRESS>",end_date=date(2019,1,16))asyncio.run(main())By default, the library creates a new connection to Ambient Weather 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:importasynciofromdatetimeimportdatefromaiohttpimportClientSessionfromaioambientimportAPIasyncdefmain()->None:"""Create the aiohttp session and run the example."""asyncwithClientSession()assession:api=API("<YOUR APPLICATION KEY>","<YOUR API KEY>")# Get all devices in an account:awaitapi.get_devices()# Get all stored readings from a device:awaitapi.get_device_details("<DEVICE MAC ADDRESS>")# Get all stored readings from a device (starting at a datetime):awaitapi.get_device_details("<DEVICE MAC ADDRESS>",end_date=date(2019,1,16))asyncio.run(main())Please be aware of Ambient Weather'srate limiting policies.Websocket APIimportasynciofromaiohttpimportClientSessionfromaioambientimportWebsocketasyncdefmain()->None:"""Create the aiohttp session and run the example."""websocket=Websocket("<YOUR APPLICATION KEY>","<YOUR API KEY>")# Note that you can watch multiple API keys at once:websocket=Websocket("YOUR APPLICATION KEY",["<API KEY 1>","<API KEY 2>"])# Define a method that should be fired when the websocket client# connects:defconnect_method():"""Print a simple "hello" message."""print("Client has connected to the websocket")websocket.on_connect(connect_method)# Alternatively, define a coroutine handler:asyncdefconnect_coroutine():"""Waits for 3 seconds, then print a simple "hello" message."""awaitasyncio.sleep(3)print("Client has connected to the websocket")websocket.async_on_connect(connect_coroutine)# Define a method that should be run upon subscribing to the Ambient# Weather cloud:defsubscribed_method(data):"""Print the data received upon subscribing."""print(f"Subscription data received:{data}")websocket.on_subscribed(subscribed_method)# Alternatively, define a coroutine handler:asyncdefsubscribed_coroutine(data):"""Waits for 3 seconds, then print the incoming data."""awaitasyncio.sleep(3)print(f"Subscription data received:{data}")websocket.async_on_subscribed(subscribed_coroutine)# Define a method that should be run upon receiving data:defdata_method(data):"""Print the data received."""print(f"Data received:{data}")websocket.on_data(data_method)# Alternatively, define a coroutine handler:asyncdefdata_coroutine(data):"""Wait for 3 seconds, then print the data received."""awaitasyncio.sleep(3)print(f"Data received:{data}")websocket.async_on_data(data_coroutine)# Define a method that should be run when the websocket client# disconnects:defdisconnect_method(data):"""Print a simple "goodbye" message."""print("Client has disconnected from the websocket")websocket.on_disconnect(disconnect_method)# Alternatively, define a coroutine handler:asyncdefdisconnect_coroutine(data):"""Wait for 3 seconds, then print a simple "goodbye" message."""awaitasyncio.sleep(3)print("Client has disconnected from the websocket")websocket.async_on_disconnect(disconnect_coroutine)# Connect to the websocket:awaitwebsocket.connect()# At any point, disconnect from the websocket:awaitwebsocket.disconnect()asyncio.run(main())Open REST APIThe official REST API and Websocket API require an API and application key to access
data for the devices you own. This API cannot be used if you do not own a personal
weather station.However, there is a second, undocumented API that is used by thehttps://ambientweather.netweb application that does not require an API and application key. You can use theOpenAPIclass to retrieve weather station data from this API:importasynciofromdatetimeimportdatefromaiohttpimportClientSessionfromaioambientimportOpenAPIasyncdefmain()->None:"""Create the aiohttp session and run the example."""api=OpenAPI()# Get a list of all the devices that are located within a radius of# three miles from the given latitude/longitude. Each device lists its# MAC address.awaitapi.get_devices_by_location(32.5,-97.3,3.0)# Get the current data from a device:awaitapi.get_device_details("<DEVICE MAC ADDRESS>")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 aioambient testsUpdateREADME.mdwith any new documentation.Submit a pull request! |
aioamqp | aioamqplibrary is a pure-Python implementation of theAMQP 0.9.1 protocol.Built on top on Python’s asynchronous I/O support introduced inPEP 3156, it provides an API based on coroutines, making it easy to write highly concurrent applications.Bug reports, patches and suggestions welcome! Just open anissueor send apull request.testsTo run the tests, you’ll need to install the Python test dependencies:pip install -r requirements_dev.txtTests require an instance of RabbitMQ. You can start a new instance using docker:docker run -d --log-driver=syslog -e RABBITMQ_NODENAME=my-rabbit --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3-managementThen you can run the tests withmake test.tests using docker-composeStart RabbitMQ usingdocker-composeup-drabbitmq. When RabbitMQ has started, start the tests usingdocker-composeup--buildaioamqp-test |
aio-amqp | AboutAsynchronous AMQP client for 0.9.1 protocol versionInstallationRecommended way (via pip):$pipinstallaio-amqpLicenseCopyright 2020 Not Just A Toy Corp.Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License athttp://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. |
aioamqp-authentise | aioamqplibrary is a pure-Python implementation of theAMQP 0.9.1 protocol.Built on top on Python’s asynchronous I/O support introduced inPEP 3156, it provides an API based on coroutines, making it easy to write highly concurrent applications.Bug reports, patches and suggestions welcome! Just open anissueor send apull request.testsTo run the tests, you’ll need to install the Python test dependencies:pip install -r requirements_dev.txtTests require an instance of RabbitMQ. You can start a new instance using docker:docker run -d --log-driver=syslog -e RABBITMQ_NODENAME=my-rabbit --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3-managementThen you can run the tests withmake test(requiresnose). |
aioamqp-beta | No description available on PyPI. |
aioamqp_consumer | info:consumer/producer/rpc library built over aioamqpInstallationpipinstallaioamqp_consumerConsumer/Producer usageimportasynciofromaioamqp_consumerimportConsumer,Producerasyncdeftask(payload,properties):awaitasyncio.sleep(1)print(payload)asyncdefmain():amqp_url='amqp://guest:[email protected]:5672//'amqp_queue='your-queue-here'queue_kwargs={'durable':True,}# https://aioamqp.readthedocs.io/en/latest/api.html#aioamqp.connectamqp_kwargs={}asyncwithProducer(amqp_url,amqp_kwargs=amqp_kwargs)asproducer:for_inrange(5):awaitproducer.publish(b'hello',amqp_queue,queue_kwargs=queue_kwargs,)consumer=Consumer(amqp_url,task,amqp_queue,queue_kwargs=queue_kwargs,amqp_kwargs=amqp_kwargs,)awaitconsumer.scale(20)# scale up to 20 background coroutinesawaitconsumer.scale(5)# downscale to 5 background coroutines# wait for rabbitmq queue is empty and all local messages are processedawaitconsumer.join()consumer.close()awaitconsumer.wait_closed()loop=asyncio.get_event_loop()loop.run_until_complete(main())loop.close()RPC usageimportasynciofromaioamqp_consumerimportRpcClient,RpcServer,rpcpayload=b'test'@rpc(queue_name='random_queue')asyncdefmethod(payload):print(payload)returnpayloadasyncdefmain():amqp_url='amqp://guest:[email protected]:5672//'server=RpcServer(amqp_url,method=method)client=RpcClient(amqp_url)ret=awaitclient.wait(method(payload))assertret==payloadawaitclient.close()awaitserver.stop()loop=asyncio.get_event_loop()loop.run_until_complete(main())loop.close()For built-in json encoding/decoding, take a look onaioamqp_consumer.json_rpcFor production deployingaioamqp_consumer.Consumer/aioamqp_consumer.RpcServerthere is built-in simpler runner:fromaioamqp_consumerimportRpcServer,json_rpcamqp_url='amqp://guest:[email protected]:5672//'@json_rpc(queue_name='random_queue')asyncdefsquare(*,x):ret=x**2print(x,ret)returnretif__name__=='__main__':RpcServer(amqp_url,method=square).run()ThanksThe library was donated byOcean S.A.Thanks to the company for contribution. |
aioamqp-consumer-best | aioamqp-consumer-bestUsageimportasynciofromtypingimportListfromaioamqp_consumer_bestimport(ConnectionParams,Consumer,Exchange,Message,ProcessBulk,Queue,QueueBinding,ToBulks,load_json,)asyncdefcallback(messages:List[Message])->None:print(messages)consumer=Consumer(middleware=(load_json|ToBulks(max_bulk_size=10,bulk_timeout=3.0)|ProcessBulk(callback)),prefetch_count=10,queue=Queue(name='test-queue',bindings=[QueueBinding(exchange=Exchange('test-exchange'),routing_key='test-routing-key',),],),connection_params=[# Round robinConnectionParams(),ConnectionParams.from_string('amqp://user@rmq-host:5672/'),],)asyncio.run(consumer.start()) |
aioamqp-ext | # Asynchronous AMQP base Consumer and Producer.AMQP Consumer and Producer base classes. Working on top of `aioamqp`.## UsageProducer:from aioamqp_ext import BaseProducerproducer = BaseProducer(**{'url': 'amqp://localhost:5672/','exchange': 'my_exchange'})producer.publish_message(payload='foo',routing_key='bar')producer.close()Consumer:from aioamqp_ext import BaseConsumerclass Consumer(BaseConsumer):async def process_request(self, data):print(data)if __name__ == "__main__":consumer = Consumer(**{'url': 'amqp://localhost:5672/','exchange': 'my_exchange','queue': 'my_queue','routing_key': 'foo.bar'})try:loop = asyncio.get_event_loop()loop.run_until_complete(consumer.consume())loop.run_forever()except KeyboardInterrupt:loop.run_until_complete(consumer.close())finally:loop.close()## TestsTo run the tests, you'll need to install the Python test dependencies::pip install -r ./requirements-ci.txtThen you can run the tests with `make unit-test `. |
aio-androidtv | Documentation for this package can be found athttps://aio-androidtv.readthedocs.io.aio-androidtvis a Python 3.7+ package that provides state information and control of Android TV and Fire TV devices via ADB.InstallationBe sure you install into a Python 3.7+ environment.pipinstallaio-androidtvADB Intents and CommandsA collection of useful intents and commands can be foundhere(credit: mcfrojd).AcknowledgmentsThis is based onpython-firetvby happyleavesaoc and theandroidtv component for Home Assistantby a1ex4, and it depends on the Python packageaio-adb-shell(which is based onpython-adb). |
aioanixart | ok |
aio_anticaptcha | API documentationhttps://anti-captcha.com/apidochttp://antigate.com/?action=api#algoInstallationYou can install it using Pip:pip install aio_anticaptchaIf you want the latest development version, you can install it from source:git clone [email protected]:nibrag/aio_anticaptcha.git
cd aio_anticaptcha
python setup.py installRequirements:python 3.4+
aiohttpUsageWith context managerimportasynciofromaio_anticaptchaimportAntiCaptcha,ServiceErrorasyncdefrun(loop):try:withAntiCaptcha('API-KEY',loop=loop)asac:# io.IOBasefh=open('captcha.jpg')resolved,captcha_id=awaitac.resolve(fh)# or bytes, bytearraybytes_buff=open('captcha.jpg','rb').read()resolved,captcha_id=awaitac.resolved(bytes_buff)exceptZeroBalanceError:print('Zero balance')exceptUserKeyError:print('Invalid api key...')exceptServiceErrorase:print('Something else',str(e))if__name__=='__main__':loop=asyncio.get_event_loop()loop.run_until_complete(run(loop))loop.close()Without context managerimportasynciofromaio_anticaptchaimportAntiCaptcha,ServiceErrorasyncdefrun(loop):ac=AntiCaptcha('API-KEY',loop=loop)try:# io.IOBaseresolved,captcha_id=awaitac.resolve(open('captcha.jpg'))# or bytes, bytearraybytes_buff=open('captcha.jpg','rb').read()resolved,captcha_id=awaitac.resolved(bytes_buff)exceptServiceErrorase:print(e)finally:# do'nt forget call close methodac.close()if__name__=='__main__':loop=asyncio.get_event_loop()loop.run_until_complete(run(loop))loop.close()If you wish to complain about a mismatch results, useabusemethod:importasynciofromaio_anticaptchaimportAntiCaptchaasyncdefrun(loop):withAntiCaptcha('API-KEY',loop=loop)asac:resolved,captcha_id=awaitac.resolve(open('captcha.jpg'))awaitac.abuse(captcha_id)if__name__=='__main__':loop=asyncio.get_event_loop()loop.run_until_complete(run(loop))loop.close()After all manipulations, you can get your account balance:importasynciofromaio_anticaptchaimportAntiCaptchaasyncdefrun(loop):withAntiCaptcha('API-KEY',loop=loop)asac:balance=awaitac.get_balance()if__name__=='__main__':loop=asyncio.get_event_loop()loop.run_until_complete(run(loop))loop.close()Additional options for sending Captcha:Read documentation about all available options:https://anti-captcha.com/apidocimportasynciofromaio_anticaptchaimportAntiCaptchaasyncdefrun(loop):withAntiCaptcha('API-KEY',loop=loop)asac:resolved,captcha_id=awaitac.resolve(open('captcha.jpg'),max_len=5,is_russian=True)if__name__=='__main__':loop=asyncio.get_event_loop()loop.run_until_complete(run(loop))loop.close()Customizing anticaptcha serviceimportasynciofromaio_anticaptchaimportAntiCaptchaasyncdefrun(loop):withAntiCaptcha('API-KEY',loop=loop,domain='antigate.com',port=80)asac:balance=awaitac.get_balance()if__name__=='__main__':loop=asyncio.get_event_loop()loop.run_until_complete(run(loop))loop.close()AntiGate.com supportedimportasynciofromaio_anticaptchaimportAntiGateasyncdefrun(loop):withAntiGate('API-KEY',loop=loop)asag:balance=awaitag.get_balance()if__name__=='__main__':loop=asyncio.get_event_loop()loop.run_until_complete(run(loop))loop.close() |
aioantipublic | No description available on PyPI. |
aioapcaccess | aioapcaccessAn async implementation ofapcaccess. This
library provides programmatic access to the status information provided byapcupsdover its Network Information Server (NIS) which
usually listens on TCP port 3551.This project is a re-implementation of the synchronous versionflyte/apcaccessusingasyncio, where a lot of the logic is
borrowed and improved.InstallInstall with pip:$ pip install aioapcaccessUsageThe primary API for getting the status from APCUPS isaioapcaccess.request_status.
It returns acollections.OrderedDictmapping from field names (e.g., "SERIALNO") to
their values in string format. What fields are available will depend on the model of
your APC UPS, seeAPCUPSD manualfor details.The following example shows a typical usage ofaioapcaccessimportasyncioimportaioapcaccessasyncdefmain():result=awaitaioapcaccess.request_status(host='localhost',port=3551)print(result)if__name__=='__main__':asyncio.run(main())The example above will print the following (prettified and simplified):OrderedDict([
('APC', '001,036,0879'),
...,
('BATTV', '13.7 Volts'),
('CUMONBATT', '0 Seconds')
))])In addition torequest_status, we offer the following functions for advanced uses:aioapcaccess.request_raw_statusfor getting raw (unparsed) status inbytes.aioapcaccess.parse_raw_statusfor parsing thebytesto the dict shown above.aioapcaccess.split_unitfor splitting the supported unit suffix from the value
strings, returning a tuple(value, unit). You can checkaioapcaccess.UNITSfor
the set of supported units. Note that units are also in the forms of strings
(e.g., "Seconds", "Volts"). If no valid units are found in the value strings,unitwill beNone. |
aioapi | aioapiYet another way to build APIs usingAIOHTTPframework.Followdocumentationto know what you can do withAIOAPI.Installation$pipinstallaioapiUsageExamples of usage can be found atexamples/directory.To run example use command below:$makeexampleContributingTo work on theAIOAPIcodebase, you'll want to clone the project locally and install the required dependencies viapoetry:[email protected]:Gr1N/aioapi.git
$makeinstallTo run tests and linters use command below:$makelint&&maketestIf you want to run only tests or linters you can explicitly specify what you want to run, e.g.:$makelint-blackMilestonesIf you're interesting in project's future you can find milestones and plans atprojectspage.LicenseAIOAPIis licensed under the MIT license. See the license file for details. |
aio.api.bazel | Async wrapper around bazel |
aio-apiclient | aio-apiclient – Async helper to work with HTTP APIsFeaturesConvenient work with any HTTP API (especially with REST)Supportshttpxandaiohttpas backends to make requestsVery configurable and usableAn ability to parse responses automaticallyContentsFeaturesRequirementsInstallationQuickStartUsageInitializationApp ShutdownMiddlewaresBug trackerContributingLicenseRequirementspython >= 3.7Installationaio-apiclientshould be installed using pip:pip install aio-apiclientPlease note thataio-apiclientrequires any of supported http backends
(aiohttp, httpx) to be installed in order for it to work.You may optionally install the requirements with the library:# For httpx
pip install aio-apiclient[httpx]
# For aiohttp
pip install aio-apiclient[aiohttp]QuickStartGithub API (https://developer.github.com/v4/):fromapiclientimportAPIClient# First available backend (aiohttp, httpx) will be usedclient=APIClient('https://api.github.com',headers={'Authorization':'token OAUTH-TOKEN'})# Read information about the current repositoryrepo=awaitclient.api.repos.klen['aio-apiclient'].get()print(repo)# dict parsed from Github Response JSONSlack API (https://api.slack.com/web):fromapiclientimportAPIClientclient=APIClient('https://api.github.com',headers={'Authorization':'token OAUTH-TOKEN'})# Update current user status (we don't care about this response)awaitclient.api['users.profile.set'].post(json={'profile':{'status_text':'working','status_emoji':':computer:''status_expiration':30,}},read_response_body=False)And etcUsageInitializationThe Client initialization requires root URL for a required API.fromapiclientimportAPIClientclient=APIClient(# Root URL for any API (required)'https://api.github.com',# Raise `client.Error` for any response with status code > 400raise_for_status=True,# Set to `False` if you only want to make a request and doesn't care about responsesread_response_body=True,# Parse response's body content-type and return JSON/TEXT/Form data instead the response itself# Set total timeout in secondstimeout=10.0,# Set backend type for making requests (apiclient.backends.BackendHTTPX,# apiclient.backends.BackendAIOHTTP) by default first available would be# choosenbackend_type=None,# Default backend options to use with every request (headers, params, data, ...)# ...)App ShutdownThe api client support graceful shutdown. Runawait client.shutdown()when
you are finishing your app (not necessary).MiddlewaresYou are able to dinamically change request params (method, url, other backend params) using middlewares.importtimefromapiclientimportAPIClientclient=APIClient('https://api.github.com')@client.middlewareasyncdefinsert_timestamp_header(method,url,options):options.setdefault('headers',{})options['headers']['X-Timestamp']=str(time.time())returnmethod,url,optionsBug trackerIf you have any suggestions, bug reports or
annoyances please report them to the issue tracker
athttps://github.com/klen/aio-apiclient/issuesContributingDevelopment of the project happens at:https://github.com/klen/aio-apiclientLicenseLicensed under aMIT license. |
aio-api-crawler | aio_api_crawlerCrawler to extract data from various json api or html endpointsFree software: BSD licenseFeaturesAPI to parse JSON and HTML endpointsSinks to save parsed data into various databases or mqWorker class to run itSee examples.History0.1.0 (2020-10-31)First release on PyPI. |
aio.api.github | Wrapper around gidgethub |
aio.api.nist | Async fetcher/parser for NIST CVE data |
aio-api-ros | async implementation Mikrotik api
Only Python 3.5+ |
aio-apisession | No description available on PyPI. |
aio-api-sm | Asynchronous Request ManagerA simple wrapper around an aiohttp.ClientSession that automatically
performs retries and simple rate limiting. |
aioapns | aioapnsis a library designed specifically for sending push-notifications to iOS devices
via Apple Push Notification Service. aioapns provides an efficient client through
asynchronous HTTP2 protocol for use with Python’sasyncioframework.aioapns requires Python 3.6 or later.PerformanceIn my testing aioapns allows you to send on average 1.3k notifications per second on a single core.FeaturesInternal connection pool which adapts to the current loadSupport for certificate and token based connectionsAbility to set TTL (time to live) for notificationsAbility to set priority for notificationsAbility to set collapse-key for notificationsAbility to use production or development APNs serverInstallationUse pip to install:$ pip install aioapnsBasic Usageimportasynciofromuuidimportuuid4fromaioapnsimportAPNs,NotificationRequest,PushTypeasyncdefrun():apns_cert_client=APNs(client_cert='/path/to/apns-cert.pem',use_sandbox=False,)apns_key_client=APNs(key='/path/to/apns-key.p8',key_id='<KEY_ID>',team_id='<TEAM_ID>',topic='<APNS_TOPIC>',# Bundle IDuse_sandbox=False,)request=NotificationRequest(device_token='<DEVICE_TOKEN>',message={"aps":{"alert":"Hello from APNs","badge":"1",}},notification_id=str(uuid4()),# optionaltime_to_live=3,# optionalpush_type=PushType.ALERT,# optional)awaitapns_cert_client.send_notification(request)awaitapns_key_client.send_notification(request)loop=asyncio.get_event_loop()loop.run_until_complete(run())Licenseaioapns is developed and distributed under the Apache 2.0 license. |
aioapollo | No description available on PyPI. |
aioapp | aioappMicro framework based on asyncioFree software: Apache License 2.0Documentation:https://aioapp.readthedocs.io.FeaturesGraceful ShutdownZipkin tracing all external communicationsself healthcheckHistory0.0.1b1 (2018-01-17)First release on PyPI. |
aio.app | Application runner for theaioasyncio frameworkBuild statusInstallationRequires python >= 3.4Install with:pipinstallaio.appQuick start - hello world schedulerSave the following into a file “hello.conf”[schedule/EXAMPLE]every=2func=my_example.schedule_handlerAnd save the following into a file named “my_example.py”importasynciodefschedule_handler(event):yield fromasyncio.sleep(1)print("Received scheduled:%s"%event.name)Run with the aio run commandaiorun-chello.confTheaio configcommandWhen saving or reading configuration options, configuration files are searched for in order from the following locationsaio.confetc/aio.conf/etc/aio/aio.confTo dump the system configuration you can runaioconfigTo dump a configuration section you can use -g or –get with the section nameaioconfig-gaioaioconfig--getaio/commandsTo get a configuration option, you can use -g with the section name and optionaioconfig-gaio:log_levelaioconfig--getlisten/example:example-signalYou can set a configuration option with -s or –setOptions containing interpolation should be enclosed in single quotesMulti-line options should be enclosed in “ and separated with “\n”aioconfig--setaio:log_levelDEBUGaioconfig-saio/otherapp:log_level'${aio:log_level}'aioconfig-slisten/example:example-signal"my.listener\nmy.listener2"If no configuration files are present in the standard locations, aio will attempt to save in “aio.conf” in the current working directoryTo get or set an option in a particular file you can use the -f flagaioconfig-gaio:modules-fcustom.confaioconfig-saio:log_levelDEBUG-fcustom.confWhen getting config values with the -f flag,ExtendedInterpolationis not used, and you therefore see the raw valuestheaio runcommandYou can run an aio app as follows:aiorunOr with a custom configuration fileaio-ccustom.confrunOn startup aio run sets up the followingConfiguration - system-wide configurationModules - initialization and configuration of modulesLogging - system logging policiesSchedulers - functions called at set timesServers - listening on tcp/udp or other type of socketSignals - functions called in response to eventsConfigurationConfiguration is in ini syntax[aio]foo=eggsspamWhile the app is running the system configuration is importable from aio.appfromaio.appimportconfigConfiguration is parsed usingExtendedInterpolationas followsaio.app defaults readuser configuration read to initialize modules“aio.conf” read from initialized modules where presentuser configuration read againLoggingLogging policies can be placed in the configuration file, following pythonsfileConfigformatAs the configuration is parsed withExtendedInterpolationyou can use options from other sections[logger_root]level=${aio:log_level}handlers=consoleHandlerqualname=aioThe default aio:log_level is INFOAny sections that begin with handler, logger, or formatter will automattically be added to the relevant logging sectionSo by adding a section such as[logger_custom]level=${aio:log_level}handlers=consoleHandlerqualname=custom“logger_custom” will automatically be added to the logger keys:[loggers]keys=root,customModulesYou can list any modules that should be imported at runtime in the configuration[aio]modules=aio.web.serveraio.manhole.serverConfiguration for each module is read from a file named “aio.conf” in the module’s path, if it exists.The initialized modules can be accessed from aio.appfromaio.appimportmodulesSchedulersSchedule definition sections are in the following format[schedule/SCHEDULE_NAME]Specify the frequency and the function to call. The function will be wrapped in a coroutine if it isnt one already[schedule/example]every=2func=my.scheduler.example_schedulerThe scheduler function receives a ScheduledEvent objectdefexample_scheduler(event):yield fromasyncio.sleep(2)# do somethingprint(event.name)passServersServer definition sections are in the following format[server/SERVER_NAME]The server requires either a factory or a protocol to startProtocol configuration example:[server/example]protocol=my.example.MyServerProtocolport=8888Protocol example code:classMyServerProtocol(asyncio.Protocol):defconnection_made(self,transport):self.transport=transportdefdata_received(self,data):# do stuffself.transport.close()For the protocol option you can either specify a subclass of asyncio.Protocol or you can use a function decorated with aio.app.server.protocol[server/example]protocol=my.example.protocolport=8888Example code for a server protocol functionimportasyncioimportaio.app@aio.app.server.protocoldefserver_protocol():yield fromasyncio.sleep(1)# do somethingreturnMyServerProtocolIf you need further control over how the protocol is attached you can specify a factory methodFactory configuration example:[server/example]factory=my.example.server_factoryport=8080The factory method must be wrapped in aio.app.server.factory, and is called in a [email protected]_factory(name,protocol,address,port):yield fromasyncio.sleep(1)# do somethingloop=asyncio.get_event_loop()return(yield fromloop.create_server(MyServerProtocol,address,port))SignalsSignal definition sections are in the following format[signal/SIGNAL_NAME]An example listen configuration section[listen/example]example-signal=my.example.listenerAnd an example listener function. The listener function will be called as a coroutinedeflistener(signal):yield fromasyncio.sleep(2)print(signal.data)Signals are emitted in a coroutineyield fromapp.signals.emit('example-signal',"BOOM!")You can add multiple subscriptions within each configuration sectionYou can also subscribe multiple functions to a signal, and you can have multiple “listen/” sections[listen/example]example-signal=my.example.listenerexample-signal-2=my.example.listener2my.example.listener[listen/example-2]example-signal-3=my.example.listener2Theaio testcommandYou can test the modules set in the aio:modules configuration option[aio]modules=aio.configaio.coreaio.signalsBy default the aio test command will test all of your test modulesaiotestYou can also specify a module, or modulesaiotestaio.appaiotestaio.appaio.coreIf you want to specify a set of modules for testing other than your app modules, you can list them in aio/testing:modules[aio/testing]modules=aio.configaio.coreThese can include the app modules[aio/testing]modules=${aio:modules}aio.web.pageaio.web.serverDependenciesaio.app depends on the following packagesaio.coreaio.signalsaio.configRelated softwareaio.testingaio.http.serveraio.web.serveraio.manhole.serveraio.app usageThe aio command can be run with any commands listed in the [aio/commands] section of its configurationThere are also 3 builtin commands - run, config and testInitially aio.app does not have any config, signals, modules or servers>>> import aio.app>>> print(aio.app.signals, aio.app.config, aio.app.modules, aio.app.servers)
None None () {}Lets start the app runner in a test loop with the default configuration and print out the signals and config objects>>> import aio.testing
>>> from aio.app.runner import runner>>> @aio.testing.run_until_complete
... def run_app():
... runner(['run'])
...
... print(aio.app.signals)
... print(aio.app.config)
... print(aio.app.modules)
... print(aio.app.servers)>>> run_app()
<aio.signals.Signals object ...>
<configparser.ConfigParser ...>
(<module 'aio.app' from ...>,)
{}Clear the appWe can clear the app vars.This will also close any socket servers that are currently running>>> aio.app.clear()>>> print(aio.app.signals, aio.app.config, aio.app.modules, aio.app.servers)
None None () {}Adding a signal listenerWe can add a signal listener in the app config>>> config = """
... [listen/testlistener]
... test-signal = aio.app.tests._example_listener
... """Lets create a test listener and make it importableThe listener needs to be wrapped with aio.app.signal.listener and is called in a coroutine>>> import asyncio>>> @aio.app.signal.listener
... def listener(signal):
... yield from asyncio.sleep(1)
... print("Listener received: %s" % signal.data)>>> aio.app.tests._example_listener = listenerRunning the test…>>> @aio.testing.run_until_complete
... def run_app(message):
... runner(['run'], config_string=config)
... yield from aio.app.signals.emit('test-signal', message)
... aio.app.clear()>>> run_app('BOOM!')
Listener received: BOOM!We can also add listeners programatically>>> @aio.testing.run_until_complete
... def run_app(message):
... runner(['run'])
...
... aio.app.signals.listen('test-signal-2', aio.app.signal.listener(listener))
... yield from aio.app.signals.emit('test-signal-2', message)
... aio.app.clear()>>> run_app('BOOM AGAIN!')
Listener received: BOOM AGAIN!Adding app modulesWhen you run the app with the default configuration, the only module listed is aio.app>>> @aio.testing.run_until_complete
... def run_app(config_string=None):
... runner(['run'], config_string=config_string)
... print(aio.app.modules)
... aio.app.clear()>>> run_app()
(<module 'aio.app' from ...>,)We can make the app runner aware of any modules that we want to include, these are imported at runtime>>> config = """
... [aio]
... modules = aio.app
... aio.core
... """>>> run_app(config_string=config)
(<module 'aio.app' from ...>, <module 'aio.core' from ...>)Running a schedulerA basic configuration for a scheduler>>> config = """
... [schedule/test-scheduler]
... every: 2
... func: aio.app.tests._example_scheduler
... """Lets create a scheduler function and make it importable.The scheduler function is wrapped in a coroutine>>> def scheduler(event):
... print('HIT: %s' % event.name)>>> aio.app.tests._example_scheduler = schedulerWe need to use a aio.testing.run_forever to wait for the scheduled events to occur>>> @aio.testing.run_forever(timeout=5)
... def run_app():
... runner(['run'], config_string=config)
...
... return aio.app.clearRunning the test for 5 seconds we get 3 hits>>> run_app()
HIT: test-scheduler
HIT: test-scheduler
HIT: test-schedulerRunning a serverLets set up and run an addition serverAt a minimum we should provide a protocol and a port to listen on>>> config_server_protocol = """
... [server/additiontest]
... protocol: aio.app.tests._example_AdditionServerProtocol
... port: 8888
... """Lets create the server protocol and make it importable>>> class AdditionServerProtocol(asyncio.Protocol):
...
... def connection_made(self, transport):
... self.transport = transport
...
... def data_received(self, data):
... nums = [
... int(x.strip())
... for x in
... data.decode("utf-8").split("+")]
... self.transport.write(str(sum(nums)).encode())
... self.transport.close()>>> aio.app.tests._example_AdditionServerProtocol = AdditionServerProtocolAfter the server is set up, let’s call it with a simple addition>>> @aio.testing.run_forever
... def run_addition_server(config_string, addition):
... runner(['run'], config_string=config_string)
...
... def call_addition_server():
... reader, writer = yield from asyncio.open_connection(
... '127.0.0.1', 8888)
... writer.write(addition.encode())
... yield from writer.drain()
... result = yield from reader.read()
... aio.app.clear()
...
... print(int(result))
...
... return call_addition_server>>> run_addition_server(
... config_server_protocol,
... '2 + 2 + 3')
7If you need more control over how the server protocol is created you can specify a factory instead>>> config_server_factory = """
... [server/additiontest]
... factory = aio.app.tests._example_addition_server_factory
... port: 8888
... """The factory method must be decorated with aio.app.server.factory>>> @aio.app.server.factory
... def addition_server_factory(name, protocol, address, port):
... loop = asyncio.get_event_loop()
... return (
... yield from loop.create_server(
... AdditionServerProtocol,
... address, port))>>> aio.app.tests._example_addition_server_factory = addition_server_factory>>> run_addition_server(
... config_server_protocol,
... '17 + 5 + 1')
23 |
aioapp-amqp | aioapp_amqpMicro framework based on asyncioFree software: Apache License 2.0History0.0.1b1 (2018-01-17)First release on PyPI. |
aioapp-http | aioapp_httpMicro framework based on asyncioFree software: Apache License 2.0History0.0.1b1 (2018-01-17)First release on PyPI. |
aioapp-pg | aioapp_pgMicro framework based on asyncioFree software: Apache License 2.0History0.0.1b1 (2018-01-17)First release on PyPI. |
aioapp-redis | aioapp_redisMicro framework based on asyncioFree software: Apache License 2.0History0.0.1b1 (2018-01-17)First release on PyPI. |
aio-appstoreserverlibrary | aio-appstoreserverlibraryapp-store-server-library-python asyncio API client, based on official versionUsagefromappstoreserverlibrary.api_clientimportAppStoreServerAPIClient,APIExceptionfromappstoreserverlibrary.models.EnvironmentimportEnvironmentfromappstoreserverlibrary.models.SendTestNotificationResponseimportSendTestNotificationResponseprivate_key=read_private_key("/path/to/key/SubscriptionKey_ABCDEFGHIJ.p8")# Implemenation will varykey_id="ABCDEFGHIJ"issuer_id="99b16628-15e4-4668-972b-eeff55eeff55"bundle_id="com.example"environment=Environment.SANDBOXclient=AppStoreServerAPIAsyncClient(private_key,key_id,issuer_id,bundle_id,environment)asyncdeftest_notifi():try:response=awaitclient.request_test_notification()print(response)exceptAPIExceptionase:print(e) |
aioaprs | aioaprsAsync Python3 libraray implementing an APRS-IS clientThis library aims to implement a complete APRS-IS client based on the modern async pattern in Python 3.It's heavily based onaprslib, available onhttps://github.com/rossengeorgiev/aprs-python.UsageTODO |
aioaquacell | AioaquacellAsynchronous library to retrieve details of your Aquacell water softener deviceRequirementsaiohttpaioboto3requests_aws4authpycognitoaws_request_signerbotocoreUsageuserName="<email address>"password="<password>"asyncdefmain():api=AquacellApi()awaitapi.authenticate(userName,password)# Get the refresh tokenprint(api.refresh_token)softeners=awaitapi.get_all_softeners()forsoftenerinsofteners:print(softener.name)if__name__=="__main__":loop=asyncio.get_event_loop()loop.run_until_complete(main())Authenticate using refresh tokenrefresh_token="<refresh token>"api=AquacellApi()awaitapi.authenticate(refresh_token) |
aioaquarea | AioaquareaAsynchronous library to control Panasonic Aquarea devicesRequirementsThis library requires:Python >= 3.9asyncioaiohttpUsageThe library supports the production environment of the Panasonic Aquarea Smart Cloud API and also the Demo environment. One of the main usages of this library is to integrate the Panasonic Aquarea Smart Cloud API with Home Assistant viahome-assistant-aquareaHere is a simple example of how to use the library via getting a device object to interact with it:fromaioaquareaimport(Client,AquareaEnvironment,UpdateOperationMode)importaiohttpimportasyncioimportloggingfromdatetimeimporttimedeltaasyncdefmain():asyncwithaiohttp.ClientSession()assession:client=Client(username="USERNAME",password="PASSWORD",session=session,device_direct=True,refresh_login=True,environment=AquareaEnvironment.PRODUCTION,)# The library is designed to retrieve a device object and interact with it:devices=awaitclient.get_devices(include_long_id=True)# Picking the first device associated with the account:device_info=devices[0]device=awaitclient.get_device(device_info=device_info,consumption_refresh_interval=timedelta(minutes=1))# Or the device can also be retrieved by its long id if we know it:device=awaitclient.get_device(device_id="LONG ID",consumption_refresh_interval=timedelta(minutes=1))# Then we can interact with the device:awaitdevice.set_mode(UpdateOperationMode.HEAT)# The device can automatically refresh its data:awaitdevice.refresh_data()AcknowledgementsBig thanks toronhksfor his awesome work on thePanasonic Aquaera Smart Cloud integration with MQTT. |
aioarango | No description available on PyPI. |
aioarangodb | No description available on PyPI. |
aioari | Asynchronous clone ofhttps://github.com/asterisk/ari-pyUses async version of swagger-pyAboutThis package contains the Python client library for the Asterisk REST
Interface. It builds upon theSwagger.pylibrary, providing an
improved, Asterisk-specific API over the API generated by Swagger.pyUsageInstall from source using thesetup.pyscript.$ sudo ./setup.py installAPIAn async ARI client can be created simply by theaioari.connectmethod.
This will create a client based on the Swagger API downloaded from Asterisk.The API is modeled into the Repository Pattern, as you would find in Domain
Driven Design. Each Swagger Resource (a.k.a. API declaration) is mapped into a
Repository object, which is provided as a field on the client
(client.channels,client.bridges).Responses from Asterisk are mapped into first-class objects, akin to Domain
Objects in the Repository Pattern. These are provided both on the responses
to RESTful API calls, and for fields from events received over the WebSocket.Making REST callsEach Repository Object provides methods which invoke the non-instance specific
operations of the associated Swagger resource (bridges.list(),channels.get()). Instance specific methods are also provided, which require
identity parameters to be passed along (channels.get(channelId=id)).Instance specific methods are also provided on the Domain Objects
(some_channel.hangup()).Registering event callbacksAsterisk may send asyncronous messages over a WebSocket to indicate events of
interest to the application.TheClientobject has anon_eventmethod, which can be used to
subscribe for specific events from Asterisk.The first-class objects also have ‘on_event’ methods, which can subscribe to
Stasis events relating to that object.Object lifetimeThe Repository Objects exist for the lifetime of the client that owns them.Domain Objects are ephemeral, and not tied to the lifetime of the underlying
object in Asterisk. Pratically, this means that if you callchannels.get('1234')several times, you may get a different object back
every time.You may hold onto an instance of a Domain Object, but you should consider it
to be stale. The data contained in the object may be out of date, but the
methods on the object should still behave properly.If you invoke a method on a stale Domain Object that no longer exists in
Asterisk, you will get a HTTPError exception (404 Not Found).CaveatsThe dynamic methods exposed by Repository and Domain objects are, effectively,
remote procedure calls. The current implementation is synchronous, which means
that if anything were to happen to slow responses (slow network, packet loss,
system load, etc.), then the entire application could be affected.Examplesimportasyncioimportaioariclient=awaitaioari.connect('http://localhost:8088/','hey','peekaboo')defon_dtmf(channel,event):digit=event['digit']ifdigit=='#':channel.play(media='sound:goodbye')channel.continueInDialplan()elifdigit=='*':channel.play(media='sound:asterisk-friend')else:channel.play(media='sound:digits/%s'%digit)defon_start(channel,event):channel.on_event('ChannelDtmfReceived',on_dtmf)channel.answer()channel.play(media='sound:hello-world')client.on_channel_event('StasisStart',on_start)loop=asyncio.get_event_loop()loop.run_until_complete(client.run(apps="hello"))DevelopmentThe code is documented usingSphinx, which
allowsIntelliJ IDEAto do a better job at inferring types for autocompletion.To keep things isolated, I also recommend installing (and using)virtualenv.$ sudo pip install virtualenv
$ mkdir -p ~/virtualenv
$ virtualenv ~/virtualenv/ari
$ . ~/virtualenv/ari/bin/activateSetuptoolsis used for
building.Noseis used
for unit testing, with thecoverageplugin installed to
generated code coverage reports. Pass--with-coverageto generate
the code coverage report. HTML versions of the reports are put incover/index.html.$ ./setup.py develop # prep for development (install deps, launchers, etc.)
$ ./setup.py nosetests # run unit tests
$ ./setup.py bdist_egg # build distributableTODOCreate asynchronous bindings that can be used with Twisted, Tornado, etc.Add support for Python 3LicenseCopyright (c) 2013-2014, Digium, Inc.
Copyright (c) 2016, Denis Fokin.
Copyright (c) 2018, Matthias Urlichs.aioari is licensed with aBSD 3-Clause
License. |
aioaria2 | aioaria2Support async rpc call with aria2 and process managementUsage:exampleimportasynciofrompprintimportpprintimportaioaria2asyncdefmain():asyncwithaioaria2.Aria2HttpClient("http://117.0.0.1:6800/jsonrpc",token="token")asclient:pprint(awaitclient.getVersion())asyncio.run(main())The ip address should be replaced with your ownSeearia2 manualfor more detail about client methods# exampe of httpimportasynciofrompprintimportpprintimportaioaria2importujsonasyncdefmain():asyncwithaioaria2.Aria2HttpClient("http://127.0.0.1:6800/jsonrpc",token="token",loads=ujson.loads,dumps=ujson.dumps)asclient:pprint(awaitclient.addUri(["http://www.demo.com"]))# that would start downloadingasyncio.run(main())# exampe of websocketimportasynciofrompprintimportpprintimportaioaria2importujson@aioaria2.run_syncdefon_download_complete(trigger,data):print(f"downlaod complete{data}")asyncdefmain():client:aioaria2.Aria2WebsocketTrigger=awaitaioaria2.Aria2WebsocketTrigger.new("http://127.0.0.1:6800/jsonrpc",token="token",loads=ujson.loads,dumps=ujson.dumps)client.onDownloadComplete(on_download_complete)pprint(awaitclient.addUri(["http://www.demo.com"]))loop=asyncio.get_event_loop()loop.create_task(main())loop.run_forever()Run that coroutine function and each method represent an aria2-rpc call. As for server, each instance represent an aria2 process.importaioaria2importasyncioasyncdefmain():server=aioaria2.AsyncAria2Server(r"aria2c.exe",r"--conf-path=aria2.conf","--rpc-secret=admin",daemon=True)awaitserver.start()awaitserver.wait()asyncio.run(main())this start an aria2 processAria2 Manualtodolistasync httpasync websocketasync process managementunitestThis module is built on top ofaria2jsonrpcwith async and websocket support.For windows users, you should# for start async aria2 process
asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
asyncio.set_event_loop(asyncio.ProactorEventLoop())For python version greater than 3.8, asyncio uses ProactorEventLoop by default, so there is no need to modifyv1.2.0new Aria2WebsocketTrigger class for websocket events, use on* methods to add [email protected]
async def onDownloadStart(trigger, future):
print("下载开始{0}".format(future.result()))v1.2.3Now you can add multiple callbacks for one event ,must be coroutine function or an async callable, useaioaria2.run_syncto wrap a sync [email protected]
async def callback1(trigger, future):
print("第一个回调{0}".format(future.result()))
@trigger.onDownloadStart
@run_sync
def callback2(trigger, future):
print("第二个回调{0}".format(future.result()))v1.3.0Big changes for classAria2WebsocketTriggerCallbacks now acceptdictas second parameter instead ofasyncio.Futuremethods of classAria2WebsocketTriggernow have same return value asAria2HttpClientidparameter now accept a callable as idfactory to generate uuid, otherwise default uuid factory is [email protected]
async def callback1(trigger, data:dict):
print("第一个回调{0}".format(data))
@trigger.onDownloadStart
@run_sync
def callback2(trigger, data:dict):
print("第二个回调{0}".format(data))v1.3.1custom json library with keyword argumentsloadsdumpsv1.3.2fix unclosed client_session when exception occurs during ws_connectalias forAria2WebsocketTrigger,namedAria2WebsocketClientv1.3.3fix method problems in clientv1.3.4rc1handle reconnect simplyhandle InvalidstateError while trying to ping aria2v1.3.4add async id factory supportallow unregister callbacks in websocketclientadd contextvars support inrun_sync |
aioarp | aioarpTable of ContentsInstallationDocumentationARP SpoofingARP requestsLicenseInstallationpip install aioarpDocumentationClick hereArp spoofingUsing this command, you can disable internet access for any device on your local network.$aioarpdisable192.168.0.81192.168.0.1enp0s3--seconds10or$aioarpspoof192.168.0.81192.168.0.111:11:11:11:11:11enp0s3--seconds10spoofcan be used to specify the fake mac address.Where...192.168.0.81is a target IP address for which we are blocking internet access.192.168.0.1is a gateway for our target IP address.enp0s3is an optional interface used to send ARP requests. if not specified, the default interface is used.secondsis an option that specifies how long we want to disable internet access for the target IP address.How to send ARP requestsSyncimportaioarpresponse=aioarp.request('10.0.2.2','enp0s3')print(response.sender_mac)# ee:xx:aa:mm:pp:le mac addressAsync [trio or asyncio]importtrioimportaioarpresponse=trio.run(aioarp.arequest,'10.0.2.2','enp0s3')importasyncioimportaioarpresponse=asyncio.run(aioarp.arequest('10.0.2.2','enp0s3'))Or without specifying aninterfaceparameterresponse = aioarp.request('10.0.2.2')Licenseaioarpis distributed under the terms of theMITlicense.Changelog0.0.11 (4/7/2023)Usegetmacpackage for mac address detecting.Addsend,disableandspoofcommands for the CLI. (#33)Make theinterfaceargument for thebuild_arp_packetfunction optional. (#32)0.0.10 (1/7/2023)AddPacketbase class. (#28)ChangeProtocoltoProtocolType. (#30)Validatesender_ipof the ARP response packet.0.0.9 (27/6/2023)Makeinterfaceargument optional. (#23)MoveStreamcreation fromrequesttosync_send_arp. (#24)0.0.8 (21/6/2023)Addwait_responseargument tosync_send_arpandasync_send_arp. (#13)0.0.7 (16/6/2023)Add basic API documentation. (#7)0.0.5 (12/6/2023)Add simple cli.0.0.3 (5/6/2023)Addsockargument torequestandarequestfunctions.Addtimeoutargument torequestandarequestfunctions.AddMockSocketclass for better unit testing.Change signature ofsync_send_arpandasync_send_arpfunctions, now they accept thestreamargument. |
aioarping | UNKNOWN |
aioartifactory | # Python Asynchronous Input Output (AIO) ArtifactoryPython Asynchronous Input Output (AIO) Artifactory |
aioaseko | aioAseko packageAn async Python wrapper for the Aseko Pool Live API.The library is currently limited to the features available on pool.aseko.com.AccountThe library provides aMobileAccountandWebAccountclass to make authenticated requests to the mobile and web API, respectively.
In this version of aioAseko,WebAccountcan only be used to obtainAccountInfoand retrieve the account units.
The mobile API does not provideAccountInfo, soMobileAccount.login()will returnNone.InstallationpipinstallaioasekoUsageImportfromaioasekoimportMobileAccountCreate aaiohttp.ClientSessionto make requestsfromaiohttpimportClientSessionsession=ClientSession()Create aMobileAccountinstance and loginaccount=MobileAccount(session,"[email protected]","passw0rd")awaitaccount.login()ExamplefromaiohttpimportClientSessionfromasyncioimportrunimportaioasekoasyncdefmain():asyncwithClientSession()assession:account=aioaseko.MobileAccount(session,"[email protected]","passw0rd")try:awaitaccount.login()exceptaioaseko.InvalidAuthCredentials:print("The username or password you entered is wrong.")returnunits=awaitaccount.get_units()forunitinunits:print(unit.name)awaitunit.get_state()print(f"Water flow:{unit.water_flow}")forvariableinunit.variables:print(variable.name,variable.current_value,variable.unit)awaitaccount.logout()run(main()) |
aioasuswrt | Small wrapper for asuswrt.How to run testspython setup.py testCredits:@mvn23@halkeye@maweki@quarcko@wdullaerInfoThere are many different versions of asuswrt and sometimes they just dont work in current implementation.
If you have a problem with your specific router open an issue, but please add as much info as you can and atleast:Version of routerVersion of AsuswrtKnown issuesBugsYou can always create an issue in this tracker.
To test and give us the information needed you could run:#!/usr/bin/env pythonimportasyncioimportloggingimportsysfromaioasuswrt.asuswrtimportAsusWrtcomponent=AsusWrt('192.168.1.1',22,username='****',password='****')logging.basicConfig(stream=sys.stdout,level=logging.DEBUG)logger=logging.getLogger(__name__)asyncdefprint_data():logger.debug("wl")logger.debug(awaitcomponent.connection.async_run_command('for dev in `nvram get wl_ifnames`; do wl -i $dev assoclist; done'))dev=awaitcomponent.async_get_wl()logger.debug(dev)logger.debug("arp")logger.debug(awaitcomponent.connection.async_run_command('arp -n'))dev.update(awaitcomponent.async_get_arp())logger.debug(dev)logger.debug("neigh")logger.debug(awaitcomponent.connection.async_run_command('ip neigh'))dev.update(awaitcomponent.async_get_neigh(dev))logger.debug(dev)logger.debug("leases")logger.debug(awaitcomponent.connection.async_run_command('cat /var/lib/misc/dnsmasq.leases'))dev.update(awaitcomponent.async_get_leases(dev))logger.debug(dev)loop=asyncio.get_event_loop()loop.run_until_complete(print_data())loop.close()Coffeefund: 1Huz6vNN6drX3Fq1sU98wPqNSdMPvkMBJG |
aioatomapi | aioatomapiallows you to interact with devices flashed withAtom.InstallationThe module is available from thePython Package Index.$pip3installaioatomapiUsageIt’s required that you enable theNative APIcomponent for the device.# Example configuration entryapi:password:'MyPassword'Check the output to get the local address of the device or use thename:``under``atom:from the device configuration.[17:56:38][C][api:095]:APIServer:[17:56:38][C][api:096]:Address:api_test.local:6053The sample code below will connect to the device and retrieve details.importaioatomapiimportasyncioasyncdefmain():"""Connect to an Atom device and get details."""loop=asyncio.get_running_loop()# Establish connectionapi=aioatomapi.APIClient(loop,"api_test.local",6053,"MyPassword")awaitapi.connect(login=True)# Get API version of the device's firmwareprint(api.api_version)# Show device detailsdevice_info=awaitapi.device_info()print(device_info)# List all entities of the deviceentities=awaitapi.list_entities_services()print(entities)loop=asyncio.get_event_loop()loop.run_until_complete(main())Subscribe to state changes of an Atom device.importaioatomapiimportasyncioasyncdefmain():"""Connect to an Atom device and wait for state changes."""loop=asyncio.get_running_loop()cli=aioatomapi.APIClient(loop,"api_test.local",6053,"MyPassword")awaitcli.connect(login=True)defchange_callback(state):"""Print the state changes of the device.."""print(state)# Subscribe to the state changesawaitcli.subscribe_states(change_callback)loop=asyncio.get_event_loop()try:asyncio.ensure_future(main())loop.run_forever()exceptKeyboardInterrupt:passfinally:loop.close()Other examples:CameraAsync printSimple printInfluxDBDevelopmentFor development is recommended to use a Python virtual environment (venv).# Setup virtualenv (optional)$python3-mvenv.$sourcebin/activate# Install aioatomapi and development depenencies$pip3install-e.$pip3install-rrequirements_test.txt# Run linters & test$script/lint# Update protobuf _pb2.py definitions (requires a protobuf compiler installation)$script/gen-protocLicenseaioatomapiis licensed under MIT, for more details check LICENSE. |
aioauth | Asynchronous OAuth 2.0 framework for Python 3aioauthimplementsOAuth 2.0 protocoland can be used in asynchronous frameworks likeFastAPI / Starlette,aiohttp. It can work with any databases likeMongoDB,PostgreSQL,MySQLand ORMs likegino,sqlalchemyordatabasesover simpleBaseStorageinterface.Why this project exists?There are few great OAuth frameworks for Python likeoauthlibandauthlib, but they do not support asyncio and rewriting these libraries to asyncio is a significant challenge (see issueshereandhere).Supported RFCsThe OAuth 2.0 Authorization FrameworkOAuth 2.0 Token IntrospectionProof Key for Code Exchange by OAuth Public ClientsOpenID supportInstallationpython -m pip install aioauthFastAPIFastAPI integration stored on separatedaioauth-fastapirepository and can be installed via the command:python -m pip install aioauth[fastapi]aioauth-fastapirepository contains demo example which I recommend to look.API Reference and User Guide |
aioauth-client | AIOAuth Client – OAuth support forAsyncio/Triolibraries.ContentsRequirementsInstallationUsageExampleBug trackerContributingLicenseRequirementspython >= 3.8InstallationAIOAuth Clientshould be installed using pip:pip install aioauth-clientUsage# OAuth2fromaioauth_clientimportGithubClientgithub=GithubClient(client_id='b6281b6fe88fa4c313e6',client_secret='21ff23d9f1cad775daee6a38d230e1ee05b04f7c',)authorize_url=github.get_authorize_url(scope="user:email")# ...# Reload client to authorize_url and get code# ...otoken,_=awaitgithub.get_access_token(code)# Save the token for later use# ...github=GithubClient(client_id='b6281b6fe88fa4c313e6',client_secret='21ff23d9f1cad775daee6a38d230e1ee05b04f7c',access_token=otoken,)# Or you can use this if you have initilized client already# github.access_token = otokenresponse=awaitgithub.request('GET','user')user_info=awaitresponse.json()# OAuth1fromaioauth_clientimportTwitterClienttwitter=TwitterClient(consumer_key='J8MoJG4bQ9gcmGh8H7XhMg',consumer_secret='7WAscbSy65GmiVOvMU5EBYn5z80fhQkcFWSLMJJu4',)request_token,_=awaittwitter.get_request_token()authorize_url=twitter.get_authorize_url(request_token)print("Open",authorize_url,"in a browser")# ...# Reload client to authorize_url and get oauth_verifier# ...print("PIN code:")oauth_verifier=input()oauth_token,data=awaittwitter.get_access_token(oauth_verifier)oauth_token_secret=data.get('oauth_token_secret')# Save the tokens for later use# ...twitter=TwitterClient(consumer_key='J8MoJG4bQ9gcmGh8H7XhMg',consumer_secret='7WAscbSy65GmiVOvMU5EBYn5z80fhQkcFWSLMJJu4',oauth_token=oauth_token,oauth_token_secret=oauth_token_secret,)# Or you can use this if you have initilized client already# twitter.access_token = oauth_token# twitter.access_token_secret = oauth_token_secrettimeline=awaittwitter.request('GET','statuses/home_timeline.json')content=awaittimeline.read()print(content)ExampleRun example with command:make exampleOpenhttp://localhost:8080in your browser.Bug trackerIf you have any suggestions, bug reports or
annoyances please report them to the issue tracker
athttps://github.com/klen/aioauth-client/issuesContributingDevelopment of AIOAuth Client happens at:https://github.com/klen/aioauth-clientLicenseLicensed under aMIT license. |
aioauth-fastapi | aioauth integration for FastAPIaioauth_fastapi: the core of FastAPI integrationaioauth_fastapi_demo: the demo project withSQLAlchemyas an ORM andsqlmodel |
aio-auth-with | # aio-auth-with## DescriptionAuth client library to handle different auth providers. |
aioautomatic | ===============================aioautomatic===============================.. image:: https://img.shields.io/pypi/v/aioautomatic.svg:target: https://pypi.python.org/pypi/aioautomatic.. image:: https://img.shields.io/travis/armills/aioautomatic.svg:target: https://travis-ci.org/armills/aioautomatic.. image:: https://img.shields.io/coveralls/armills/aioautomatic.svg:target: https://coveralls.io/r/armills/aioautomatic?branch=masterAsyncio library for the Automatic API* Free software: Apache Software License 2.0All methods are python wrappers of the API definitions defined by `Automatic <https://developer.automatic.com/api-reference/>`_.Usage-----It is recommended to manage the aiohttp ClientSession object externally and pass it to the Client constructor. `(See the aiohttp documentation.) <https://aiohttp.readthedocs.io/en/stable/client_reference.html#aiohttp.ClientSession>`_ If not passed to Server, a ClientSession object will be created automatically.Query for information from the users account... code-block:: pythonimport asyncioimport aioautomaticimport aiohttpfrom datetime import datetimefrom datetime import timedeltaCLIENT_ID = '<client_id>'SECRET_ID = '<secret>'SCOPE = ['current_location', 'location', 'vehicle:profile', 'user:profile', 'trip']@asyncio.coroutinedef loop():aiohttp_session = aiohttp.ClientSession()try:client = aioautomatic.Client(CLIENT_ID,SECRET_ID,aiohttp_session)url = client.generate_oauth_url(SCOPE)# Redirect the user to this URL. After the user authorizes access# to their account, Automatic will redirect them to your# application's OAuth Redirect URL, configured in the Automatic# Developer Apps Manager. Capture the code and state returned# with that request.code = '<code>'state = '<state>'session = yield from client.create_session_from_oauth_code(code, state)# Fetch information about the authorized useruser = yield from session.get_user()user_profile = yield from user.get_profile()user_metadata = yield from user.get_metadata()print("***USER***")print(user)print(user.email)print(user.first_name)print(user.last_name)print(user_profile.date_joined)print(user_metadata.firmware_version)print(user_metadata.device_type)print(user_metadata.phone_platform)# Fetch all devices associated with the user accountdevices = yield from session.get_devices()print("***DEVICES***")print(devices)# Fetch a list of vehicles associated with the user accountvehicles = yield from session.get_vehicles()print("***VEHICLES***")print(vehicles)print(vehicles[0].make)print(vehicles[0].model)print(vehicles[0].fuel_level_percent)# Fetch a list of all trips in the last 10 daysmin_end_time = datetime.utcnow() - timedelta(days=10)trips = yield from session.get_trips(ended_at__gte=min_end_time, limit=10)print("***TRIPS***")print(trips)print(trips[0].start_location.lat)print(trips[0].start_location.lon)print(trips[0].start_address.name)print(trips[0].distance_m)print(trips[0].duration_s)# If more than 10 trips exist, get the next page of resultsif trips.next is not None:trips = yield from trips.get_next()print(trips)# Save the refresh token from the session for use next time# a session needs to be created.refresh_token = session.refresh_token# Create a new session with the refresh token.session = yield from client.create_session_from_refresh_token(refresh_token)finally:yield from aiohttp_session.close()asyncio.get_event_loop().run_until_complete(loop())Open a websocket connection for realtime updates.. code-block:: pythonimport asyncioimport aioautomaticimport aiohttpSCOPE = ['current_location', 'location', 'vehicle:profile', 'user:profile', 'trip']CLIENT_ID = '<client_id>'SECRET_ID = '<secret>'def error_callback(name, message):print(message)def event_callback(name, data):print(name)if data.location:print(data.location.lat)print(data.location.lon)def speeding_callback(name, data):print("Speeding! Velocity: {:1.2f} KPH".format(data.velocity_kph))@asyncio.coroutinedef loop():aiohttp_session = aiohttp.ClientSession()try:client = aioautomatic.Client(CLIENT_ID,SECRET_ID,aiohttp_session)client.on('closed', closed_callback)client.on('notification:speeding', speeding_callback)client.on_app_event(callback)future = yield from client.ws_connect()# Run until websocket is closedyield from futurefinally:yield from aiohttp_session.close()asyncio.get_event_loop().run_until_complete(loop())Changelog---------0.6.5 (February 17, 2018)~~~~~~~~~~~~~~- Validation schemas are now compatible with voluptuous 0.11.0.6.4 (October 22, 2017)~~~~~~~~~~~~~~- Vehicle requets now correctly return a location object for latest_location.0.6.3 (September 14, 2017)~~~~~~~~~~~~~~- Trip responses that don't include start or end addresses are now accepted.0.6.2 (August 26, 2017)~~~~~~~~~~~~~~- Invalid messages received during the websocket loop will only emit a log error instead of bubbling out of the loop.0.6.1 (August 26, 2017)~~~~~~~~~~~~~~- Voluptuous errors will no longer bubble out of aioautomatic. Instead InvalidMessageError will be raised.0.6.0 (August 15, 2017)~~~~~~~~~~~~~~- Removed `Client.create_session_from_password`, which is no longer supported by Automatic.0.5.0 (August 12, 2017)~~~~~~~~~~~~~~- Added `Client.generate_oauth_url` to simplify implementation of OAuth2 authentication.- State is now required for `Client.create_session_from_oauth_code`.Credits---------This package is built on aiohttp_, which provides the foundation for async HTTP and websocket calls.This package was created with Cookiecutter_ and the `audreyr/cookiecutter-pypackage`_ project template... _aiohttp: http://aiohttp.readthedocs.io/en/stable/.. _Cookiecutter: https://github.com/audreyr/cookiecutter.. _`audreyr/cookiecutter-pypackage`: https://github.com/audreyr/cookiecutter-pypackage |
aioautomower | AioautomowerAsynchronous library to communicate with the Automower Connect API
To use this library, you need to register on theHusqvarna Developers Portal.
And connect your account to theAuthentication APIand theAutomower Connect API.QuickstartIn order to use the library, you'll need to do some work yourself to get authentication
credentials. This depends a lot on the context (e.g. redirecting to use OAuth via web)
but should be easy to incorporate using Husqvarna's authentication examples. See
Husqvarna'sAuthentication APIfor details.You will implementAbstractAuthto provide an access token. Your implementation
will handle any necessary refreshes. You can invoke the service with your auth implementation
to access the API.For a first start you can run theexample.py, by doing the following stepsgit clone https://github.com/Thomas55555/aioautomower.gitpip install -e ./Enter your personalclient_idandclient_secretin theexample.pyRun withpython3 ./aioautomower/example.pyAutomowerCLI exampleAn AutomowerSession that provides you with the data in a CLIautomower --client_secret 12312312-12ec-486b-a7a7-9d9b06644a14 --api-key 12312312-0126-6222-2662-3e6c49f0012c |
aioavast | asyncio (PEP 3156) Avast Linux supportFeaturesScanning files and/or directories.Checking URLs.Exclude files from the scanning.Get and set the list of enabled or disabled pack and flags.RequirementsPython >= 3.3asynciohttps://pypi.python.org/pypi/asyncioLicenseaioavastis offered under the MIT license.Source codeThe latest developer version is available in a github repository:https://github.com/earada/aioavastGetting startedScanningScan a file and prints its output:[email protected](item):av=Avast()yield fromav.connect()return(yield fromav.scan(item))if__name__=='__main__':loop=asyncio.get_event_loop()results=loop.run_until_complete(scan('/bin/ls'))print(results)You can check an url too:return(yield fromav.checkurl('http://python.org'))Exclude itemsThere is also a possibility to exclude certain files from being scanned.importasynciofromaioavastimportAvast@asyncio.coroutinedefdont_scan(item):av=Avast()yield fromav.connect()yield fromav.exclude(item)return(yield fromav.scan(item))if__name__=='__main__':loop=asyncio.get_event_loop()results=loop.run_until_complete(scan('/bin/ls'))print(results)You can retrieve excluded items by:excluded=yield fromav.exclude()Other methodsYou could modify Flags and Packs too.flags=yield fromav.flags()yield fromav.flags("-allfiles")packs=yield fromav.pack()yield fromav.flags("-ole") |
aio-avion | aio_avionLibrary for controlling Avi-on based devices through the RAB (Remote Access Bridge) |
aioawait | This package implements two primitives (awaitandspawn) on top
of asyncio infrastructure of Python 3. This two functions allow us to call
asynchronous functions from synchronous code.Installationpip3installaioawaitExamplefromasyncio.tasksimportcoroutine,sleep,asyncfromaioawaitimportawait,spawn@coroutinedefmonitor(name,size,total):whileTrue:print('\ttotal',name,total)yield fromsleep(1)@coroutinedefcounter(name,size,total):"""sums into total all numbers from 0 to size"""m=async(monitor(name,size,total))# monitor could be called using spawn. eg:# m = spawn(monitor(name, size, total))forninrange(size):total[0]+=nifn%5==0:print('sleeping',name,n)yield fromsleep(2)else:print('counting',name,n)yield# stops monitorm.cancel()returnname,'done',n,totalclassCounter:"""note that this class has no asynchronous code"""def__init__(self):self.cb=spawn(counter('b',40,[0]))@propertydefcounter_a(self):returnawait(counter('a',20,[0]))@propertydefcounter_b(self):returnawait(self.cb)if__name__=='__main__':c=Counter()print(c.counter_a)print(c.counter_b) |
aioaws | aioawsAsyncio compatible SDK for aws services.This library does not depend on boto, boto3 or any of the other bloated, opaque and mind thumbing AWS SDKs. Instead, it
is written from scratch to provide clean, secure and easily debuggable access to AWS services I want to use.The library is formatted with black and includes complete type hints (mypy passes in strict-mode).It currently supports:S3- list, delete, recursive delete, generating signed upload URLs, generating signed download URLsSES- sending emails including with attachments and multipartSNS- enough to get notifications about mail delivery from SESAWS Signature Version 4authentication for any AWS service (this is the only clean & modern implementation of AWS4 I know of in python, seecore.py)The only dependencies ofaioaws, are:aiofiles- for asynchronous reading of filescryptography- for verifying SNS signatureshttpx- for HTTP requestspydantic- for validating responsesInstallpipinstallaioawsS3 Usageimportasyncio# requires `pip install aioaws`fromaioaws.s3importS3Client,S3ConfigfromhttpximportAsyncClient# requires `pip install devtools`fromdevtoolsimportdebugasyncdefs3_demo(client:AsyncClient):s3=S3Client(client,S3Config('<access key>','<secret key>','<region>','my_bucket_name.com'))# upload a file:awaits3.upload('path/to/upload-to.txt',b'this the content')# list all files in a bucketfiles=[fasyncforfins3.list()]debug(files)"""[S3File(key='path/to/upload-to.txt',last_modified=datetime.datetime(...),size=16,e_tag='...',storage_class='STANDARD',),]"""# list all files with a given prefix in a bucketfiles=[fasyncforfins3.list('path/to/')]debug(files)# # delete a file# await s3.delete('path/to/file.txt')# # delete two files# await s3.delete('path/to/file1.txt', 'path/to/file2.txt')# delete recursively based on a prefixawaits3.delete_recursive('path/to/')# generate an upload link suitable for sending to a borwser to enabled# secure direct file upload (see below)upload_data=s3.signed_upload_url(path='path/to/',filename='demo.png',content_type='image/png',size=123,)debug(upload_data)"""{'url': 'https://my_bucket_name.com/','fields': {'Key': 'path/to/demo.png','Content-Type': 'image/png','AWSAccessKeyId': '<access key>','Content-Disposition': 'attachment; filename="demo.png"','Policy': '...','Signature': '...',},}"""# generate a temporary link to allow yourself or a client to download a filedownload_url=s3.signed_download_url('path/to/demo.png',max_age=60)print(download_url)#> https://my_bucket_name.com/path/to/demo.png?....asyncdefmain():asyncwithAsyncClient(timeout=30)asclient:awaits3_demo(client)asyncio.run(main())upload_datashown in the above example can be used in JS with something like this:constformData=newFormData()for(let[name,value]ofObject.entries(upload_data.fields)){formData.append(name,value)}constfileField=document.querySelector('input[type="file"]')formData.append('file',fileField.files[0])constresponse=awaitfetch(upload_data.url,{method:'POST',body:formData})(in the request to getupload_datayou would need to provide the file size and content-type in order
for them for the upload shown here to succeed)SESTo send an email with SES:frompathlibimportPathfromhttpximportAsyncClientfromaioaws.sesimportSesConfig,SesClient,SesRecipient,SesAttachmentasyncdefses_demo(client:AsyncClient):ses_client=SesClient(client,SesConfig('<access key>','<secret key>','<region>'))message_id=awaitses_client.send_email(SesRecipient('[email protected]','Sender','Name'),'This is the subject',[SesRecipient('[email protected]','John','Doe')],'this is the plain text body',html_body='<b>This is the HTML body.<b>',bcc=[SesRecipient(...)],attachments=[SesAttachment(b'this is content','attachment-name.txt','text/plain'),SesAttachment(Path('foobar.png')),],unsubscribe_link='https:://example.com/unsubscribe',configuration_set='SES configuration set',message_tags={'ses':'tags','go':'here'},)print('SES message ID:',message_id)asyncdefmain():asyncwithAsyncClient()asclient:awaitses_demo(client)asyncio.run(main())SNSReceiving data about SES webhooks from SNS (assuming you're using FastAPI)fromaioaws.sesimportSesWebhookInfofromaioaws.snsimportSnsWebhookErrorfromfastapiimportRequestfromhttpximportAsyncClientasync_client=AsyncClient...@app.post('/ses-webhook/',include_in_schema=False)asyncdefses_webhook(request:Request):request_body=awaitrequest.body()try:webhook_info=awaitSesWebhookInfo.build(request_body,async_client)exceptSnsWebhookErrorase:debug(message=e.message,details=e.details,headers=e.headers)raise...debug(webhook_info)...Seeherefor more information about what's provided in aSesWebhookInfo. |
aio-aws | aio-awsAsynchronous functions and tools for AWS services. There is a
limited focus on s3 and AWS Batch and Lambda. Additional services could be
added, but this project is likely to retain a limited focus.
For general client solutions, seeaioboto3andaiobotocore, which wrapbotocoreThe API documentation is atreadthedocsInstallThis project has a very limited focus. For general client solutions, seeaioboto3andaiobotocore, which wrapbotocoreto patch it with features for async coroutines usingaiohttpandasyncio.This project is alpha-status with a 0.x.y API version that could break.
There is no promise to support or develop it extensively, at this time.pippipinstall-Uaio-aws[all]pipcheck# pip might not guarantee consistent packagespoetrypoetry will try to guarantee consistent packages or fail.# with optional extraspoetryaddaio-aws--extrasall# pyproject.toml snippet[tool.poetry.dependencies]python="^3.7"# with optional extrasaio-aws={version="^0.1.0",extras=["all"]}# or, to make it an optional extraaio-aws={version="^0.1.0",extras=["all"],optional=true}[tool.poetry.extras]aio-aws=["aio-aws"]ContributingTo use the source code, it can be cloned directly. Contributions are welcome
via github flow and pull requests. To contribute to the project, first fork
it and clone the forked repository.The following setup assumes thatminiconda3andpoetryare installed already
(andmake4.x).https://docs.conda.io/en/latest/miniconda.htmlrecommended for creating virtual environments with required versions of pythonseehttps://github.com/dazza-codes/conda-venvhttps://python-poetry.org/docs/recommended for managing a python project with pip dependencies for
both the project itself and development dependenciesgitclonehttps://github.com/dazza-codes/aio-awscdaio-aws
condacreate-naio-awspython=3.8
condaactivateaio-aws
makeinit# calls poetry installmaketestNote: on OSX, install GNU make >= 4.x using homebrew and substitutegmakeformake.Release VersionsInstallpipxand use it to installversionner.pipxinstallversionner
ver--helpWithpipxandversionnerinstalled, it can be used to manage releases
for any python library. See the documentation forverfor details on
how to manage sem-ver library releases. See.versionner.rcfile for
details of the project configuration.LicenseCopyright 2019-2023 Darren Weber
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.NoticesInspiration for this project comes from various open source projects that use
the Apache 2 license, including but not limited to:Apache Airflow:https://github.com/apache/airflowaiobotocore:https://github.com/aio-libs/aiobotocorebotocore:https://github.com/boto/botocore |
aioax25 | aioax25: AX.25 and APRS library inasyncioThe aim of this project is to implement a simple-to-understand asynchronous
AX.25 library built onasyncioandpyserial, implementing a AX.25 and APRS
stack in pure Python.Python 3.5+ and above is required as of 2021-11-12I did try to support 3.4, but this proved to be infeasible for the following
reasons:Python 3.8+ makesasyncio.coroutinedeprecated (apparently will be removed
in 3.10). This meant I neededcoroutineandasync defversions of some
API functions, and the necessary logic to "hide" the latter from Python 3.4.Trying to coax generator-based coroutines to run "in the background" for unit
test purposes proved to be a pain in the arse.Python 3.5 support is planned to continue until it too, becomes infeasible
(e.g. if type annotations become required).What worksWe can put a Kantronics KPC-3 TNC into KISS mode automaticallyMulti-port KISS TNCs (tested withDirewolfand theNWDR UDRC-II)We can receive AX.25 UI framesWe can send AX.25 UI framesWhat doesn't workConnecting to AX.25 nodesAccepting connections from AX.25 nodesWhat isn't testedPlatforms other than GNU/LinuxCurrent plansRight now, I intend to get enough going for APRS operation, as that is my
immediate need now. Hence the focus on UI frames.I intend to write a core class that will take care of some core AX.25 message
handling work and provide the basis of what's needed to implement APRS.After that, some things I'd like to tackle in no particular order:Connected mode operationNET/ROM supportSupported platforms will be GNU/Linux, and possibly BSD variants. I don't
have access to recent Apple hardware (my 2008-era MacBook will not run
contemporary MacOS X) so I'm unable to test this software there, but itshouldwork nonetheless.It might work on Windows -- most probably using Cygwin or Subsystem for Linux.
While I do have a Windows 7 machine handy, life's too short to muck around
with an OS that can't decide if it's pretending to be Linux, VMS or CP/M.
There's an abundance of AX.25 stacks and tools for that platform, I'll accept
patches here on the proviso they don't break things or make the code
unmaintainable.UsageThis is a rough guide regarding how to useaioax25in your programs.Create a KISS device interface and portsRight now we only support serial KISS interfaces (patches for TCP-based
interfaces are welcome). Importmake_devicefromaioax25.kiss, then
create an instance as shown:kissdev=make_device(type='serial',device='/dev/ttyS4',baudrate=9600,log=logging.getLogger('your.kiss.log'))Or for a TCP-connected KISS interface:kissdev=make_device(type='tcp',host='kissdevice.example.com',port=12345,log=logging.getLogger('your.kiss.log'))(Note: ifkissdevice.example.comis going over the Internet, I suggest either
routing via a VPN or supplying assl.SSLContextvia thesslparameter so
that your client is authenticated with the server.)Or for a subprocess:kissdev = make_device(
type='subproc', command=['/path/to/your/command', 'arg1', 'arg2'],
log=logging.getLogger('your.kiss.log')
)Some optional parameters:reset_on_close: When asked to close the device, try to issue ac0 ff c0reset sequence to the TNC to put it back into CMD mode.send_block_size,send_block_delay: If a KISS frame is larger than
this size, break the transmissions out the serial port into chunks of
the given size, and waitsend_block_delayseconds between each chunk.
(If your TNC has a small buffer, this may help.)This represents the KISS TNC itself, with its ports accessible using the usual__getitem__syntax:kissport0=kissdev[0]kissport1=kissdev[1]These KISS port interfaces just spit out the content of raw AX.25 frames via
theirreceivedsignals and accept raw AX.25 frames via thesendmethod.
Any object passed tosendis wrapped in abytescall -- this will
implicitly call the__bytes__method on the object you pass in.Setting up an AX.25 InterfaceThe AX.25 interface is a logical routing and queueing layer which decodes the
data received from a KISS port and routes it according to the destination
call-sign.AX25Interfaceis found in theaioax25.interfacepackage. Import that, then
do the following to set up your interface:ax25int=AX25Interface(kissport=kissdev[0],# or whatever port number you needlog=logging.getLogger('your.ax25.log'))Some optional parameters:cts_delay,cts_rand: The number of seconds to wait after making a
transmission/receiving a transmission, before we send another transmission.
The delay time iscts_delay + (random.random() * cts_rand), the idea
being to avoid doubling when two stations attempt transmission.TheAX25Interfaceis a subclass ofRouter(seeaioax25.router), which
exposes the following methods and properties:received_msg: This is aSignalobject which is fired for every AX.25
frame received. Slots are expected to take two keyword arguments:interface(the interface that received the frame) andframe(the
AX.25 frame itself).bind(callback, callsign, ssid=0, regex=False): This method allows you to
bind a call-back function to receive AX.25 frames whosedestinationfield
is addressed to the call-sign and SSID specified. The call-sign may be a
regular expression ifregex=True. This will be compiled and matched
against all incoming traffic. Regardless of the value ofregex, thecallsignparametermustbe a string.unbind(callback, callsign, ssid=0, regex=False): This method un-binds a
previously bound call-back method from receiving the nominated traffic.Additionally, for transmitting frames,AX25Interfaceadds the following:transmit(frame, callback=None): This method allows you to transmit
arbitrary AX.25 frames. They are assumed to be instances ofAX25Frame(fromaioax25.frame). Thecallback, if given, will be called once the
frame is sent with the following keyword arguments:interface(theAX25Interfacethat sent the frame),frame(the frame that was sent).cancel_transmit(frame): This cancels a pending transmission of a frame.
If the frame has been sent, this has no effect.APRS Traffic handlingTheAX25Interfacejust deals in AX.25 traffic, and does not provide any
special handling of APRS UI frames. For this, one may look atAPRSInterface.Import this fromaioax25.aprs. It too, is a subclass ofRouter, and sobind,unbindandreceived_msgare there -- the messages received will
be instances ofAPRSFrame(seeaioax25.aprs.frame), otherwise the behaviour
is identical.aprsint=APRSInterface(ax25int=ax25int,# Your AX25Interface objectmycall='VK4MSL-9',# Your call-sign and SSIDlog=logging.getLogger('your.aprs.log'))Other optional parameters:retransmit_count,retransmit_timeout_base,retransmit_timeout_rand,retransmit_timeout_scale: These control the timing of retransmissions
when sendingconfirmableAPRS messages. Before transmission, a time-out
is computed astimeout = retransmit_timeout_base + (random.random() * retransmit_timeout_rand), and a retry counter is initialised toretransmit_count. On each re-transmission, the retry counter is
decremented and the timeout is multiplied byretransmit_timeout_scale.aprs_destination: This sets the destination call-sign used for APRS
traffic. Right now, we use the experimental call ofAPZAIOfor all
traffic except direct messages (which instead are sent directly to the
station addressed).aprs_pathspecifies the digipeater path to use when sending APRS traffic.listen_destinationsis a list of AX.25 destinations. Behind the scenes,
these are values passed toRouter.bind, and thus are given asdicts of
the form:{callsign: "CALL", regex: True/False, ssid: None/int}.Setting
this may break reception of MICe packets!listen_altnetsis an additional list of AX.25 destinations, given using
the same scheme aslisten_destinations.Setting this may break
reception of MICe packets!msgid_modulosets the modulo value used when generating a message ID.
The default value (1000) results in a message ID that starts at 1 and wraps
around at 999.deduplication_expirysets the number of seconds we store message hashes
for de-duplication purposes. The default is 28 seconds.To send APRS messages, there issend_messageandsend_response:send_message(addressee, path=None, oneshot=False, replyack=False):
This sends an APRS message to the addressed station. IfpathisNone,
then theaprs_pathis used. Ifoneshot=True, then the message is sent
without a message ID, no ACK/REJ is expected and no retransmissions will be
made, the method returnsNone. Otherwise, aAPRSMessageHandler(fromaioax25.aprs.message) is returned.Ifreplyackis set toTrue, then the message will advertisereply-ackcapability to
the recipient. Not all APRS implementations support this.Ifreplyackreferences an incoming message which itself hasreplyackset (either toTrueor to a previous message ID), then the outgoing
message will have a reply-ack suffix appended to "ack" the given message.The default ofreplyack=Falsedisables all reply-ack capability (an
incoming reply-ack message will still be treated as an ACK however).send_response(message, ack=True): This is used when you have received
a message from another station -- passing that message to this function
will send aACKorREJmessage to that station.TheAPRSMessageHandlerclassTheAPRSMessageHandlerclass implements the APRS message retransmission
logic. The objects have adonesignal which is emitted upon any of the
following events:Message time-out (no ACK/REJ received) (state=HandlerState.TIMEOUT)Message was cancelled (via thecancel()method)
(state=HandlerState.CANCEL)An ACK or REJ frame was received (state=HandlerState.SUCCESSorstate=HandlerState.REJECT)The signal will call call-back functions with the following keyword arguments:handler: TheAPRSMessageHandlerobject emitting the signalstate: The state of theAPRSMessageHandlerobject.TAPR TNC2 packet formatSometimes, you need the incoming packet in TAPR TNC2 format, notably for
APRS-IS interaction. This is somewhat experimental inaioax25as no one
seems to have a definition of what "TNC2 format" is.AllAX25Frameinstances implementtnc2property, which returns the frame in
a hopefully TNC2-compatible format. For UI frames, which may be encoded in a
number of different formats, there is also aget_tnc2method, which accepts
arguments that are passed tobytes.decode(); the default is to decode the
payload as ISO-8859-1 since this preserves the byte values losslessly.APRS Digipeatingaioax25includes a module that implements basic digipeating for APRS
including handling of theWIDEn-NSSIDs. The implementation treatsWIDElikeTRACE: inserting the station's own call-sign in the path (which I
believe is more compliant with theAmateur License Conditions
Determinationin that it
ensures each digipeater "identifies" itself).Theaioax25.aprs.uidigimodule can be configured to digipeat for other
aliases such as the legacyWIDEandRELAY, or any alias of your choosing.It is capable of handling multiple interfaces, but will repeat incoming
messages on the interface they were received fromONLY. (i.e. if you connect
a 2m interface and a HF interface, it willNOTdigipeat from HF to 2m).Set-up is pretty simple:from aioax25.aprs.uidigi import APRSDigipeater
# Given an APRSInterface class (aprsint)
# Create a digipeater instance
digipeater = APRSDigipeater()
# Connect your interface
digipeater.connect(aprsint)
# Optionally add any aliases you want handled
digipeater.addaliases('WIDE', 'GATE')You're now digipeating. The digipeater will automatically handleWIDEn-NandTRACEn-N, and in the above example, will also digipeat forWIDE,GATE.Preventing message loops on busy networksIf you have alotof digipeaters in close proximity (say about 6) and there's
a lot of traffic, you can get the situation where a message queued up to be
digipeated sits in the transmit queue longer than the 28 seconds needed for
other digipeaters to "forget" the message.This leads to a network with the memory of an elephant, it almost never forgets
a message because the digipeats come more than 30 secondsafterthe original.TheAPRSDigipeaterclass constructor can take a single parameter,digipeater_timeout, which sets an expiry (default of 5 seconds) on queued
digipeat messages. If a message is not sent by the time this timeout expires,
the message is quietly dropped, preventing the memory effect. |
aioayla | Provides very basic read capabilities of device data from the Ayla IoT platform. |
aioazure | Failed to fetch description. HTTP Status Code: 404 |
aioazuredevops | aioazuredevopsGet data from the Azure DevOps API using aiohttp.LinksContribution GuidelinesCode of Conduct |
aiob | AIOBAll In One Bridge for your DatasExplore the docs »📜 TOCTable of Contents🌟 Badges💡 Introduction✨ Features🎏 Getting Started🗺️ Roadmap❓ Faq💌 Contributing🙏 Acknowledgment📖 License📧 Contact🌟 Badges💡 IntroductionUnfortunately, AIOB is still under initial development and hasn't been prepared for users.Several embeded sources/destinations will be added until the very first official release. Salient changes might be made to optimize project structures and so on.Please wait until version 0.1.0 is published.(back to top)✨ Features(back to top)🎏 Getting StartedClick Here to Get Started Instantly.TODO.Installation(back to top)Command Line Interface(back to top)Configuration(back to top)Plugin System(back to top)🗺️ RoadmapPlease check out ourGithub Project.See theopen issuesfor a full list of proposed features (and known issues).(back to top)❓ FAQ(back to top)💌 ContributingContributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make aregreatly appreciated.If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement".
Don't forget to give the project a star! Thanks again!Fork the ProjectCreate your Feature Branch (git checkout -b feature/AmazingFeature)Commit your Changes (git commit -m 'Add some AmazingFeature')Push to the Branch (git push origin feature/AmazingFeature)Open a Pull RequestDon't forget to see ourContributing Guidelinefor details.(back to top)🙏 AcknowledgmentThere are various open source projects that AIOB depends on, without which this tool wouldn't exist. Credits to them!Listtinydb, MIT LicenseDynaconf, MIT Licenseaiofiles, Apache License 2.0python-frontmatter, MIT Licensetyper, MIT Licenseaiohttp, Apache License 2.0importlib_metadata, Apache License 2.0(back to top)📖 LicenseDistributed under the Apache License 2.0. SeeLICENSEfor more information.(back to top)📧 ContactClouder0's email:[email protected] Link:https://github.com/Clouder0/AIOB(back to top) |
aiob2 | aiob2aiob2 is an asynchronous API wrapper for theBackblaze B2 Bucket API.It will allow you to interact with your B2 bucket, it's files and anything else that the B2 API allows in a modern, object-oriented fashion.NOTE:There are API endpoints left to implement, eventually they will be added. To speed up this process you can submit apull requestorsuggest it.Installationaiob2 is compatible with Python 3.8+ (this is an estimate). To install aiob2, run the following command in your (virtual) environment.pipinstallaiob2Alternatively, for the latest though least stable version, you can download it from the GitHub repo:pipinstallgit+https://github.com/Void-ux/aiob2.gitUsageUploadingimportaiohttpimportasynciofromaiob2importClient# Our image to upload to our bucketwithopen(r'C:\Users\MS1\Pictures\Camera Roll\IMG_5316.jpeg','rb')asfile:data=file.read()asyncdefmain():asyncwithClient('key_id','key')asclient:file=awaitclient.upload_file(content_bytes=data,file_name='test.jpg',bucket_id='bucket_id',)if__name__=='__main__':asyncio.run(main())And that's it!upload_file()returns aFileobject that neatly wraps everything Backblaze's API has provided us with.
TheFileobject's documentation can be foundhereLicenseThis project is released under theMIT License. |
aio-background | aio-backgroundv0.0.9 (2022-11-18)[Support python 3.11]v0.0.8 (2022-08-09)De-synchronize periodic jobs started at the same time |
aiobafi6 | aiobafi6aiobafi6 is a python library to discovery, query and controlBig Ass Fansproducts that use the i6 protocol, which
includes i6 fans and Haiku fans with the 3.0 firmware.It supports almost all the features of the previous protocol ("SenseMe"), with
the exception of rooms, and sleep mode. Occupancy support was added in the 3.1 firmware.Command lineThe aiobafi6 package comes with a minimal command line (aiobafi6) that uses
either the library or direct communication with a target device. It is useful
for debugging and interacting with the firmware. Run with--helpfor usage.Compiling the aiobafi6 protocol bufferThe BAF i6 protocol usesprotocol buffersfor message
wire serialization. This library maintains asingle proto filewith all known messages and constants.The generated Python client for this proto file is checked in the repo to avoid
depending on the protocol buffer compiler for installation. Whenever the source
proto file is changed, the Python client files must be re-generated.poe protocSpecial thanks@bdracofor writing the HASS integration, helping with
Python, and suggesting BAF is using protobufs.@oogjefor a reference homebridge implementation.Big Ass Fansfor making great products. |
aiobaidu | No description available on PyPI. |
aio-baidu | No description available on PyPI. |
aiobalaboba | aiobalabobaAsynchronous wrapper forYandex Balaboba(Яндекс Балабоба).Synchronous versionhere.DisclaimerThe neural network doesn’t really know what it’s saying, so it can say absolutely anything. Don’t get offended if it says something that hurts your feelings. When sharing the texts, make sure they’re not offensive or violate the law.Installationpython-mpipinstall-UaiobalabobaDocumentationhttps://aiobalaboba.readthedocs.io/LicenseMIT |
aiobananas | Banana Python SDKGetting StartedInstall via pippip3 install aiobananasGet your API KeySign in / log in hereRun:importaiobananasapi_key="demo"# "YOUR_API_KEY"model_key="carrot"# "YOUR_MODEL_KEY"model_inputs={# a json specific to your model. For example:"imageURL":"https://demo-images-banana.s3.us-west-1.amazonaws.com/image2.jpg"}asyncwithaiobananas.Session(api_key)asbanana:out=awaitbanana.run(model_key,model_inputs)out=banana.run(api_key,model_key,model_inputs)print(out)Return type:{"id":"12345678-1234-1234-1234-123456789012","message":"success","created":1649712752,"apiVersion":"26 Nov 2021","modelOutputs":[{# a json specific to your model. In this example, the caption of the image"caption":"a baseball player throwing a ball"}]}Parse the server output:model_out=out["modelOutputs"][0] |
aiobaseclient | aiobaseclient |
aiobasex | UNKNOWN |
aiobastion | aiobastionaiobastionis a simple and fully asynchronous framework forCyberark APIwritten in Python 3.11 withasyncioandaiohttp.
It helps you to manage your Cyberark implementation faster and in an intuitive way.ExamplesSeeexamples of usagein thedocumentationQuick (and dirty) startList safesHere's a minimal python snippet to list safesimportaiobastionimportasynciofromaiobastionimportGetTokenExceptionasyncdefmain():# Define your PVWA host herepvwa_host="pvwa.mycompany.fr"vault=aiobastion.EPV(serialized={'api_host':pvwa_host})# Define login and passwordlogin=input("Login: ")password=input("Password: ")# Login to the PVWAtry:awaitvault.login(login,password)exceptGetTokenExceptionaserr:print(f"An error occured while login :{err}")awaitvault.close_session()exit(0)# Working with PVWAasyncwithvaultasepv:# For example, listing all safessafes=awaitepv.safe.list()forsinsafes:print(s)if__name__=='__main__':asyncio.run(main())Getting startedDefine a config file, and start using functions to avoid spending hours in annoying tasks in the PVWA :Accounts manipulationSafe manipulationUser manipulationCheck the documentation for moreDocumentationThe documention is hosted on readthedocs :https://aiobastion.readthedocs.io/en/latest/index.htmlRationaleI've been working on Cyberark projects for years and I see everywhere a profusion of scripts, very often complicated and long to execute for very simple tasks (sometimes even with a "do not turn off" post-it on the screen).
This package makes it quick and easy to accomplish without having to deal with the specifics of the Cyberark API.
The acquisition time may be longer than for other well-known libraries, but, believe me, you will save this time very quickly. |
aiobcrypt | aiobcrypt is a library/wrapper for asynchronous bcrypt hashing. This is just an wrapper around bcrypt in order to make it asynchronous. |
aiobdb | aiobdbDevelopment status: planningCreditsThis package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.History0.0.1dev1 (2016-08-20)Planning release on PyPI. |
aiobeanstalk | UNKNOWN |
aio-beanstalk | UNKNOWN |
aiobearychat | BearyChat异步 Python SDKFree software: MIT licenseDocumentation:https://aiobearychat.readthedocs.orgGitHub:https://github.com/mozillazg/aiobearychatPyPI:https://pypi.python.org/pypi/aiobearychatPython version: 3.5, 3.6Features封装所有的 OpenAPI封装所有的 RTM HTTP API支持不同的异步 HTTP 请求模块(aiohttp, tornado, …)InstallationAt the command line:$ pip install aiobearychat[aiohttp]UsageOpenAPIimportaiohttpfromaiobearychat.openapi.aiohttpimportOpenAPIasyncdefmain(token):asyncwithaiohttp.ClientSession()assession:api=OpenAPI(session,token=token)response=awaitapi.user.list()print(response.json())RTM HTTP APIimportaiohttpfromaiobearychat.rtm.aiohttpimportRtmAPIasyncdefmain(token):asyncwithaiohttp.ClientSession()assession:api=RtmAPI(session,token=token)response=awaitapi.start()pprint(response.json())CreditsThis package was created withCookiecutterand themozillazg/cookiecutter-pypackageproject template. |
aiobernhard | UNKNOWN |
aiobestproxiesapi | No description available on PyPI. |
aiobfd | UNKNOWN |
aiobgjobs | AIOBGJOBS DOCSEn - docsThis library is designed for asynchronous
execution of scheduled tasks.Simple example:importasyncioimportdatetimefromaiobgjobs.dispatcherimportBgDispatcherfromaiobgjobs.typesimportEvery,Repeatsbg_dp=BgDispatcher()@bg_dp.handler_job(every=Every.seconds(15),count_repeats=3)asyncdefsimple_func_every_second():print('Test')@bg_dp.handler_job(every=Every.weekdays.monday(hour=11,minute=40),count_repeats=Repeats.infinity)asyncdefsimple_func_infinity_monday():print('Test2')@bg_dp.handler_job(every=Every.minutes(2),count_repeats=Repeats.infinity)asyncdefsimple_func_every_2_minutes():print('Test3')@bg_dp.handler_job(count_repeats=Repeats.one,datetime_start=datetime.timedelta(minutes=2.0))asyncdefsimple_func_delta_to_start():print('Test4')asyncdefmain():awaitasyncio.create_task(bg_dp.start(relax=.3))if__name__=='__main__':loop=asyncio.new_event_loop()try:loop.run_until_complete(main())exceptKeyboardInterrupt:print('Goodbye!')Example without using decorators:importasyncioimportdatetimefromaiobgjobs.dispatcherimportBgDispatcherfromaiobgjobs.handlersimportHandlerfromaiobgjobs.jobsimportJobfromaiobgjobs.typesimportEvery,Repeatsbg_dp=BgDispatcher()asyncdefsimple_func_every_seconds():print('Test')asyncdefsimple_func_infinity_monday():print('Test2')asyncdefsimple_func_every_2_minutes():print('Test3')asyncdefsimple_func_delta_to_start():print('Test4')bg_dp.register_handler(Handler(job=Job(func=simple_func_every_seconds,name='Job - 1',kwargs=None),count_repeats=3,every=Every.seconds(15)))bg_dp.register_handler(Handler(job=Job(func=simple_func_infinity_monday,name='Job - 2',kwargs=None),count_repeats=Repeats.infinity,every=Every.weekdays.monday()))bg_dp.register_handler(Handler(job=Job(func=simple_func_every_2_minutes,name='Job - 3',kwargs=None),count_repeats=Repeats.infinity,every=Every.minutes(2)))bg_dp.register_handler(Handler(job=Job(func=simple_func_delta_to_start,name='Job - 4',kwargs=None),count_repeats=Repeats.one,datetime_start=datetime.timedelta(minutes=2)))asyncdefmain():awaitasyncio.create_task(bg_dp.start(relax=.3))if__name__=='__main__':loop=asyncio.new_event_loop()try:loop.run_until_complete(main())exceptKeyboardInterrupt:print('Goodbye!')Ru - docsЭта библиотека предназначена для асинхронного
выполнения задач по расписанию.Простой пример:importasyncioimportdatetimefromaiobgjobs.dispatcherimportBgDispatcherfromaiobgjobs.typesimportEvery,Repeatsbg_dp=BgDispatcher()@bg_dp.handler_job(every=Every.seconds(15),count_repeats=3)asyncdefsimple_func_every_second():print('Test')@bg_dp.handler_job(every=Every.weekdays.monday(hour=11,minute=40),count_repeats=Repeats.infinity)asyncdefsimple_func_infinity_monday():print('Test2')@bg_dp.handler_job(every=Every.minutes(2),count_repeats=Repeats.infinity)asyncdefsimple_func_every_2_minutes():print('Test3')@bg_dp.handler_job(count_repeats=Repeats.one,datetime_start=datetime.timedelta(minutes=2.0))asyncdefsimple_func_delta_to_start():print('Test4')asyncdefmain():awaitasyncio.create_task(bg_dp.start(relax=.3))if__name__=='__main__':loop=asyncio.new_event_loop()try:loop.run_until_complete(main())exceptKeyboardInterrupt:print('Goodbye!')Пример без использования декораторов:importasyncioimportdatetimefromaiobgjobs.dispatcherimportBgDispatcherfromaiobgjobs.handlersimportHandlerfromaiobgjobs.jobsimportJobfromaiobgjobs.typesimportEvery,Repeatsbg_dp=BgDispatcher()asyncdefsimple_func_every_seconds():print('Test')asyncdefsimple_func_infinity_monday():print('Test2')asyncdefsimple_func_every_2_minutes():print('Test3')asyncdefsimple_func_delta_to_start():print('Test4')bg_dp.register_handler(Handler(job=Job(func=simple_func_every_seconds,name='Job - 1',kwargs=None),count_repeats=3,every=Every.seconds(15)))bg_dp.register_handler(Handler(job=Job(func=simple_func_infinity_monday,name='Job - 2',kwargs=None),count_repeats=Repeats.infinity,every=Every.weekdays.monday()))bg_dp.register_handler(Handler(job=Job(func=simple_func_every_2_minutes,name='Job - 3',kwargs=None),count_repeats=Repeats.infinity,every=Every.minutes(2)))bg_dp.register_handler(Handler(job=Job(func=simple_func_delta_to_start,name='Job - 4',kwargs=None),count_repeats=Repeats.one,datetime_start=datetime.timedelta(minutes=2)))asyncdefmain():awaitasyncio.create_task(bg_dp.start(relax=.3))if__name__=='__main__':loop=asyncio.new_event_loop()try:loop.run_until_complete(main())exceptKeyboardInterrupt:print('Goodbye!') |
aiobiketrax | aiobiketraxPython library for interacting with the PowUnity BikeTrax GPS tracker.IntroductionThis library is mainly written to work with a custom component for
Home Assistant. You can find this custom componenthere.ThePowUnity BikeTraxis a GPS tracker for electric
bicycles. It provides real-time updates every when the bike is in motion, using
a 2G modem. It works in Europe, and requires a subscription after a trial
period of one year.FeaturesMulti-device support.Traccar and admin API support.Live updates using websocket.Not implemented:Geofencing.Global configuration, such as webhooks.Known issuesTheschemasof the models haven been
reversed-engineerd by observing responses for a small number of devices. It is
likely that responses of other devices do not map onto the current models. For
example, some properties are not set if they have never been configured from
the app.Please open an issue, and provide some responses so that the schemas can be
improved. Be sure to redact sensitive information, such as locations, unique
identifiers and personal details.DebuggingIn case of issues, it is possible to enable logging in your application for the
following loggers:aiobiketrax.api- API logging.aiobiketrax.api.responses- Additional API response logging.aiobiketrax.api.client- Client interaction logging.UsageIn codefromaiobiketraximportAccountimportaiohttpasyncwithaiohttp.ClientSession()assession:account=Account(username="[email protected]",password="secret",session=session)awaitaccount.update_devices()fordeviceinaccount.devices:print(device.name)CLIFor demonstration and testing purposes, one can use the CLI as well. If you
have the package installed, usebiketrax --helpcommand to get started.Mock serverFor development, a mock server is included incontrib/mock/. Simply runserver.pyand adaptaiobiketrax/consts.pyto use other endpoints.API_TRACCAR_ENDPOINT="http://localhost:5555/traccar/api"API_ADMIN_ENDPOINT="http://localhost:5555/admin/api"Do note that authentication is not mocked.ContributingSee theCONTRIBUTING.mdfile.LicenseSee theLICENSE.mdfile (MIT license).DisclaimerUse this library at your own risk. I cannot be held responsible for any
damages.This page and its content is not affiliated with PowUnity. |
aiobinance | No description available on PyPI. |
aio-binance-library | aio-binance-libraryAsync library for connecting to the Binance API on PythonThis is a lightweight library that works as a connector toBinance Futures public APISupported APIs:USDT-M Futures `/fapi/*``Futures/Delivery Websocket Market StreamFutures/Delivery User Data StreamInclusion of examplesResponse metadata can be displayedInstallationpipinstallaio-binance-libraryGetting startedREST APIUsage examples:importasynciofromaio_binance.futures.usdtimportClientasyncdefmain():client=Client()res=awaitclient.get_public_time()print(res)client=Client(key='<api_key>',secret='<api_secret>')# Get account informationres=awaitclient.get_private_account_info()print(res)# Post a new orderparams={'symbol':'BTCUSDT','side':'SELL','type_order':'LIMIT','time_in_force':'GTC','quantity':0.002,'price':59808}res=awaitclient.create_private_order(**params)print(res)asyncio.run(main())Or you can use session (For multiple requests, this acts faster):importasynciofromaio_binance.futures.usdtimportApiSessionasyncdefmain():asyncwithApiSession(key='<api_key>',secret='<api_secret>')assession:res=awaitsession.get_public_time()print(res)# Get account informationres=awaitsession.get_private_account_info()print(res)# Post a new orderparams={'symbol':'BTCUSDT','side':'SELL','type_order':'LIMIT','time_in_force':'GTC','quantity':0.002,'price':59808}res=awaitsession.create_private_order(**params)print(res)asyncio.run(main())Please findexamplesfolder to check for more endpoints.NotesThe methods you need, adheres to a hierarchy<method>_<availability>_<method_name>
create_private_order()
or
get_public_time()Methods:create, get, delete, change, updateAvailability:private- methods where key_api and secret_api are requiredpublic- you can get information without a keyTestnetYou can choose testnetfromaio_binance.futures.usdtimportClientclient=Client(testnet=True)Optional parametersParameters can be passed in different formats as in Binance api documents or PEP8 suggestslowercase with words separated by underscores# Binance apiresponse=awaitclient.get_private_open_order('BTCUSDT',orderListId=1)# PEP8response=awaitclient.get_private_open_order('BTCUSDT',order_list_id=1)Timeouttimeoutis available to be assigned with the number of seconds you find most appropriate to wait for a server response.Please remember the value as it won't be shown in error messageno bytes have been received on the underlying socket for timeout seconds.By default,timeout=5fromaio_binance.futures.usdtimportClientclient=Client(timeout=1)Response MetadataThe Binance API server provides weight usages in the headers of each response.
You can display them by initializing the client withshow_limit_usage=True:fromaio_binance.futures.usdtimportClientclient=Client(show_limit_usage=True)res=awaitclient.time()print(res)returns:{'data':{'serverTime':1647990837551},'limit_usage':40}You can also display full response metadata to help in debugging:client=Client(show_header=True)res=awaitclient.time()print(res)returns:{'data':{'serverTime':1587990847650},'header':{'Context-Type':'application/json;charset=utf-8',...}}User agentclient=Client(agent='name_app')You can pass the name of your application.WebsocketThis is an example of connecting to multiple streamsimportasynciofromaio_binance.futures.usdtimportWsClientasyncdefcallback_event(data:dict):print(data)asyncdefmain():ws=WsClient()stream=[ws.stream_liquidation_order(),ws.stream_book_ticker(),ws.stream_ticker('BTCUSDT')]res=awaitasyncio.gather(*stream)awaitws.subscription_streams(res,callback_event)asyncio.run(main())More websocket examples are available in theexamplesfolderNoteStream methods start with the wordstreamExample:stream_<name_method>Subscribing to multiple streams:subscription_streams()HeartbeatOnce connected, the websocket server sends a ping frame every 3 minutes and requires a response pong frame back within
a 5 minutes period. This package handles the pong responses automatically. |
aiobitcoin | No description available on PyPI. |
aiobitmex | No description available on PyPI. |
aio-bitrix | No description available on PyPI. |
aiobitrix24 | AIOBitrix24 |
aiobittrex | Requirements: Python3.6Installation:pip install aiobittrexUsageimportasynciofromaiobittreximportBittrexAPI,BittrexApiError,BittrexResponseErrorasyncdefmain():api=BittrexAPI()try:result=awaitapi.get_markets()exceptBittrexApiErrorase:print(e)exceptBittrexResponseErrorase:print('Invalid response:',e)else:print(result)finally:awaitapi.close()V1 APIget_markets()Get the open and available trading markets at Bittrex along with other meta data.[{"MarketCurrency":"LTC","BaseCurrency":"BTC","MarketCurrencyLong":"Litecoin","BaseCurrencyLong":"Bitcoin","MinTradeSize":0.01441756,"MarketName":"BTC-LTC","IsActive":true,"Created":"2014-02-13T00:00:00","Notice":null,"IsSponsored":null,"LogoUrl":"https://bittrexblobstorage.blob.core.windows.net/public/6defbc41-582d-47a6-bb2e-d0fa88663524.png"}]get_currencies()Get all supported currencies at Bittrex along with other meta data.[{"Currency":"BTC","CurrencyLong":"Bitcoin","MinConfirmation":2,"TxFee":0.0005,"IsActive":true,"CoinType":"BITCOIN","BaseAddress":"1N52wHoVR79PMDishab2XmRHsbekCdGquK","Notice":null}]get_ticker(market)Get the current tick values for a market.{"Bid":0.01702595,"Ask":0.01709242,"Last":0.01702595}get_market_summaries()Get the last 24 hour summary of all active markets.[{"MarketName":"BTC-LTC","High":0.01717,"Low":0.01664,"Volume":19292.05592121,"Last":0.01709242,"BaseVolume":325.65963883,"TimeStamp":"2018-04-23T13:09:54.903","Bid":0.01702596,"Ask":0.01709242,"OpenBuyOrders":1957,"OpenSellOrders":4016,"PrevDay":0.016837,"Created":"2014-02-13T00:00:00"}]get_market_summary(market)Get the last 24 hour summary of a specific market.{"MarketName":"BTC-LTC","High":0.01717,"Low":0.01664,"Volume":19298.50773759,"Last":0.017092,"BaseVolume":325.76997876,"TimeStamp":"2018-04-23T13:12:20.447","Bid":0.017092,"Ask":0.01709242,"OpenBuyOrders":1957,"OpenSellOrders":4018,"PrevDay":0.01687339,"Created":"2014-02-13T00:00:00"}get_order_book(market,order_type='both')Retrieve the orderbook for a given market.Order types:buysellboth{"buy":[{"Quantity":0.56636808,"Rate":0.01709205}],"sell":[{"Quantity":67.07309757,"Rate":0.01709242}]}get_market_history(market)Retrieve the latest trades that have occurred for a specific market.[{"Id":159594115,"TimeStamp":"2018-04-23T12:59:56.333","Quantity":7.08668072,"Price":0.01702576,"Total":0.12065612,"FillType":"PARTIAL_FILL","OrderType":"SELL"},{"Id":159594103,"TimeStamp":"2018-04-23T12:59:38.147","Quantity":1.60041657,"Price":0.01709242,"Total":0.02735499,"FillType":"FILL","OrderType":"BUY"}]buy_limit(market, quantity, rate)Place a buy order.{"uuid":"614c34e4-8d71-11e3-94b5-425861b86ab6"}sell_limit(market, quantity, rate)Place a sell order.{"uuid":"614c34e4-8d71-11e3-94b5-425861b86ab6"}cancel_order(order_id)Cancel a buy or sell order.get_open_orders(market=None)Get open orders, a market can be specified.[{"Uuid":null,"OrderUuid":"09aa5bb6-8232-41aa-9b78-a5a1093e0211","Exchange":"BTC-LTC","OrderType":"LIMIT_SELL","Quantity":5.00000000,"QuantityRemaining":5.00000000,"Limit":2.00000000,"CommissionPaid":0.00000000,"Price":0.00000000,"PricePerUnit":null,"Opened":"2014-07-09T03:55:48.77","Closed":null,"CancelInitiated":false,"ImmediateOrCancel":false,"IsConditional":false,"Condition":null,"ConditionTarget":null}]get_balances()Retrieve all balances for the account.[{"Currency":"BSD","Balance":0.0,"Available":0.0,"Pending":0.0,"CryptoAddress":null},{"Currency":"BTC","Balance":6e-08,"Available":6e-08,"Pending":0.0,"CryptoAddress":"1JQts7UT3gYTs31p6k5YGj3qjcRQ6XAXsn"}]get_balance(currency)Retrieve balance for specific currency.{"Currency":"BTC","Balance":6e-08,"Available":6e-08,"Pending":0.0,"CryptoAddress":"1JQts7UT3gYTs31p6k5YGj3qjcRQ6XAXsn"}get_deposit_address(currency)Retrieve or generate an address for a specific currency.{"Currency":"BTC","Address":"1JQts7UT3gYTs31p6k5YGj3qjcRQ6XAXsn"}withdraw(currency, quantity, address)Withdraw funds from the account.{"uuid":"68b5a16c-92de-11e3-ba3b-425861b86ab6"}get_order(order_id)Retrieve a single order by uuid.{"AccountId":null,"OrderUuid":"0cb4c4e4-bdc7-4e13-8c13-430e587d2cc1","Exchange":"BTC-SHLD","Type":"LIMIT_BUY","Quantity":1000.00000000,"QuantityRemaining":1000.00000000,"Limit":0.00000001,"Reserved":0.00001000,"ReserveRemaining":0.00001000,"CommissionReserved":0.00000002,"CommissionReserveRemaining":0.00000002,"CommissionPaid":0.00000000,"Price":0.00000000,"PricePerUnit":null,"Opened":"2014-07-13T07:45:46.27","Closed":null,"IsOpen":true,"Sentinel":"6c454604-22e2-4fb4-892e-179eede20972","CancelInitiated":false,"ImmediateOrCancel":false,"IsConditional":false,"Condition":"NONE","ConditionTarget":null}get_order_history(market=None)Retrieve order history.[{"OrderUuid":"fd97d393-e9b9-4dd1-9dbf-f288fc72a185","Exchange":"BTC-LTC","TimeStamp":"2014-07-09T04:01:00.667","OrderType":"LIMIT_BUY","Limit":0.00000001,"Quantity":100000.00000000,"QuantityRemaining":100000.00000000,"Commission":0.00000000,"Price":0.00000000,"PricePerUnit":null,"IsConditional":false,"Condition":null,"ConditionTarget":null,"ImmediateOrCancel":false}]get_withdrawal_history(currency=None)Retrieve the account withdrawal history.[{"PaymentUuid":"88048b42-7a13-4f57-8b7e-109aeeca07d7","Currency":"SAFEX","Amount":803.7676899,"Address":"145J9p6AVjFc2fFV1uyA8d4xweULphyuNv","Opened":"2018-02-20T13:54:41.12","Authorized":true,"PendingPayment":false,"TxCost":100.0,"TxId":"e1ded8356d2855716ba99ae6b8cbd2c4220a8df15dd37fd7eb29a76dd7a0b1d1","Canceled":false,"InvalidAddress":false}]get_deposit_history(currency=None)Retrieve the account deposit history.[{"Id":41565639,"Amount":0.008,"Currency":"BTC","Confirmations":3,"LastUpdated":"2017-11-20T16:40:30.6","TxId":"abfec55561b5440b28784dc4b152635c05139f33faec090a3d8e18a8d2c75eec","CryptoAddress":"1JQts7UT3gYTs31p6k5YGj3qjcRQ6XAXsn"}]V2 APIget_wallet_health()View wallets health.[{"Health":{"Currency":"BTC","DepositQueueDepth":0,"WithdrawQueueDepth":24,"BlockHeight":519583,"WalletBalance":0.0,"WalletConnections":8,"MinutesSinceBHUpdated":2,"LastChecked":"2018-04-23T13:50:11.827","IsActive":true},"Currency":{"Currency":"BTC","CurrencyLong":"Bitcoin","MinConfirmation":2,"TxFee":0.0005,"IsActive":true,"CoinType":"BITCOIN","BaseAddress":"1N52wHoVR79PMDishab2XmRHsbekCdGquK","Notice":null}}]get_pending_withdrawals(currency=None)Get the account pending withdrawals.get_pending_deposits(currency=None)Get the account pending deposits.get_candles(market, tick_interval)Get tick candles for market.Intervals:oneMinfiveMinhourday[{"O":0.017059,"H":0.01712003,"L":0.017059,"C":0.017059,"V":49.10766337,"T":"2018-04-23T14:07:00","BV":0.83816494}]get_latest_candle(market, tick_interval)Get the latest candle for the market.{"O":0.017125,"H":0.017125,"L":0.01706,"C":0.017125,"V":2.35065452,"T":"2018-04-23T14:09:00","BV":0.04018997}SocketBittrex socket documentation:https://bittrex.github.io/Usage example:fromaiobittreximportBittrexSocketsocket=BittrexSocket()market=awaitsocket.get_market(markets=['BTC-ETH','BTC-TRX'])print(json.dumps(market,indent=2))asyncforminsocket.listen_market(markets=['BTC-ETH','BTC-TRX']):print(json.dumps(m,indent=2))`listen_account()`Listen for orders and balances updates for the account.`get_market(markets)`Get market orders.{"BTC-TRX":{"market_name":null,"nonce":11333,"buys":[{"quantity":428996.57288094,"rate":8.65e-06}],"sells":[{"quantity":91814.92314615,"rate":8.66e-06}],"fills":[{"id":5020055,"time_stamp":1524904823903,"quantity":34413.0,"price":8.66e-06,"total":0.29801658,"fill_type":"FILL","order_type":"BUY"}]}}`listen_market(markets)`Listen for market orders updates.Delta types:0 = ADD1 = REMOVE2 = UPDATE{"market_name":"BTC-TRX","nonce":11919,"buys":[],"sells":[{"type":2,"rate":8.7e-06,"quantity":197473.52148216}],"fills":[{"order_type":"BUY","rate":8.7e-06,"quantity":28376.84449489,"time_stamp":1524905878547}]}`get_summary()`Get markets summaries.{"nonce":5108,"summaries":[{"market_name":"BTC-ADA","high":3.388e-05,"low":3.116e-05,"volume":45482116.6444527,"last":3.337e-05,"base_volume":1481.80378307,"time_stamp":1524907023543,"bid":3.333e-05,"ask":3.337e-05,"open_buy_orders":5195,"open_sell_orders":15219,"prev_day":3.118e-05,"created":1506668518873}]}`listen_summary_light()`Markets summary updates light.{"deltas":[{"market_name":"BTC-ADT","last":7.37e-06,"base_volume":118.05}]}`listen_summary()`Markets summary updates.{"nonce":5069,"deltas":[{"market_name":"BTC-ETH","high":0.07371794,"low":0.071695,"volume":9535.44197173,"last":0.07318011,"base_volume":695.21677418,"time_stamp":1524907827823,"bid":0.07318011,"ask":0.07346991,"open_buy_orders":4428,"open_sell_orders":3860,"prev_day":0.07188519,"created":1439542944817}]} |
aiobittrexapi | Python Async Bittrex API WrapperThis package is used by the Bittrex integration of Home Assistant.Available functionsThe following functions are available:fromaiobittrexapiimportBittrexapi=Bittrex(api_key,api_secret)api.get_account()api.get_balances()api.get_closed_orders()api.get_markets()api.get_open_orders()api.get_tickers()ExamplefromaiobittrexapiimportBittrexfromaiobittrexapi.errorsimport(BittrexApiError,BittrexResponseError,BittrexInvalidAuthentication,)importasynciofromtypingimportOptionalAPI_KEY=""API_SECRET=""asyncdefmain(api_key:Optional[str]=None,api_secret:Optional[str]=None):ifapi_keyandapi_secret:api=Bittrex(api_key,api_secret)else:api=Bittrex()try:# Get the active markets from Bittrex - works without secret & keymarkets=awaitapi.get_markets()print(markets)# Get the tickerstickers=awaitapi.get_tickers()print(tickers)# Get your account data - requires secret & keyaccount=awaitapi.get_account()exceptBittrexApiErrorase:print(e)exceptBittrexResponseErrorase:print("Invalid response:",e)exceptBittrexInvalidAuthentication:print("Invalid authentication. Please provide a correct API Key and Secret")else:print(account)finally:awaitapi.close()if__name__=="__main__":loop=asyncio.get_event_loop()ifAPI_KEYandAPI_SECRET:loop.run_until_complete(main(API_KEY,API_SECRET))else:loop.run_until_complete(main())Feedback & Pull RequestsAll feedback and Pull Requests are welcome!DevelopmentDon't forget to create your venvpython3-mvenvvenvsourcevenv/bin/activate |
ai-object-detection | AI Object DetectionUsageInstallationRequirementsCompatibilityLicenceAuthorsai_object_detectionwas written byNhan Vo. |
aioble | No description available on PyPI. |
aioblescan | aioblescan is a Python 3/asyncio library to listen for BLE advertized
packets.InstallationWe are on PyPi sopip3 install aioblescanorpython3 -m pip install aioblescanHow to useEssentially, you create a function to process the incoming information
and you attach it to theBTScanRequester. You then create a
Bluetooth connection, you issue the scan command and wait for incoming
packets and process them.You can use Eddystone or RuuviWeather to retrieve specific informationThe easiest way is to look at the__main__.pyfile.You can run the command:aioblescanor you can run the module withpython3 -m aioblescanAdd-hfor help.To see the RuuviTag weather information try:python3 -m aioblescan -rYou will getWeather info {'rssi': -64, 'pressure': 100300, 'temperature': 24, 'mac address': 'fb:86:84:dd:aa:bb', 'tx_power': -7, 'humidity': 36.0}
Weather info {'rssi': -62, 'pressure': 100300, 'temperature': 24, 'mac address': 'fb:86:84:dd:aa:bb', 'tx_power': -7, 'humidity': 36.0}To check Eddystone beaconpython3 -m aioblescan -eYou getGoogle Beacon {'tx_power': -7, 'url': 'https://ruu.vi/#BEgYAMR8n', 'mac address': 'fb:86:84:dd:aa:bb', 'rssi': -52}
Google Beacon {'tx_power': -7, 'url': 'https://ruu.vi/#BEgYAMR8n', 'mac address': 'fb:86:84:dd:aa:bb', 'rssi': -53}To check ATC_MiThermometer withcustom
firmwarebeaconpython3 -m aioblescan -AYou getTemperature info {'mac address': 'a4:c1:38:40:52:38', 'temperature': 2.8, 'humidity': 62, 'battery': 72, 'battery_volts': 2.863, 'counter': 103, 'rssi': -76}
Temperature info {'mac address': 'a4:c1:38:40:52:38', 'temperature': 2.8, 'humidity': 62, 'battery': 72, 'battery_volts': 2.863, 'counter': 103, 'rssi': -77}To check ThermoBeacon sensorspython3 -m aioblescan -TYou getTemperature info {'mac address': '19:c4:00:00:0f:5d', 'max_temperature': 27.0625, 'min_temperature': 21.75, 'max_temp_ts': 0, 'min_temp_ts': 2309}
Temperature info {'mac address': '19:c4:00:00:0f:5d', 'temperature': 21.75, 'humidity': 49.5, 'battery_volts': 3234, 'counter': 2401, 'rssi': -67}For a generic advertise packet scanningpython3 -m aioblescanYou getHCI Event:
code:
3e
length:
19
LE Meta:
code:
02
Adv Report:
num reports:
1
ev type:
generic adv
addr type:
public
peer:
54:6c:0e:aa:bb:cc
length:
7
flags:
Simul LE - BR/EDR (Host): False
Simul LE - BR/EDR (Control.): False
BR/EDR Not Supported: False
LE General Disc.: True
LE Limited Disc.: False
Incomplete uuids:
ff:30
rssi:
-67
HCI Event:
code:
3e
length:
43
LE Meta:
code:
02
Adv Report:
num reports:
1
ev type:
no connection adv
addr type:
random
peer:
fb:86:84:dd:aa:bb
length:
31
flags:
Simul LE - BR/EDR (Host): False
Simul LE - BR/EDR (Control.): False
BR/EDR Not Supported: False
LE General Disc.: True
LE Limited Disc.: True
Complete uuids:
fe:aa
Advertised Data:
Service Data uuid:
fe:aa
Adv Payload:
10:f9:03:72:75:75:2e:76:69:2f:23:42:45:77:59:41:4d:52:38:6e
rssi:
-59Here the first packet is from a Wynd device, the second from a Ruuvi Tagaioblescan can also send EddyStone advertising. Try the -a flag when
running the module.To check Tilt hydrometerpython3 -m aioblescan --tiltYou will see the regular Bluetooth beacons from any Tilt in range:{"uuid": "a495bb40c5b14b44b5121370f02d74de", "major": 70, "minor": 1054, "tx_power": 31, "rssi": -58, "mac": "xx:xx:xx:xx:xx:xx"}
{"uuid": "a495bb40c5b14b44b5121370f02d74de", "major": 70, "minor": 1054, "tx_power": 31, "rssi": -74, "mac": "xx:xx:xx:xx:xx:xx"}
{"uuid": "a495bb40c5b14b44b5121370f02d74de", "major": 70, "minor": 1054, "tx_power": 31, "rssi": -57, "mac": "xx:xx:xx:xx:xx:xx"}Hitctrl-cto stop the scan.Interpreting the Tilt DataThe information from the tilt plugin is returned as a valid JSON:{
"uuid": "a495bb40c5b14b44b5121370f02d74de",
"major": 69,
"minor": 1056,
"tx_power": 31,
"rssi": -49,
"mac": "xx:xx:xx:xx:xx:xx"
}These keys may be interpreted as:uuid: Tilt name. The “40” in
a495bb40c5b14b44b5121370f02d74de is an indication of the
color.10: Red20: Green30: Black40: Purple50: Orange60: Blue70: Yellow80: Pinkmajor: Temp in degrees F.minor: Specific gravity x1000.tx_power: Weeks since battery change (0-152 when converted to
unsigned 8 bit integer). You will occasionally see-59which is
there to allow iOS to compute RSSI. This value should be discarded.rssi: Received Signal Strength Indication (RSSI) is a measurement
of the power present in the received radio signal. A lower negative
number is stronger.mac: Media Access Control (MAC) address of the device.FAQWhy not use scapy?Scapy is great and you can do
import scapy.all as sa
test=sa.BluetoothHCISocket(0)
command=sa.HCI_Cmd_LE_Set_Scan_Enable(enable=1,filter_dups=0)
chdr=sa.HCI_Command_Hdr(len=len(command))
hdr=sa.HCI_Hdr(type=1)
test.send(hdr / chdr / command)
to get things going. But... the great thing with Scapy is that there is so
many versions to choose from.... and not all have all the same functions ... and
installation can be haphazard, with some version not installing at all. Also
scapy inludes a lot of other protocols and could be an overkill... lastly it
is never too late to learn...What can you track?aioblescan will try to parse all the incoming advertised information. You can see
the raw data when it does not know what to do. With Eddystone beacon you can see the
URL, Telemetry and UID |
aiobloom | aiobloomasync api for bloom filter using redisInstallationpip install aiobloomtestpy.test |
aiobme280 | aiobme280is a Python 3 module to read data asynchronously from BME280
environmental sensor.Featuresasynchronous sensor data read using Python asyncio coroutines, which
allows to read multiple sensors in parallel without using threadssensor is put into sleep mode to minimize power consumption after data is
read |
aiobml | This is an asynchronous wrapper around Bank of Maldives API.How it worksCurrently you can use this library to get the transaction history of all your Bank of Maldives accounts, details of all you BML accounts & contacts and add & remove contacts.
If you want to check for new transactions; save the transactions to a db, check, alert and add any transactions that's not currently saved to the dbcheck the basic example below.Async Bank of Maldives (BML) APIThis library is not fully completed yet. As of now it can be used to get the transactions done within the last 24 - 48 hours, get all the information about your Accounts and your contacts and add & remove contacts.scroll to the end to see the to do list of this librarysetupYou must have python 3 installedusing PIP$ pip install -U aiobmlFrom Source$ git clone https://github.com/quillfires/aioBML.git$ cd aioBML$ python setup.py installBasic ExampleimportasynciofromaiobmlimportasyncBMLloop=asyncio.get_event_loop()bank=asyncBML(username="your_user_name",password="your_password")asyncdefstart_bank_client():awaitbank.start()@bank.event('new_transaction')asyncdefon_new_transaction(transaction):print(transaction)# on app reboot, event will trigger for all the transactions within 24 hours# Use a db to avoid being notified of the same transaction.# check if transaction is in your db# if not, save to db and alert about the transactionasyncdefcontacts():data=awaitbank.get_contacts()print(data)# show all the contacts you have savedasyncdefaccounts():data=awaitbank.get_accounts()print(data)# show all the accounts you have in Bank of Maldivesasyncdefadd_cont(account,name):added_acc=awaitbank.add_contact(account,name)print(added_acc)# adds the account your contact list# throws DuplicateContent error if it is already in the contact listasyncdefdelete_cont(account):awaitbank.delete_contact(account)# deletes the first match from your contact list# account can be the account number or the saved nameif__name__=='__main__':try:loop.run_until_complete(start_bank_client())except(KeyboardInterrupt,SystemExit):passfinally:loop.run_until_complete(bank.close())ChanglogSee the change log hereTodoGet todays historyGet Account detailsGet contactsAdd contactsDelete contactsGet history from a date rangeMake Transfer to a given account numberMake transfers to contacts. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.