package
stringlengths
1
122
pacakge-description
stringlengths
0
1.3M
aiothinkingcleaner
aiothinkingcleanerLibrary to communicate with a Thinking Cleaner module asynchronouslyVery first stepsInitialize your codeInitializegitinside your repo:cdaiothinkingcleaner&&gitinitIf you don't havePoetryinstalled run:makepoetry-downloadInitialize poetry and installpre-commithooks:makeinstall makepre-commit-installRun the codestyle:makecodestyleUpload initial code to GitHub:gitadd. gitcommit-m":tada: Initial commit"gitbranch-Mmain gitremoteaddoriginhttps://github.com/matthijs2704/aiothinkingcleaner.git gitpush-uoriginmainSet up botsSet upDependabotto ensure you have the latest dependencies.Set upStale botfor automatic issue closing.PoetryWant to know more about Poetry? Checkits documentation.Details about PoetryPoetry'scommandsare very intuitive and easy to learn, like:poetry add numpy@latestpoetry run pytestpoetry publish --buildetcBuilding and releasing your packageBuilding a new version of the application contains steps:Bump the version of your packagepoetry version <version>. You can pass the new version explicitly, or a rule such asmajor,minor, orpatch. For more details, refer to theSemantic Versionsstandard.Make a commit toGitHub.Create aGitHub release.And... publish 🙂poetry publish --build🎯 What's nextWell, that's up to you 💪🏻. I can only recommend the packages and articles that helped me.Typeris great for creating CLI applications.Richmakes it easy to add beautiful formatting in the terminal.Pydantic– data validation and settings management using Python type hinting.Logurumakes logging (stupidly) simple.tqdm– fast, extensible progress bar for Python and CLI.IceCreamis a little library for sweet and creamy debugging.orjson– ultra fast JSON parsing library.Returnsmakes you function's output meaningful, typed, and safe!Hydrais a framework for elegantly configuring complex applications.FastAPIis a type-driven asynchronous web framework.Articles:Open Source Guides.A handy guide to financial support for open sourceGitHub Actions Documentation.Maybe you would like to addgitmojito commit names. This is really funny. 😄🚀 FeaturesDevelopment featuresSupports forPython 3.7and higher.Poetryas the dependencies manager. See configuration inpyproject.tomlandsetup.cfg.Automatic codestyle withblack,isortandpyupgrade.Ready-to-usepre-commithooks with code-formatting.Type checks withmypy; docstring checks withdarglint; security checks withsafetyandbanditTesting withpytest.Ready-to-use.editorconfig,.dockerignore, and.gitignore. You don't have to worry about those things.Deployment featuresGitHubintegration: issue and pr templates.Github Actionswith predefinedbuild workflowas the default CI/CD.Everything is already set up for security checks, codestyle checks, code formatting, testing, linting, docker builds, etc withMakefile. More details inmakefile-usage.Dockerfilefor your package.Always up-to-date dependencies with@dependabot. You will onlyenable it.Automatic drafts of new releases withRelease Drafter. You may see the list of labels inrelease-drafter.yml. Works perfectly withSemantic Versionsspecification.Open source community featuresReady-to-usePull Requests templatesand severalIssue templates.Files such as:LICENSE,CONTRIBUTING.md,CODE_OF_CONDUCT.md, andSECURITY.mdare generated automatically.Stale botthat closes abandoned issues after a period of inactivity. (You will onlyneed to setup free plan). Configuration ishere.Semantic Versionsspecification withRelease Drafter.Installationpipinstall-Uaiothinkingcleaneror install withPoetrypoetryaddaiothinkingcleanerMakefile usageMakefilecontains a lot of functions for faster development.1. Download and remove PoetryTo download and install Poetry run:makepoetry-downloadTo uninstallmakepoetry-remove2. Install all dependencies and pre-commit hooksInstall requirements:makeinstallPre-commit hooks coulb be installed aftergit initviamakepre-commit-install3. CodestyleAutomatic formatting usespyupgrade,isortandblack.makecodestyle# or use synonymmakeformattingCodestyle checks only, without rewriting files:makecheck-codestyleNote:check-codestyleusesisort,blackanddarglintlibraryUpdate all dev libraries to the latest version using one comandmakeupdate-dev-deps4. Code securitymakecheck-safetyThis command launchesPoetryintegrity checks as well as identifies security issues withSafetyandBandit.makecheck-safety5. Type checksRunmypystatic type checkermakemypy6. Tests with coverage badgesRunpytestmaketest7. All lintersOf course there is a command torulerun all linters in one:makelintthe same as:maketest&&makecheck-codestyle&&makemypy&&makecheck-safety8. Dockermakedocker-buildwhich is equivalent to:makedocker-buildVERSION=latestRemove docker image withmakedocker-removeMore informationabout docker.9. CleanupDelete pycache filesmakepycache-removeRemove package buildmakebuild-removeDelete .DS_STORE filesmakedsstore-removeRemove .mypycachemakemypycache-removeOr to remove all above run:makecleanup📈 ReleasesYou can see the list of available releases on theGitHub Releasespage.We followSemantic Versionsspecification.We useRelease Drafter. As pull requests are merged, a draft release is kept up-to-date listing the changes, ready to publish when you’re ready. With the categories option, you can categorize pull requests in release notes using labels.List of labels and corresponding titlesLabelTitle in Releasesenhancement,feature🚀 Featuresbug,refactoring,bugfix,fix🔧 Fixes & Refactoringbuild,ci,testing📦 Build System & CI/CDbreaking💥 Breaking Changesdocumentation📝 Documentationdependencies⬆️ Dependencies updatesYou can update it inrelease-drafter.yml.GitHub creates thebug,enhancement, anddocumentationlabels for you. Dependabot creates thedependencieslabel. Create the remaining labels on the Issues tab of your GitHub repository, when you need them.🛡 LicenseThis project is licensed under the terms of theMITlicense. SeeLICENSEfor more details.📃 Citation@misc{aiothinkingcleaner,author={matthijs2704},title={Library to communicate with a Thinking Cleaner module asynchronously},year={2022},publisher={GitHub},journal={GitHub repository},howpublished={\url{https://github.com/matthijs2704/aiothinkingcleaner}}}CreditsThis project was generated withpython-package-template
aiothornode
aiothornodeThis is a simple Python library to accessTHORChainnodes. It is asynchronous and usesaiohttp.Importantv.0.1.0 breaking changes:NamedTuples instead of DataClasses for Thor entitiesEnvironments were renamedNo more consensus featuresv.0.0.21 is hotfix. Port 1317 was disabled, so it is an emergency upgrade to save this lib. More news will be later...Features:Now it is just a convenient wrapper for THORNode APISupported endpoints:ConstantsMimirNodes (node accounts)Current TX queue lengthPools (current and at arbitrary height)Tendermint block at heightInbound addresses and other chain infoAsgard & Yggdrasil vaults (new!)Balance of THOR accountInstallationpython -m pip install git+https://github.com/tirinox/aiothornodeQuick startThe following code is quite self-documenting:import random from aiothornode.connector import * from aiothornode.env import * import asyncio import aiohttp def delim(): print('-' * 100) async def main(): env = MAINNET.copy() # env = ThorEnvironment(...) # custom async with aiohttp.ClientSession() as session: connector = ThorConnector(env, session) genesis = await connector.query_genesis() print(f'Chain ID = {genesis["chain_id"]}') delim() chains = await connector.query_chain_info() chains = list(chains.values()) print('Chain info:', chains) delim() print('Tendermint Block:') tender_block = await connector.query_tendermint_block_raw(100001) block_header = tender_block['result']['block']['header'] print(f'{block_header["height"] = } and {block_header["time"] = }') delim() constants = await connector.query_constants() print(f'Constants: {constants}') delim() mimir = await connector.query_mimir() mimir_1 = mimir.get('MINIMUMBONDINRUNE') print(f'Mimir: {mimir}, MINIMUMBONDINRUNE = {mimir_1}') delim() queue = await connector.query_queue() print(f'Queue: {queue}') delim() node_accounts = await connector.query_node_accounts(consensus=False) print(f'Example node account: {random.sample(node_accounts, 1)[0]}') delim() pool = await connector.query_pool('BNB.BUSD-BD1', height=8218339) print(pool) delim() pools = await connector.query_pools() print(pools[0]) print(f'Total {len(pools)} pools') delim() bank = await connector.query_balance('thor1dheycdevq39qlkxs2a6wuuzyn4aqxhve4qxtxt') print(f'Balance of {bank.address} is {bank.runes_float} Rune') delim() if __name__ == '__main__': asyncio.run(main())TestingInstall PyTest and an async plugin for it:pip install pytest pip install pytest-asyncioThen runpytest test
aiothread
# aiothread Run asyncio loop in another thread.
aiothrift
Asyncio implementation for thrift protocol, which is heavily based onthriftpy2.Documentation:https://aiothrift.readthedocs.org/Installation$ pip install aiothriftUsage exampleThrift fileservice PingPong { string ping(), i64 add(1:i32 a, 2:i64 b), }Serverimportasyncioimportaiothriftpingpong_thrift=aiothrift.load('pingpong.thrift',module_name='pingpong_thrift')classDispatcher:defping(self):return"pong"asyncdefadd(self,a,b):awaitasyncio.sleep(1)returna+basyncdefmain():server=awaitaiothrift.create_server(pingpong_thrift.PingPong,Dispatcher()))asyncwithserver:awaitserver.serve_forever()asyncio.run(main())Clientimportasyncioimportaiothriftpingpong_thrift=aiothrift.load('pingpong.thrift',module_name='pingpong_thrift')asyncdefgo():conn=awaitaiothrift.create_connection(pingpong_thrift.PingPong)print(awaitconn.ping())print(awaitconn.add(5,6))conn.close()asyncio.run(go())Or use ConnectionPoolimportasyncioimportaiothriftpingpong_thrift=aiothrift.load('pingpong.thrift',module_name='pingpong_thrift')asyncdefgo():client=awaitaiothrift.create_pool(pingpong_thrift.PingPong)print(awaitclient.ping())print(awaitclient.add(5,6))client.close()awaitclient.wait_closed()asyncio.run(go())It’s just that simple to begin withaiothrift, and you are not forced to useaiothrifton both server and client side. So if you already have a normal thrift server setup, feel free to create an async thrift client to communicate with that server.RequirementsPython >= 3.7.0async-timeoutthriftpy2LICENSEaiothriftis offered under the MIT license.
aiothrottle
aiothrottleThrottling, flow controlling StreamReader for aiohttpRequirementsPython >= 3.4.2aiohttphttps://pypi.python.org/pypi/aiohttpLicenseaiothrottleis offered under the GPL v3 license.Documentationhttps://aiothrottle.readthedocs.org/Source codeThe latest developer version is available in a github repository:https://github.com/panda73111/aiothrottleUsageimportasyncioimportaiohttpimportaiothrottle@asyncio.coroutinedefload_file(url):response=yield fromaiohttp.request("GET",url)data=yield fromresponse.read()withopen("largefile.zip","wb")asfile:file.write(data)response.close()# setup the rate limit to 200 KB/saiothrottle.limit_rate(200*1024)# download a large file without blocking bandwidthloop=asyncio.get_event_loop()loop.run_until_complete(load_file("http://example.com/largefile.zip"))# unset the rate limitaiothrottle.unlimit_rate()TODOUpload rate limiting classGeneral socket limiting classCHANGES0.1.3 (30-08-2016)Set minimum required Python version to 3.4.2, the same as aiohttp 1.0.0Made aiothrottle compatible with current aiohttp version again (Now using aiohttp.StreamReader._buffer_size)Catching RuntimeError when trying to pause a closing _SSLProtocolTransport0.1.2 (08-08-2015)Fixed resuming transport too oftenAdded ‘rate_limit’ and ‘throttling’ propertiesFixed buffer limit control0.1.1 (08-02-2015)Added limit_rate() and unlimit_rate() globally and response-wiseRaising ValueError on invalid rate limitCancelling _check_handle in Throttle’s destructor0.1.0 (08-01-2015)Initial release with basic throttling functionality
aio-throttle
This library is inspired bythis bookand this implementationhttps://github.com/vostok/throttling.Features:Set capacity(max parallel requests) and queue(max queued requests) limits.Per-consumer limits. For instance, to not allow any consumer to use more than 70% of service's capacity.Per-request priorities. For instance, to not allow requests with lowest priority to be queued or to now allow requests with normal priority to use more than 90% of service's capacity.Example:fromaio_throttleimportThrottler,MaxFractionCapacityQuota,ThrottlePriority,ThrottleResultcapacity_limit=100queue_limit=200consumer_quotas=[MaxFractionCapacityQuota(0.7)]priority_quotas=[MaxFractionCapacityQuota(0.9,ThrottlePriority.NORMAL)]throttler=Throttler(capacity_limit,queue_limit,consumer_quotas,priority_quotas)consumer,priority="yet another consumer",ThrottlePriority.HIGHasyncwiththrottler.throttle(consumer=consumer,priority=priority)asresult:...# check if result is ThrottleResult.ACCEPTED or notExample of an integration with aiohttp and prometheus_client()importaiohttpimportaiohttp.webimportaiohttp.web_requestimportaiohttp.web_responseimportaio_throttle@aio_throttle.aiohttp_ignore()# do not throttle this handlerasyncdefhealthcheck(_:aiohttp.web_request.Request)->aiohttp.web_response.Response:returnaiohttp.web_response.Response()asyncdefauthorize(_:aiohttp.web_request.Request)->aiohttp.web_response.Response:returnaiohttp.web_response.Response()asyncdefcreate_app()->aiohttp.web.Application:app=aiohttp.web.Application(middlewares=[aio_throttle.aiohttp_middleware_factory(capacity_limit=20,queue_limit=100,consumer_quotas=[aio_throttle.MaxFractionCapacityQuota[str](0.7)],priority_quotas=[aio_throttle.MaxFractionCapacityQuota[aio_throttle.ThrottlePriority](0.9,aio_throttle.ThrottlePriority.NORMAL)],metrics_provider=aio_throttle.PROMETHEUS_METRICS_PROVIDER,),])app.router.add_get("/healthcheck",healthcheck)app.router.add_post("/authorize",authorize)returnappaiohttp.web.run_app(create_app(),port=8080,access_log=None)
aiothrottler
aiothrottlerThrottler for asyncio PythonInstallationpipinstallaiothrottlerUsageCreate a sharedThrottler, passing a minimum interval, e.g.0.5secondsfromaiothrottlerimportThrottlerthrottler=Throttler(min_interval=0.5)and then just before the piece(s) of code to be throttled,callthis andawaitits result.awaitthrottler()# There will be a gap of at least 0.5 seconds# between executions reaching this lineExample: multiple tasks throttledimportasyncioimporttimefromaiothrottlerimportThrottlerasyncdefmain():throttler=Throttler(min_interval=0.5)awaitasyncio.gather(*[worker(throttler)for_inrange(10)])asyncdefworker(throttler):awaitthrottler()# Interval of at least 0.5 seconds between prints# even though all workers started togetherprint(time.time())loop=asyncio.get_event_loop()loop.run_until_complete(main())loop.close()Example: single task throttled/smoothedimportasyncioimportrandomimporttimefromaiothrottlerimportThrottlerasyncdefmain():throttler=Throttler(min_interval=0.5)for_inrange(10):awaitthrottler()# Interval of at least 0.5 seconds between prints# even though each sleep is randomprint(time.time())awaitasyncio.sleep(random.random())loop=asyncio.get_event_loop()loop.run_until_complete(main())loop.close()Differences to alternativesThe API features a function to call toawaitits result [some use a context manager]The API is imperative [some use a functional approach/higher-order function]No polling is used [some use polling internally]Aminimum interval between resolutionsis used to throttle [rather that amax resolutions per time interval, which can cause an irregular pattern of resolutions]The tests cover edge cases, such as asserting on throttling after tasks being throttled have been cancelled [some alternatives do not]
aiothrottles
aiothrottlesaiothrottles synchronization primitives are designed to be extension toasyncio synchronization primitives.For more details, seeaiothrottles Documentation.UsageThrottle implements a rate limiting for asyncio task. A throttle can be used to guarantee limited access to a shared resources.The preferred way to use a Throttle is anasync withstatement:throttle=Throttle('3/s')# ... laterasyncwiththrottle:# access shared statewhich is equivalent to:throttle=Throttle('3/s')# ... laterawaitthrottle.acquire()try:# access shared statefinally:throttle.release()A call rate is determined by therateargument. Pass the rate in the following formats:"{integer limit}/{unit time}""{limit's numerator}/{limit's denominator}{unit time}"rateexamples:4/s,5/m,6/h,7/d1/second,2/minute,3/hour,4/day1/3s,12/37m,1/5h,8/3dInstallationpipinstallaiothrottlesorpythonsetup.pyinstallSupported Python VersionsPython 3.6, 3.7, 3.8 and 3.9 are supported.TestRun all tests.pythonsetup.pytestRun tests with PyTest.python-mpytest[-kTEST_NAME][-mMARKER]Licenseaiothrottlesis released under the BSD 3-Clause License.
aio-throttle-to-next-second
aio-throttle-to-next-secondThrottler for asyncio Python that throttles to the next whole second, as reported bytime.time(). This is useful to force an order on requests to a service that uses a "latest timestamp wins" strategy, such as S3.Installationpipinstallaio-throttle-to-next-secondUsageCreate a sharedThrottler, with no argumentsfromaio_throttle_to_next_secondimportThrottlerthrottler=Throttler()and then just before the piece(s) of code to be throttled,callthis andawaitits result.awaitthrottler()# Each execution reaching this line will reach this line at a different secondExample: multiple tasks throttledimportasyncioimporttimefromaio_throttle_to_next_secondimportThrottlerasyncdefmain():throttler=Throttler()awaitasyncio.gather(*[worker(throttler)for_inrange(10)])asyncdefworker(throttler):awaitthrottler()# Each print will show a distinct second, though all workers started togetherprint(int(time.time()))loop=asyncio.get_event_loop()loop.run_until_complete(main())loop.close()Example: single task throttledimportasyncioimportrandomimporttimefromaio_throttle_to_next_secondimportThrottlerasyncdefmain():throttler=Throttler()for_inrange(10):awaitthrottler()# Each print will show a distinct second, though there is a random sleepprint(int(time.time()))awaitasyncio.sleep(random.random())loop=asyncio.get_event_loop()loop.run_until_complete(main())loop.close()
aiotieba
安装pipinstallaiotieba尝试一下importasyncioimportaiotiebaasyncdefmain():asyncwithaiotieba.Client()asclient:threads=awaitclient.get_threads("天堂鸡汤")forthreadinthreads[3:6]:print(f"tid={thread.tid}text={thread.text}")asyncio.run(main())输出样例--- tid=8537603600 text=一人发一句最喜欢的游戏台词 楼主先来 很喜欢lol布隆说的“夜晚越黑暗,星星就越明亮”,尤其在当下这个有着诸多缺点的世界里,这句话让我感觉舒服了很多在人们已不再相信理想主义的至暗时刻,高擎炬火之人便显得更加重要,至少我会坚持我的理想 --- tid=8093410706 text=大概是剪切板里的一些有意思的话 今天看自己的剪切板快满了,稍微翻翻突然发现以前存的一些话还挺有意思,就放在这里啦 (咦,疑似水帖啊我) --- tid=8537699088 text=记录一下自己人生第一次当“老师”的经历^_^ 明天我带的孩子们就“毕业”了,第一次当老师我改变了很多也收获了很多,就想着给自己记录一下这段宝贵的经历:-)继续阅读入门教程项目特色收录数十个常用API类型注解全覆盖,方法注释全覆盖,类属性注释全覆盖,内部命名统一支持protobuf序列化请求参数支持websocket接口与官方版本高度一致的密码学实现友情链接TiebaManager(吧务管理器 有用户界面)TiebaLite(第三方安卓客户端 Archived)基于aiotieba的高弹性吧务审查框架贴吧protobuf定义文件合集(更新至12.51.7.1)特别鸣谢为本开源项目提供的免费产品授权
aiotieba-reviewer
客户名单2024.02.24更新吧名关注量浏览量(30天平均)发帖量抗压背锅543152084402943940孙笑川5383418478024144280原神内鬼69151337550721945憨批7299215782347995lol半价2099998886803882新孙笑川971561210527381vtuber23216415166682元气骑士2841717691941天堂鸡汤39619767851626友情链接TiebaManager(吧务管理器 有用户界面)TiebaLite(第三方安卓客户端)贴吧protobuf定义文件合集
aiotiktok
aiotiktokis super simple and fast library to get all video data from TikTokSimple RequestimportasynciofromaiotiktokimportClienttiktok=Client()asyncdefmain():awaittiktok.get_data(url="some url")asyncio.run(main())SignatureFor use method user_feed_sig you must up your application.This must be done in order to be able to generate a signature for a request to the private TikTok apiFollow this instructionhttps://github.com/sheldygg/tiktok-signatureAfter you have run it, you must specify a reference when initializing the Client classfromaiotiktokimportClienttiktok=Client(signature_url="some url")By default ishttp://127.0.0.1:8002/signatureThen you can get user feedfromaiotiktokimportClienttiktok=Client()awaittiktok.user_feed_sig("playboicarti")
aiotime
aiotimeAnasynciotest helper that allows you to deterministically control the event loop's internal clock in your tests, affecting the behavior of the following functions:asyncio.sleeploop.call_atloop.call_laterNote about behaviorIf you enter theaiotime.FastForwardcontext manager (as in thewithblock in the examples below), then theloopsupplied to its constructor will STOP triggering scheduled events, tasks or callbacks. Once you__enter__the context manager, you MUST call the returned object or the event loop will be stuck in time. Only when you__exit__the context manager will the loop return to normal behavior.(Using the same event loop with and withoutaiotimecontrol is not supported; there may be unexpected effects with scheduling at the margins.)Getting started# TODO Add to pypiControllingasyncio.sleeploop=asyncio.get_event_loop()# Try sleeping with normal loop behaviorstart=dt.datetime.now()sleep_task=asyncio.create_task(asyncio.sleep(0.25))awaitsleep_taskassertdt.datetime.now()-start>dt.timedelta(seconds=0.25)withaiotime.FastForward(loop)asff:# Try fast-forwarding through the sleepstart=dt.datetime.now()sleep_task=asyncio.create_task(asyncio.sleep(0.25))awaitff(1.5)# ff more than necessaryawaitsleep_taskassertdt.datetime.now()-start<dt.timedelta(seconds=0.05)Controllingloop.call_laterloop=asyncio.get_event_loop()withaiotime.FastForward(loop)asff:# Try call_later() with fast-forwardingstart=dt.datetime.now()event=asyncio.Event()deftest():event.set()loop.call_later(0.25,test)awaitff(1.5)# ff more than necessaryawaitasyncio.wait_for(event.wait(),2)# timeout just in caseassertdt.datetime.now()-start<dt.timedelta(seconds=0.05)# call_later() with normal loop behavior now, after context manager exitsstart=dt.datetime.now()event=asyncio.Event()deftest():event.set()loop.call_later(0.25,test)awaitasyncio.wait_for(event.wait(),1)# timeout just in caseassertdt.datetime.now()-start>dt.timedelta(seconds=0.25)
aiotimeout
aiotimeoutTimeout context manager for asyncio PythonUsagefromaiotimeoutimporttimeout# Will raise an asyncio.TimeoutErrorwithtimeout(1):awaitasyncio.sleep(1.5)# Will not raise anythingwithtimeout(1):awaitasyncio.sleep(0.5)You can respond to a timeout fromoutsidethe context by catchingasyncio.TimeoutErrortry:withtimeout(1):awaitasyncio.sleep(1.5)print('This line is not reached')exceptasyncio.TimeoutError:print('Timed out')or you can respond to a timeout frominsidethe context by catchingasyncio.CancelledErrorand re-raising.try:withtimeout(1):try:awaitasyncio.sleep(1.5)exceptasyncio.CancelledErrorprint('Doing some cleanup')raiseexceptasyncio.TimeoutError:print('Timed out')Differences to alternativesasyncio.wait_fordoes not offer a context manager. In some cases a context manager is clearer.asyncio.wait_forcreates/uses an extra task. In some cases this is not necessary, and an extra task adds non-determinism in terms of sequence of operations.Clearer internal code [in the author's opinion]. Rather than a custom class,contextlib.contextmanageris used.
aiotimer
AsyncIO compatible periodic timer. Linux only and very alpha API.ExampleThe timer is implemented as a straightforward protocol similar to how the asyncio’s network protocols are handled:classMyTimer(aiotimer.Protocol):def__init__(self):self.counter=0deftimer_started(self,timer):self.timer=timerdeftimer_ticked(self):# Callback triggered when the timer interval elapses...deftimer_overrun(self):# Callback triggered if the timer_ticked callback runtime# should exceed the timer interval. Return True to# reschedule, otherwise the timer is aborted.returnTruedeferror_received():...The protocol can then be used to create a new timer:# Schedule once every 10th of a secondaiotimer.create_timer(MyTimer,0.1,loop=loop)
aio-timers
aio-timersTiming utilities based onasyncio.Setuppip install aio-timersUsageimportasynciofromaio_timersimportTimerdefcallback(name):print("Hello{}!".format(name))# timer is scheduled heretimer=Timer(5,callback,callback_args=("World",))# wait until the callback has been executedloop=asyncio.get_event_loop()loop.run_until_complete(timer.wait())print("end")Output:(after 5 seconds)Hello World!endTimerCalls acallbackafterdelayseconds.The timer is executed as a task on an event loop.The callback is invoked:as a synchronous function if it is not a coroutine;with an await if it is a coroutine or thecallback_asyncflag is set toTrue.Any result returned by the callback is ignored.ConstructorTimer(delay, callback, callback_args=(), callback_kwargs={}, callback_async=False, *, loop=None)where:delay, seconds before thecallbackis executed;callback, the callback to execute afterdelaysecondscallback_args, (optional, default=()) positional arguments to pass tocallbackcallback_kwargs, (optional, default={}) keyword arguments to pass tocallbackcallback_async, (optional, default=False) ifTruethe callback will be executed on the event loop (await)loop, (optional, default=None) event loop where the delayed task will be scheduled (ifNonewill useasyncio.get_event_loop())NOTE: thecallback_asyncflag should be used when a coroutine is decorated (e.g., usingfunctools.partial).cancel()Cancels the execution of the callback.async .wait()Wait until the callback has been executed or its execution has been canceled.If the execution has been canceled, will raiseasyncio.CancelledError.
aiotinder
No description available on PyPI.
aio-tinder
IntroductionAsynchronous Tinder API client written in Python that targets Python 3.5 and above.NoteThis library is Python 3.5 and above only. It relies on asyncio and type hinting henceforth the library is not compatible with the previous Python versions.Installation$pipinstallaio-tinder
aiotinydb
aiotinydbasyncio compatibility shim forTinyDBEnables usage of TinyDB in asyncio-aware contexts without slow syncronous IO.See documentation on compatible version ofTinyDB.Basically all API calls fromTinyDBare supported inAIOTinyDB. With the following exceptions: youshould notuse basicwithsyntax andclosefunctions. Instead, youshoulduseasync with.importasynciofromaiotinydbimportAIOTinyDBasyncdeftest():asyncwithAIOTinyDB('test.json')asdb:db.insert(dict(counter=1))loop=asyncio.new_event_loop()loop.run_until_complete(test())loop.close()CPU-bound operations likedb.search(),db.update()etc. are executed synchronously and may block the event loop under heavy load. Use multiprocessing if that's an issue (see#6andexamples/processpool.pyfor an example).MiddlewareAny middlewares you useshould beasync-aware. See example:fromtinydb.middlewaresimportCachingMiddlewareasVanillaCachingMiddlewarefromaiotinydb.middlewareimportAIOMiddlewareclassCachingMiddleware(VanillaCachingMiddleware,AIOMiddlewareMixin):"""Async-aware CachingMiddleware. For more info readdocstring for `tinydb.middlewares.CachingMiddleware`"""passIf middleware requires some special handling on entry and exit, override__aenter__and__aexit__.Concurrent database accessInstances ofAIOTinyDBsupport database access from multiple coroutines.Onunix-like systems, it's also possible to access one database concurrently from multiple processes when usingAIOJSONStorage(the default) orAIOImmutableJSONStorage.Installationpip install aiotinydb
aio-tiny-healthcheck
aio_tiny_healthcheckTiny asynchronous implementation of healthcheck provider and serverInstallationpipinstallaio-tiny-healthcheckUsageBy default, the Checker returns 200 if all checks successfully finish or 500 in opposite case.Using with aiohttpfromaiohttpimportwebfromaio_tiny_healthcheck.checkerimportCheckerdefsome_sync_check():returnTrueasyncdefsome_async_check():returnFalsehealthcheck_provider=Checker()healthcheck_provider.add_check('sync_check_true',some_async_check)healthcheck_provider.add_check('async_check_false',some_async_check)app=web.Application()app.router.add_get('/healthcheck',healthcheck_provider.aiohttp_handler)web.run_app(app)Using with SanicfromsanicimportSanicfromsanic.responseimportjsonfromaio_tiny_healthcheck.checkerimportCheckerapp=Sanic()defsome_sync_check():returnTrueasyncdefsome_async_check():returnFalsehealthcheck_provider=Checker(success_code=201,fail_code=400)healthcheck_provider.add_check('sync_check_true',some_async_check)healthcheck_provider.add_check('async_check_false',some_async_check)@app.route("/healthcheck")asyncdeftest(request):hc_response=healthcheck_provider.check_handler()returnjson(hc_response.body,status=hc_response.code)if__name__=="__main__":app.run(host="0.0.0.0",port=8000)Using in concurrent modeYou should want to run healthcheck in background if you already have some blocking operation in your execution flow. So, you can just use built-in server for this.fromaio_tiny_healthcheck.checkerimportCheckerfromaio_tiny_healthcheck.http_serverimportHttpServerimportasyncioasyncdefsome_long_task():awaitasyncio.sleep(3600)defsome_sync_check():returnTrueasyncdefsome_async_check():returnTrueaio_thc=Checker()hc_server=HttpServer(aio_thc,path='/health',host='localhost',port=9090)aio_thc.add_check('sync_check_true',some_async_check)aio_thc.add_check('async_check_false',some_async_check)asyncdefmain():# Run healthcheck concurrentlyasyncio.create_task(hc_server.run())# Run long taskawaitsome_long_task()if__name__=='__main__':loop=asyncio.get_event_loop()loop.run_until_complete(main())Utility for health checkingpython -m aio_tiny_healthcheck http://localhost:9192/healthcheckUseful for running health check without external dependencies like curl.By default, concurrent server and health checking utility are working with a port and query pathhttp://localhost:8000/healthcheck. So, if you run concurrent server with no using arguments, you can also run the utility with without argumentspython -m aio_tiny_healthcheck.
aiotk
PurposeThis is a collection of asyncio-related utilities that I have found useful, that I’ve used in at least two projects and that seem like they might be useful to others.ResourcesDocumentation:aiotk on ReadTheDocsOfficial releases:aiotk on PyPISource code:aiotk on GitHubContributingNobody is paid to maintain this software, but we welcome pull requests!LicenseLicensed under the very permissive MIT license for maximum usage.
aiotkinter
This module provide an asyncio API for the the Tkinter event loopLicense: MIT (see LICENSE)RequirementsUnix platform (it doesn’t work on Windows because of the lack ofTcl_CreateFileHandleron this platform)Python 3.3 + asyncio or Python >= 3.4Installationpythonsetup.pyinstallUsageaiotkinterexpose an event loop policy (which based on the default event loop policy ofasyncio) so the only thing you have to do is to set the global event loop policy with an instance ofTkinterEventLoopPolicy:importasyncioimportaiotkinterasyncio.set_event_loop_policy(aiotkinter.TkinterEventLoopPolicy())loop=asyncio.get_event_loop()loop.run_forever()
aiotmdb
No description available on PyPI.
aiotnse
aioTNSEAsynchronous Python API forTNS-Energo.InstallationUse pip to install the library:pip install aiotnseUsageimportasynciofrompprintimportpprintimportaiohttpfromaiotnseimportSimpleTNSEAuth,TNSEApiasyncdefmain(account:str)->None:"""Create the aiohttp session and run the example."""asyncwithaiohttp.ClientSession()assession:auth=SimpleTNSEAuth(session)api=TNSEApi(auth)data=awaitapi.async_get_latest_readings(account)pprint(data)if__name__=="__main__":_account=string=str(input("Account: "))asyncio.run(main(_account))TheSimpleTNSEAuthclient also accept custom access token (this can be found by sniffing the client).This will return a price object that looks a little like this:{"STATUS":"Используется","counters":{"1111111":[{"Can_delete":"0","DatePok":"06.02.2023","DatePosledPover":"31.12.2021","DatePover":"31.12.2037","DatePoverStatus":0,"DatePoverURL":"","GodVipuska":"01.01.22","KoefTrans":"1","Label":"Дневная зона","MaxPok":"2000","MestoUst":"Жилой дом","ModelPU":"Нева МТ 114 AS PLRFPC","NazvanieTarifa":"День","NazvanieUslugi":"Электроснабжение ","NomerTarifa":"0","NomerUslugi":"0100","PredPok":"700","RaschSch":"Работает","Razradnost":"6","RowID":"1111111","Tarifnost":"2","Type":"1","ZavodNomer":"22222222","sort":0,"zakrPok":"700"},{"Can_delete":"0","DatePok":"06.02.2023","DatePosledPover":"31.12.2021","DatePover":"31.12.2037","DatePoverStatus":0,"DatePoverURL":"","GodVipuska":"01.01.22","KoefTrans":"1","Label":"Ночная зона","MaxPok":"2000","MestoUst":"Жилой дом","ModelPU":"Нева МТ 114 AS PLRFPC","NazvanieTarifa":"Ночь","NazvanieUslugi":"Электроснабжение ","NomerTarifa":"1","NomerUslugi":"0100","PredPok":"337","RaschSch":"Работает","Razradnost":"6","RowID":"1111111","Tarifnost":"2","Type":"1","ZavodNomer":"22222222","sort":1,"zakrPok":"337"}]},"result":true}Timeoutsaiotnse does not specify any timeouts for any requests. You will need to specify them in your own code. We recommend thetimeoutfromasynciopackage:importasynciowithasyncio.timeout(10):data=awaitapi.async_get_account_status(account)
aiotodoist
aiotodoisttodoist APIwith async enabled usingaiohttp.ChangesTo enable asynchronous, there have plenty methods be changed to returnawaitableinstead, list below:APIapi._get,api_postwill be changed to returncoroutine.api.sync,api.commitwill be changed to returnfuture.ManagersAll of those managers could be accessed viaapi.<manager_name>.activity.getbackups.getbusiness_users.invite,business_users.accept_invitation, business_users.reject_invitation`completed.get_stats,completed.get_allemails.get_or_create,emails.disableitems.get_completedprojects.get_archived,projects.get_dataquick.addtemplates.import_into_project,templates.export_as_file,templates.exort_as_urluploads.add,uploads.get,uploads.deleteuser.delete,user.update_notification.settingMethods listed above, will returncoroutine, and others will returnFuture:collaborator_states.sync,collaborators.syncfilters.sync,filters.getinvitations.syncitems.synclabels.synclive_notifications.synclocations.syncnotes.syncproject_notes.syncprojects.syncreminders.syncsections.syncuser.sync
aiotoml
AiotomlAsync package for work with TOML. In develop.
aioton
No description available on PyPI.
aiotools
aiotoolsIdiomatic asyncio utiltiesNOTE:This project is under early stage of development. The public APIs may break version by version.ModulesAsync Context ManagerAsync ForkAsync FunctoolsAsync ItertoolsAsync ServerAsync TaskGroupAsync TimerI also recommend to try the following asyncio libraries for your happier life.async_timeout: Provides a light-weight timeout wrapper that does not spawn subtasks.aiojobs: Provides a concurrency-limited scheduler for asyncio tasks with graceful shutdown.trio: An alternative implementation of asynchronous IO stack for Python, with focus on cancellation scopes and task groups called "nursery".ExamplesAsync Context ManagerThis is an asynchronous version ofcontextlib.contextmanagerto make it easier to write asynchronous context managers without creating boilerplate classes.importasyncioimportaiotools@aiotools.actxmgrasyncdefmygen(a):awaitasyncio.sleep(1)yielda+1awaitasyncio.sleep(1)asyncdefsomewhere():asyncwithmygen(1)asb:assertb==2Note that you need to wrapyieldwith a try-finally block to ensure resource releases (e.g., locks), even in the case when an exception is ocurred inside the async-with block.importasyncioimportaiotoolslock=asyncio.Lock()@aiotools.actxmgrasyncdefmygen(a):awaitlock.acquire()try:yielda+1finally:lock.release()asyncdefsomewhere():try:asyncwithmygen(1)asb:raiseRuntimeError('oops')exceptRuntimeError:print('caught!')# you can catch exceptions here.You can also create a group of async context managers, which are entered/exited all at once usingasyncio.gather()[email protected](a):yielda+10asyncdefsomewhere():ctxgrp=aiotools.actxgroup(mygen(i)foriinrange(10))asyncwithctxgrpasvalues:assertlen(values)==10foriinrange(10):assertvalues[i]==i+10Async ServerThis implements a common pattern to launch asyncio-based server daemons.importasyncioimportaiotoolsasyncdefecho(reader,writer):data=awaitreader.read(100)writer.write(data)awaitwriter.drain()writer.close()@aiotools.serverasyncdefmyworker(loop,pidx,args):server=awaitasyncio.start_server(echo,'0.0.0.0',8888,reuse_port=True,loop=loop)print(f'[{pidx}] started')yield# wait until terminatedserver.close()awaitserver.wait_closed()print(f'[{pidx}] terminated')if__name__=='__main__':# Run the above server using 4 worker processes.aiotools.start_server(myworker,num_workers=4)It handles SIGINT/SIGTERM signals automatically to stop the server, as well as lifecycle management of event loops running on multiple processes. Internally it usesaiotools.forkmodule to get kernel support to resolve potential signal/PID related races via PID file descriptors on supported versions (Python 3.9+ and Linux kernel 5.4+).Async TaskGroupATaskGroupobject manages the lifecycle of sub-tasks spawned via itscreate_task()method by guarding them with an async context manager which exits only when all sub-tasks are either completed or cancelled.This is motivated fromtrio's nursery APIand a draft implementation is adopted fromEdgeDB's Python client library.importaiotoolsasyncdefdo():asyncwithaiotools.TaskGroup()astg:tg.create_task(...)tg.create_task(...)...# at this point, all subtasks are either cancelled or done.Async Timerimportaiotoolsi=0asyncdefmytick(interval):print(i)i+=1asyncdefsomewhere():t=aiotools.create_timer(mytick,1.0)...t.cancel()awaitttis anasyncio.Taskobject. To stop the timer, callt.cancel(); await t. Please don't forgetawait-ingtbecause it requires extra steps to cancel and await all pending tasks. To make your timer function to be cancellable, add a try-except clause catchingasyncio.CancelledErrorsince we use it as a termination signal.You may addTimerDelayPolicyargument to control the behavior when the timer-fired task takes longer than the timer interval.DEFAULTis to accumulate them and cancel all the remainings at once when the timer is cancelled.CANCELis to cancel any pending previously fired tasks on every interval.importasyncioimportaiotoolsasyncdefmytick(interval):awaitasyncio.sleep(100)# cancelled on every next interval.asyncdefsomewhere():t=aiotools.create_timer(mytick,1.0,aiotools.TimerDelayPolicy.CANCEL)...t.cancel()awaittVirtual ClockIt provides a virtual clock that advances the event loop time instantly upon any combination ofasyncio.sleep()calls in multiple coroutine tasks, by temporarily patching the event loop selector.This is also used inour timer test [email protected]_sleeps():loop=aiotools.compat.get_running_loop()vclock=aiotools.VirtualClock()withvclock.patch_loop():print(loop.time())# -> prints 0awaitasyncio.sleep(3600)print(loop.time())# -> prints 3600Changelog1.7.0 (2023-08-25)Breaking changesDropped the support for Python 3.7 as it's end-of-life.FixesCorrect the type annotation of the callback argument increate_timer()(#61)1.6.1 (2023-05-02)FixesPersistentTaskGroup no longer stores the history of unhandled exceptions and raises them as an exception group to prevent memory leaks (#54)1.6.0 (2023-03-14)FeaturesAddas_completed_safe()which enhancesasyncio.as_completed()usingPersistentTaskGroup(#52)1.5.9 (2022-04-26)FixesImprove checks for pidfd availability to avoid corner cases that may fail on Linux kernel 5.1 and 5.2 wheresignal.pidfd_send_signal()is available butos.pidfd_open()is not (#51)1.5.8 (2022-04-25)FixesExplicitly attach the event loop to thePidfdChildWatcherwhen first initialized (#50)1.5.7 (2022-04-12)FixesFix regression of the default imports in macOS by removing the unused code that caused the misleading fix in #47 (#49)1.5.6 (2022-04-11)FeaturesAdd theclosing_async()async context manager, in addition toaclosing()(#48)FixesAllow importing aiotools on Windows platforms, removing incompatible modules from the default__all__import list (#47)1.5.5 (2022-03-22)FeaturesAddwait_timeoutoption tostart_server()(#46)FixesResolve singal races by minimizing expose of event loop inafork()-ed child processes (#46)MiscellaneousNow the CI runs with Python 3.11a6 or later, with stdlib support ofasyncio.TaskGroup(#45)1.5.4 (2022-03-10)FeaturesPropagate task results and exceptions via separate future instances if they areawait-ed by the caller ofcreate_task()inPersistentTaskGroup, in addition to invocation of task group exception handler. Note thatawait-ing those futures hangs indefinitely in Python 3.6 but we don't fix it since Python 3.6 is EoL as of December 2021. (#44)1.5.3 (2022-03-07)FixesFix feature detection forExceptionGroupand letMultiErrorinheritExceptionGroupinstead ofBaseExceptionGroup(#42)1.5.2 (2022-03-06)FixesRestore the default export ofMultiErrorfor backward compatibility (#40)Setcurrent_ptaskgrouponly whenPersistentTaskGroupis used via theasync withstatement. (#41)1.5.1 (2022-03-06)FixesFix missing naming support ofTaskGroupin Python 3.11 (#39)1.5.0 (2022-03-06)FeaturesAdd support for Python 3.9'smsgargument toTask.cancel(). (#32)Fix "unexpected cancel" bug inTaskGroup. (#35)Rewrite PersistentTaskGroup to use Python 3.11's latest additions such asTask.uncancel()andTask.cancelling()while still supporting older Python versions (#36)AddPersistentTaskGroup.all()to enumerate all non-terminated persistent task groups (#38)1.4.0 (2022-01-10)Featuresptaskgroup: ImplementPersistentTaskGroup(#30)server: Exposeprocess_indexcontext variable for worker processes (#31)1.3.0 (2021-12-19)FixesAdd support for Python 3.10. (#28)Documentation ChangesFix documentation builds on Python 3.10 and Sphinx 4.x, by removing the 3rd-party autodoc-typehints extension and custom stylesheet overrides. (#28)1.2.2 (2021-06-07)Fixesfork:Handle children's segfault (core-dump with signals) explicitly inPidfdChildProcess(#27)1.2.1 (2021-01-12)FixesAvoid side effects of customclone()function and resorts back to the combinatino ofos.fork()andos.pidfd_open()for now (#25)1.2.0 (2021-01-12)Breaking Changesserver:Theuse_threadingargument forstart_server()is completely deprecated. (#23)FeaturesNow the primary target is Python 3.9, though we still support from Python 3.6 (#22)fork:Add a new moduleforkto support PID file descriptors in Linux 5.4+ and a POSIX-compatible fallback to asynchornously fork the Python process without signal/PID races. (#22)server:Completely rewrote the module using the newforkmodule with handling of various edge cases such as async failures of sibiling child processes (#23)1.1.1 (2020-12-16)FixesFix a potential memory leak withTaskGroupwhen it's used for long-lived asyncio tasks. (#21)1.1.0 (2020-10-18)FeaturesAdd acurrent_taskgroupcontext-variable to the taskgroup module (only available for Python 3.7 or later)FixesFix missing auto-import oftaskgroupmodule exports in theaiotoolsroot package.1.0.0 (2020-10-18)FeaturesAdopt an implementation of the taskgroup API asaiotools.taskgroupfromEdgeDB(#18)Addtimer.VirtualClockwhich provides a virtual clock that makes a block of asyncio codes usingasyncio.sleep()to complete instantly and deterministically (#19)MiscellaneousAdopt towncrier for changelog management (#15)Migrate to GitHub Actions for CI (#19)0.9.1 (2020-02-25)A maintenance release to fix up thedefermodule exports in theaiotoolsnamespace.0.9.0 (2020-02-25)defer:A new module that emulates Golang'sdefer()API with asyncio awareness.0.8.5 (2019-11-19)server:Rewrite internals of the worker main functions to use nativeasync withinstead of manually unrolling__aenter__()and__aexit__()dunder methods, to keep the code simple and avoid potential bugs.0.8.4 (2019-11-18)Python 3.8 is now officially supported.server:Fix errors whenmultiprocessing.set_start_method("spawn")is used.NOTE: This is now the default for macOS since Python 3.8.KNOWN ISSUE:#12Remove some packaging hacks in__init__.pyand let setuptools read the version from a separateaiotools/VERSIONtext file.0.8.3 (2019-10-07)context:Fixaclosing()'s__aexit__()exception arguments.0.8.2 (2019-08-28)context,server:Catch asyncio.CancelledError along with BaseException to make the cancellation behavior consistent in Python 3.6, 3.7, and 3.8.0.8.1 (2019-02-24)server:Fix yields of the received stop signal in main/worker context managers when using threaded workers.0.8.0 (2018-11-18)server:Updated stop signal handling and now user-defined worker/main context managers have a way to distinguish the stop signal received. See the updated docs for more details.0.7.3 (2018-10-16)This ia a technical release to fix a test case preventing the automated CI release procedure.0.7.2 (2018-10-16)Improve support for Python 3.6/3.7 using a small compatibility module against asyncio.func: Addexpire_afteroption tolru_cache()function.0.7.1 (2018-08-24)Minor updates to the documentation0.7.0 (2018-08-24)Add support for Python 3.7context:Updated to work like Python 3.7context:DeprecatedAsyncContextDecoratorstuffs in Python 3.7+context:Added an alias tocontextlib.AsyncExitStackin the standard library.0.6.0 (2018-04-10)Introduce a new moduleaiotools.iterwithaiter()function which corresponds to an async version of the builtiniter().0.5.4 (2018-02-01)server:Remove use of unncessary setpgrp syscall, which is also blocked by Docker's default seccomp profile!0.5.3 (2018-01-12)server:Ooops! (a finally block should have been an else block)0.5.2 (2018-01-12)server:Improve inner beauty (code readability)server:Improve reliability and portability of worker-to-main interrupts0.5.1 (2018-01-11)server:Fix a race condition related to handling of worker initialization errors with multiple workers0.5.0 (2017-11-08)func:Addlru_cache()which is a coroutine version offunctools.lru_cache()0.4.5 (2017-10-14)server:Fix a race condition related to signal handling in the multiprocessing module during terminationserver:Improve error handling during initialization of workers (automatic shutdown of other workers and the main loop after logging the exception)0.4.4 (2017-09-12)Add a new moduleaiotools.funcwithapartial()function which is an async version offunctools.partial()in the standard library0.4.3 (2017-08-06)Addaclosing()context manager likeclosing()in the standard librarySpeed up Travis CI builds for packagingNow provide README in rst as well as CHANGES (this file)0.4.2 (2017-08-01)server: Fix spawning subprocesses in child workersAdd support foruvloop0.4.0 (2017-08-01)Adduse_threadingargument toAdd initial documentation (which currently not served on readthedocs.io due to Python version problem)0.3.2 (2017-07-31)Addextra_procsargument tostart_server()functionAdd socket and ZeroMQ server examplesImprove CI configs0.3.1 (2017-07-26)Improve CI scriptsAdopt editorconfig0.3.0 (2017-04-26)Addstart_server()function using multiprocessing with automatic children lifecycle managementClarify the semantics ofAsyncContextGroupusingasyncio.gather()withreturn_exceptions=True0.2.0 (2017-04-20)Add abstract types forAsyncContextManagerRenameAsyncGenContextManagertoAsyncContextManagerAddAsyncContextGroup0.1.1 (2017-04-14)Initial release
aiotoolz
An async port of the wonderful pytoolz/toolz library.See the PyToolz documentation athttps://toolz.readthedocs.ioand the github page athttps://github.com/pytoolz/toolz.LICENSENew BSD. SeeLicense File.Installaiotoolzis not yet on the Python Package Index (PyPI), but soon you can install it like so:pip install aiotoolzCurrently, you can install it like so:pip install git+https://github.com/eabrouwer3/aiotoolz.gitStructure and Heritagetoolzis implemented in three parts:itertoolz, for operations on iterables. Examples:groupby,unique,interpose,functoolz, for higher-order functions. Examples:memoize,curry,compose,dicttoolz, for operations on dictionaries. Examples:assoc,update-in,merge.These functions come from the legacy of functional languages for list processing. They interoperate well to accomplish common complex tasks.Read ourAPI Documentationfor more details.ExampleThis builds a standard wordcount function from pieces withintoolz:>>>defstem(word):...""" Stem word to primitive form """...returnword.lower().rstrip(",.!:;'-\"").lstrip("'\"")>>>fromtoolzimportcompose,frequencies,partial>>>fromtoolz.curriedimportmap>>>wordcount=compose(frequencies,map(stem),str.split)>>>sentence="This cat jumped over this other cat!">>>wordcount(sentence){'this':2,'cat':2,'jumped':1,'over':1,'other':1}Dependenciesaiotoolzsupports Python 3.5+ with a common codebase. It is pure Python and requires no dependencies beyond the standard library.It is, in short, a lightweight dependency.See AlsoUnderscore.js: A similar library for JavaScriptEnumerable: A similar library for RubyClojure: A functional language whose standard library has several counterparts intoolzitertools: The Python standard library for iterator toolsfunctools: The Python standard library for function toolsContributions Welcomeaiotoolzaims to be a repository for utility functions, particularly those that come from the functional programming and list processing traditions. We welcome contributions that fall within this scope.We also try to keep the API small to keepaiotoolzmanageable. The ideal contribution is significantly different from existing functions and has precedent in a few other functional systems.Please take a look at ourissue pagefor contribution ideas.CommunitySee ourtoolzmailing list. We’re friendly.
aiotopics
aiotopicsFetch random topics to start conversations. Ideal for discord and other social media bots.Installationpip install aiotopicsUsageimportaiotopicstopic=awaitaiotopics.get_topic()print(topic)
aiotor
No description available on PyPI.
aiotorclient
Failed to fetch description. HTTP Status Code: 404
aiotorndb
torndbrewrite to asynchronousExampleFirst get a connection objectfromaiotorndbimportConnectionconn=Connection(host="127.0.0.1",db="test",user="root",password="123456",port=3306,time_zone="+8:00",charset="utf8",)Next, you can use methods such as select, update, insert, delete, etc.importasyncioasyncdeftest():get_result=awaitconn.get("select * from user where id = 1")print(get_result)# {'id': 1, 'name': 'tom'}select_result=awaitconn.select("select * from user")print(select_result)# [{'id': 1, 'name': 'tom'}, {'id': 2, 'name': 'ellis'}]update_result=awaitconn.update("update user set name =%(name)swhere id = 1",name="eddie")print(update_result)# 1insert_result=awaitconn.insert("insert into user (name) values (%(name)s)",name="dav")print(insert_result)# 3# sql = select * from user where id in (1, 3)select_result2=awaitconn.select("select * from user where id in%(user_ids)s",user_ids=[1,3])print(select_result2)# [{'id': 1, 'name': 'eddie'}, {'id': 3, 'name': 'dav'}]# sql = select * from project_tag where name like '%e%'select_result3=awaitconn.select("select * from project_tag where name like%(name)s",name="%e%")print(select_result3)# [{'id': 1, 'name': 'eddie'}, {'id': 2, 'name': 'ellis'}]asyncio.run(test())
aiotp
aiotp - One-time password package in PythonInstallationpip install aiotpUsageTime-based OTPsimportasynciofromaiotpimportTOTPfromaiotpimportrandom_b32# from aiotp.sync import HOTP, TOTP, random_b32, random_hexasyncdefmain():key=awaitrandom_b32()asyncwithTOTP(key,digits=4,interval=5)astotp:code=awaittotp.create()result=awaittotp.verify(code)print(result)# -> Trueawaitasyncio.sleep(5)result=awaittotp.verify(code)print(result)# -> Falseasyncio.run(main())Counter-based OTPsimportasynciofromaiotpimportHOTPfromaiotpimportrandom_b32# from aiotp.sync import HOTP, TOTP, random_b32, random_hexasyncdefmain():key=awaitrandom_b32()asyncwithHOTP(key,digits=4)ashotp:code=awaithotp.create(1000)result=awaithotp.verify(code,1000)print(result)# -> Trueresult=awaithotp.verify(code,1001)print(result)# -> Falseasyncio.run(main())LinksPackage (PyPi)RFC 6238: TOTP (algorithm)RFC 4226: HOTP (algorithm)
aiotplink
# aiotplinkLibrary to communicate with TP-Link Smart Plugs and similar devices## Features* Supports TPLink Smart Switches and Lights* Python API to interact with device at a low level using asyncio## About this libraryBased on the work done by [SoftSCheck](https://github.com/softScheck/tplink-smartplug)and [GadgetReactor](https://github.com/GadgetReactor/pyHS100)## Installation```$ sudo pip3 install aiotplink```At this point you should be able to useYou can try:```python3 -m aioyplink```And you should be able to turn On/Off your devices## Using the library.To make things simple, you create a class with 2 methods, "register" and "unregister"class devices():""" A simple class with a register and unregister methods"""def __init__(self):self.devices={}self.doi=None #device of interestdef register(self,info, addr):if "mac" in info and info["mac"].lower() not in self.devices:self.devices[info["mac"].lower()] = aiot.GetDevice(addr,info,hb=10)else:self.devices[info["mac"].lower()].addr = addrdef unregister(self,mac):if mac.lower() in self.devices:print ("%s is gone"% self.devices[mac.lower()].name)self.devices[mac.lower()].stop()del(self.devices[mac.lower()])def stop(self):for dev in self.devices.values():dev.stop()When registering, you get an dictionary with the flatten out info from a TP-Link device, and an address withthe format (ip address, port). You can pass those information directly to 'GetDevice' to get the correct object.'GetDevice" is defined like soGetDevice(addr,info,hb=HBTIMEOUT,on_change=lambda x: print(x))With addr, the address pair, info, the flatten out informaton from discovery, hb, a heatbeat timeout in secs andon_change a function that will react to whatever is produced by the heartbeat. Note that if the device has an energy meter,those values will automatically be produced with the heartbeat.After that it is quite simple.MyDevices= devices()loop = aio.get_event_loop()discovery = aiot.TPLinkDiscovery(loop, MyDevices, repeat=15)try:loop.add_reader(sys.stdin,readin)discovery.start()print("Hit \"Enter\" to start")print("Use Ctrl-C to quit")loop.run_forever()except:print("Exiting at user's request.")finally:MyDevices.stop()discovery.cleanup()loop.remove_reader(sys.stdin)loop.run_until_complete(aio.sleep(10))loop.close()Create a registrar instanceCreate a TPLinkDiscovery instance passing the registrar and how often to run discoveryStart discovery, and you are on your merry way.The various device object will have these methods available.on(): Turning the device onoff(): Turning the device offled_on(): Turn the LED light on (AKA "Night mode" off)led_off : Turn the LED light off (AKA "Night mode" on)set_name(name)set_brighness)set_temperature()set_colour(hue, saturation, value)depending on their capabilities.Most commands are defined in the commands.py file.## TroubleshootingOpen an issue and I'll try to help.
aiotr
aiotrThe transmission python client with asyncio supportsimple usageadd a torrentimportasynciofrompprintimportpprintimportujsonfromaiotrimportTransmissionClientasyncdefmain():client=TransmissionClient(loads=ujson.loads,dumps=ujson.dumps)# client.host="xxx" needed when verify is enabledpprint(awaitclient.port_test())data=awaitclient.torrent_add(filename="magnet:?xt=urn:btih:091e5c8b3b3f4c4fac68c0867b4c5740365d79fb&dn=%5B210730%5D%5B%E9%88%B4%E6%9C%A8%E3%81%BF%E3%82%89%E4%B9%83%5D%E3%83%88%E3%82%A4%E3%83%AC%E3%81%AE%E8%8A%B1%E5%AD%90%E3%81%95%E3%82%93VS%E5%B1%88%E5%BC%B7%E9%80%80%E9%AD%94%E5%B8%AB%20%EF%BD%9E%E6%82%AA%E5%A0%95%E3%81%A1%E3%83%9E%E2%97%8B%E3%82%B3%E3%81%AB%E5%A4%A9%E8%AA%85%E3%82%B6%E3%83%BC%E3%83%A1%E3%83%B3%E9%80%A3%E7%B6%9A%E4%B8%AD%E5%87%BA%E3%81%97%EF%BD%9E%20%E7%AC%AC%E4%B8%89%E6%80%AA%EF%BC%88%E3%81%A0%E3%81%84%E3%81%95%E3%82%93%E3%81%8B%E3%81%84%EF%BC%89%20%E6%88%A6%E6%85%84%E3%80%8E%E4%BA%BA%E9%9D%A2%E7%8A%AC%E3%80%8F%EF%BC%81%E5%81%A5%E5%BA%B7%E5%84%AA%E8%89%AF%E7%8A%AC%E8%80%B3%E2%97%8B%E5%A5%B3%E3%81%AB%E5%88%9D%E3%82%81%E3%81%A6%E3%81%AE%E6%80%A7%E6%95%99%E8%82%B2%28No%20Watermark%29.mp4&tr=http%3A%2F%2Fsukebei.tracker.wf%3A8888%2Fannounce&tr=udp%3A%2F%2Fopen.stealth.si%3A80%2Fannounce&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337%2Fannounce&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969%2Fannounce&tr=udp%3A%2F%2Fexodus.desync.com%3A6969%2Fannounce")pprint(data)asyncio.run(main())Rpc methods are listedhere
aiotracemoeapi
No description available on PyPI.
aiotraceroute
Simple asynchronous tracerouteDead simple module which provides asynchronous traceroute with asynchronous dns resolution.Needs root privileges to be executed (for raw socket)Installationpip install aiotracerouteExampleimportasynciofromaiotracerouteimportaiotracerouteasyncdefmain(dest):# print hop by hopasyncforn,addr,hostinaiotraceroute(dest):print(n,addr,host)# Or run it without iteratingtr=aiotraceroute(dest)result=awaittr.run()print(result)asyncio.get_event_loop().run_until_complete(main("google.com"))APITheaiotraceroutefunction takes the following arguments:dest: Traceroute destination, can either be a hostname or an IP address.port: Destination port (optionnal, default: 33434)max_hops: Maximum number of hops before reaching final destination (optionnal, default: 30)timeout: Timeout between each hop (optionnal: default: 1s)packet_size: Pakcte size in bytes to send each time (optionnal: default: 60)Therun()method runs the traceroute and returns a list of tuples containing hop_number, address or None, hostname or NonePython versionsPython >= 3.6 are supportedTestsThis project usesunittest. Runmake initthensudo make test
aiotractive
aiotractiveUnofficialAsynchronous Python client for theTractiveREST API.This project and it's author are not affilated with Tractive GmbHThis project is a result of reverse engineering of the Tractive web app.Inspired byhome_assistant_tractive.Initially some code was borrowed from home_assistant_tractive, but in the end all of it was replaced with my own implementations.The package is in active development.Not all features available in the Tractive web app are implemented.Important notes:In order to use Tractive devices and their service you need to have an active subscription.Tractive may change their API at any point of time and this project will be broken. Please, report any issues.Installationpip install aiotractiveUsageimportasynciofromaiotractiveimportTractiveasyncdefmain():asyncwithTractive("email","password")asclient:# interact with the client herepassif__name__=="__main__":asyncio.run(main())TractiveTractive is the entrypoint class, it acts as an async context manager and provides access to API endpoints.Authenticationclient.authenticate()# {'user_id': 'user_id', 'client_id': 'client_id', 'expires_at': 1626821491, 'access_token': 'long access token'}Trackerstrackers=awaitclient.trackers()tracker=trackers[0]# Ortracker=client.tracker("TRACKER_ID")# Retrieve detailsawaittrackers.details()# Includes device capabilities, battery status(not level), charging state and so onawaittracker.hw_info()# Includes battery level, firmware version, model and so on# Retrieve current locationawaittracker.pos_report()# Includes coordinates, latitude, speed and so on# Retrieve hardware info# Retrive history positions```pythonnow=datetime.timestamp(datetime.now())time_from=now-3600*LAST_HOURStime_to=nowformat=json_segmentsawaittracker.positions(time_from,time_to,format):Control the buzzerawait set_buzzer_active(True) # or FalseControl the LEDawait set_led_active(True) # or FalseControl the live trackingawait set_live_tracking_active(True) # or False#### Trackable objects (usually pets) ```python objects = await client.trackable_objects() object = objects[0] # Retrieve details await object.details() # Includes pet's name, pet's tracker id and so onEventsasyncforeventinclient.events():pp(event)After connecting you will immediately receive onetracker_statusevent per owned tracker. The first event always includes full current status of the tracker including current position, battery level, states of the buzzer, the LED and the live tracking.All following events will have the same name, but only include one of these: either a position, battery info, or a buzzer/LED/live status.ContributionYou know;)
aiotrade
Is an open-source event-driven backtesting and live trading platform.
aiotradier
aiotradierPython library to access Tradier´s API using Async IOTradier's documentation is athttps://documentation.tradier.com/brokerage-apiThis is a very lightweight library to wrap Tradier's API. It implements functions to access most of the endpoints for Accounts, Market Data, and Trading. It does not include yet functions to access Authentication or Watchlists. Instead of authenticating with the API, you can obtain a token by logging into your account.RequirementsPython >= 3.11InstallpipinstallaioatradierInstall from SourceRun the following command inside this folderpipinstall--upgrade.ExamplesExamples can be found in theexamplesfolder
aiotrading
IntroductionCrypto exchange APIs are often callback-oriented. This makes coding a nightmare and will distract you from your most important goal of developing a winning strategy.aiotrading is here to solve this problem. Using it, interacting with exchanges will be as much fun as the followingexample:from aiotrading import CandleStream from aiotrading.exchange import BinanceFutures async with BinanceFutures() as exchange: async with CandleStream(exchange, 'btcusdt', '3m') as stream: for i in range(10): candle = await stream.read() log.info(candle)Sample output of this code example is:connecting to exchange: binance-futures opening candle stream btcusdt@3m candle btcusdt, 3m, t:2021-01-30 11:39:00, o:33795.69, h:33800.00, l:33789.99, c:33795.18, v:4.164 candle btcusdt, 3m, t:2021-01-30 11:39:00, o:33795.69, h:33800.00, l:33789.99, c:33799.76, v:4.481 candle btcusdt, 3m, t:2021-01-30 11:39:00, o:33795.69, h:33800.00, l:33789.99, c:33797.73, v:4.741 candle btcusdt, 3m, t:2021-01-30 11:39:00, o:33795.69, h:33800.00, l:33789.99, c:33797.47, v:5.132 candle btcusdt, 3m, t:2021-01-30 11:39:00, o:33795.69, h:33800.89, l:33789.99, c:33797.39, v:5.520 candle btcusdt, 3m, t:2021-01-30 11:39:00, o:33795.69, h:33800.89, l:33789.99, c:33797.38, v:5.605 candle btcusdt, 3m, t:2021-01-30 11:39:00, o:33795.69, h:33800.89, l:33789.99, c:33797.39, v:6.000 candle btcusdt, 3m, t:2021-01-30 11:39:00, o:33795.69, h:33807.99, l:33789.99, c:33806.80, v:16.562 candle btcusdt, 3m, t:2021-01-30 11:39:00, o:33795.69, h:33807.99, l:33789.99, c:33797.70, v:16.590 candle btcusdt, 3m, t:2021-01-30 11:39:00, o:33795.69, h:33807.99, l:33789.99, c:33794.60, v:17.342 closing candle stream btcusdt@3m disconnecting from exchange: binance-futuresInstallationpip3 install aiotradingDesign PrinciplesThin portable API. Lots of exchanges exist in the wild and developers like to migrate from exchange to exchange with no hassle.Easy concurrency. No callbacks as they distract from the goal and introduce errors.Statusaiotrading is at its early stage of development. It currently supports a subset ofBinance exchange API services. More services will be supported in the future. It is designed in a way that other exchanges can be supported easily.
aiotrans
Simple async Google Translate libraryInstalation:pip install aiotrans[aiohttp]orpip install aiotrans[httpx]FeatruresFast and reliable - it uses the same servers that translate.google.com usesSupport for httpx and aiohttpFully asyncio supportSimple result cachingExamplefromasyncioimportrunfromaiotransimportTranslaitorasyncdefmain():t=Translaitor()print(awaitt.translate("Hello",target='ru',source='en'))awaitt.transport.close()run(main())
aiotranslate
aiotranslateFree google translate module that uses async/await syntax.ExamplefromaiotranslateimportTranslatorimportasyncioasyncdefmain():translator=Translator()# you can add aiohttp session if you want like -> Translator(session=aiohttp.ClientSession())# also you can save the translates like -> Translator(save_translates=True)translated=awaittranslator.translate("hello","tr","en")# first argument: the text will be translated# second argument: the language will converted# last argument: the language that textprint(translated)# -> Merhabaprint(translator.history())# shows all translates that saved.if__name__=="__main__":loop=asyncio.get_event_loop()loop.run_until_complete(main())
aiotraversal
No description available on PyPI.
aiotrello
aiotrelloAsync Trello Python libraryInstallationInstall withpip$pipinstallaiotrelloExamplesimportasyncio;loop=asyncio.get_event_loop()fromaiotrelloimportTrellotrello=Trello(key="123",token="abc123")# Initialize a new Trello clientasyncdefmain():# Create 10 boards and make a list for eachforiinrange(10):board=awaittrello.create_board(f"Board{i}")awaitboard.create_list("My List")# Delete all boards that start with "Board"forboardinawaittrello.get_boards():ifboard.name.startswith("Board"):awaitboard.delete()# Get a board and list, then make a new card, and finally, add a comment to itmy_board=awaittrello.get_board(lambdab:b.id=="123")my_list=awaitmy_board.get_list(lambdal:l.name=="My List")card=awaitmy_list.create_card("Hello World","Here is my awesome card")awaitcard.add_comment("aiotrello rocks!")# Move card (above example) to a different listmy_other_list=awaitmy_board.get_list(lambdal:l.name=="My Other List")awaitcard.move_to(my_other_list)# also supports moving to external boardsboard2=awaittrello.get_board(lambdab:b.name=="My Other Board")list2=awaitboard2.get_list(lambdal:l.name=="My Other List")awaitcard.move_to(list2,board2)# Edit a card (above), archive it, and then delete itawaitcard.edit(name="This card will be deleted soon..")awaitcard.archive()awaitcard.delete()try:loop.run_until_complete(main())finally:loop.run_until_complete(trello.session.close())# Remember to close the session!SupportJoin ourDiscord Server
aioTrends
aioTrendsIntro.This is a project for asynchronously obtaining data from google trends in an efficient way. Inspired bypytrends, I am developing this project based on a asynchronous framework, asyncio, and a related module,aiohttp.The logic behind this project is to firstly build a cookies pool, then obtain and store the tokenized queries (wrapped inside the widgets) in another pool, and lastly retreive the data with widgets from the widget pool.Only data of interest over time is tested and avaiable now.Pros & ConsProsSaving time~ By employing the asynchronous framework, the programme will deal with other requests while waiting for responses from Google Trends, saving the waiting time.Saving repeated requests~ Suffering from broken connections and being tired of restarting the requests process? This programme separates the whole process into (1) building a cookies pool, (2) building a widgets pool and (3) retrieving data. The programme can be started from either sub-stage, avoiding sending repeated requests.Unlimited tasks amount~ Tons of queries? The programme will handle that for you automatically.ConsHeavily relying on proxies~ When running on a large amount of queries, proxies would be required for successfully catching responses. In this context, a small amount of rotating proxies or a large amount of static proxies would be required.Only timeseries interest data is avaiable now~ Will test others in the future.Requirementspython >= 3.10aiohttpaiofilesnumpypandasFilesSettings can be customized by amending the settings.json under the foler settings.An example input of queries is given under the data folder.An example of proxies file is given under the proxies folder.The file userAgents.json is fromSaid-Ait-Driss.Before StartI. Initial stageInstallPython version at least 3.10if you don't have one, I use python 3.11 in this exampleInstall package via pip command line. (On macOS's terminal or WindowsOS's CMD)pip install aioTrends pip install virtualenvCreate a virtual environment, named as atenv, for running python3.11 without affecting your other setups.where python3.11copy the path to python 3.11 and replace below pathvirtualenv -p /path/to/python3.11 atenvActivate the virtual environmentOn Windows:atenv\Scripts\activateOn macOS and Linux:source atenv/bin/activateInstall aioTrends ********the package must be installed under the environment of python 3.10+pip install aioTrendsChecking if installed properly. The programme will creat folders, please follow the instructions given by the programme.cd path/to/your/working/path python import aioTrends as atAmend the settings.json under the folder 'settings'.Paste proxies to the proxies.txt under the folder 'proxies'.Get userAgents.json file fromSaid-Ait-Drissand past it under the folder 'settings'.Getting StartedII. Setup a queries fileimportpickleqrys={0:{'keywords':['AAPL'],'periods':'2007-01-01 2007-08-31','freq':'D'},1:{'keywords':['AMZN'],'periods':'all','freq':'M'},2:{'keywords':['AAPL','AMZN'],'periods':'all','freq':'M'},...10000:{'keywords':['MSFT'],'periods':'2004-01-01 2022-12-31','freq':'M'}}pickle.dump(qrys,open('./data/qrys.pkl','wb'))Alternatively, functionformQuerieswould form the query dataset based on the list of keywords you give.fromaioTrendsimportformQueriesfromdatetimeimportdateimportpickleqrys=formQueries(keywords=['AMZN','MSFN'],start='2004-01-01',end=date.today(),freq='D')pickle.dump(qrys,open('./data/qrys.pkl','wb'))III. Create a py script named as example.pyimportaioTrendsasat#Step 0: Set the log file. Other settings can be customized by amending the settings.json under the folder settings.at.setLog('./data/hello.log')#Step 1: collect 1000 cookies with 100 cocurrent tasks. Cocurrent tasks amount can be customized.at.CookeisPool(100).run(1000)#Step 2: get widgets with 100 cocurrent tasks. Cocurrent tasks can be customized.at.WidgetsPool(100).run()#Step 3: get data with 100 cocurrent tasks. Cocurrent tasks can be customized.at.DataInterestOverTime(100).run()Alternatively, you can use below one line for forming queries and getting daily scaled data or monthly data.importaioTrendsasatfromdatetimeimportdateqry_list=['AMZN','AAPL','MSFT']# running 50 cocurrent tasksataio=at.Aio(50)df=ataio.getScaledDailyData(keywords=qry_list,# the query keyword listfilename='test.csv',# json and pickle are both supportedstart='2004-01-01',# both datetime and str are supportedend=date.today())fig=df.plot(figsize=(16,8),title='TEST_SCALED_DAILY_DATA').get_figure()fig.savefig('test_scaled_daily_data.png')df_m=ataio.getMonthlyData(keywords=qry_list,start='2004-01-01',end='2022-12-31')fig=df_m.plot(figsize=(16,8),title='TEST_MONTHLY_DATA').get_figure()fig.savefig('test_monthly_data.png')IV. Run the above example.py file on your terminal or cmd (The code need to be running under the python 3.10+ environment)python example.py
aiotrino
IntroductionThis package provides a asyncio client interface to queryTrinoa distributed SQL engine. It supports Python 3.7, 3.8, 3.9, 3.10, 3.11, 3.12.Installation$ pip install aiotrinoQuick StartUse the DBAPI interface to query Trino:importaiotrinoconn=aiotrino.dbapi.connect(host='localhost',port=8080,user='the-user',catalog='the-catalog',schema='the-schema',)cur=awaitconn.cursor()awaitcur.execute('SELECT * FROM system.runtime.nodes')rows=awaitcur.fetchall()awaitconn.close()Or with context managerimportaiotrinoasyncwithaiotrino.dbapi.connect(host='localhost',port=8080,user='the-user',catalog='the-catalog',schema='the-schema',)asconn:cur=awaitconn.cursor()awaitcur.execute('SELECT * FROM system.runtime.nodes')rows=awaitcur.fetchall()This will query thesystem.runtime.nodessystem tables that shows the nodes in the Trino cluster.The DBAPI implementation inaiotrino.dbapiprovides methods to retrieve fewer rows for exampleCursorfetchone()orCursor.fetchmany(). By defaultCursor.fetchmany()fetches one row. Please settrino.dbapi.Cursor.arraysizeaccordingly.For backwards compatibility with PrestoSQL, override the headers at the start of your applicationimportaiotrinoaiotrino.constants.HEADERS=aiotrino.constants.PrestoHeadersBasic AuthenticationTheBasicAuthenticationclass can be used to connect to a LDAP-configured Trino cluster:importaiotrinoconn=aiotrino.dbapi.connect(host='coordinator url',port=8443,user='the-user',catalog='the-catalog',schema='the-schema',http_scheme='https',auth=aiotrino.auth.BasicAuthentication("principal id","password"),)cur=awaitconn.cursor()awaitcur.execute('SELECT * FROM system.runtime.nodes')rows=awaitcur.fetchall()awaitconn.close()JWT Token AuthenticationTheJWTAuthenticationclass can be used to connect to a configured Trino cluster:importaiotrinoconn=aiotrino.dbapi.connect(host='coordinator url',port=8443,catalog='the-catalog',schema='the-schema',http_scheme='https',auth=aiotrino.auth.JWTAuthentication(token="jwt-token"),)cur=awaitconn.cursor()awaitcur.execute('SELECT * FROM system.runtime.nodes')rows=awaitcur.fetchall()awaitconn.close()TransactionsThe client runs by default inautocommitmode. To enable transactions, setisolation_levelto a value different thanIsolationLevel.AUTOCOMMIT:importaiotrinofromaiotrinoimporttransactionasyncwithaiotrino.dbapi.connect(host='localhost',port=8080,user='the-user',catalog='the-catalog',schema='the-schema',isolation_level=transaction.IsolationLevel.REPEATABLE_READ,)asconn:cur=awaitconn.cursor()awaitcur.execute('INSERT INTO sometable VALUES (1, 2, 3)')awaitcur.fetchone()awaitcur.execute('INSERT INTO sometable VALUES (4, 5, 6)')awaitcur.fetchone()The transaction is created when the first SQL statement is executed.trino.dbapi.Connection.commit()will be automatically called when the code exits thewithcontext and the queries succeed, otherwise `trino.dbapi.Connection.rollback()' will be called.DevelopmentGetting Started With DevelopmentStart by forking the repository and then modify the code in your fork.Clone the repository and go inside the code directory. Then you can get the version with./setup.py --version.We recommend that you usevirtualenvfor development:$ virtualenv .venv $ . .venv/bin/activate # TODO add requirements.txt: pip install -r requirements.txt $ pip install .For development purpose, pip can reference the code you are modifying in avirtualenv:$ pip install -e .[tests]That way, you do not need to runpip installagain to make your changes applied to thevirtualenv.When the code is ready, submit a Pull Request.Code StyleFor Python code, adhere to PEP 8.Prefer code that is readable over one that is "clever".When writing a Git commit message, follow theseguidelines.Running TestsThere is a helper scripts,run, that provides commands to run tests. Type./run teststo run both unit and integration tests.aiotrinousespytestfor its tests. To run only unit tests, type:$ pytest testsThen you can pass options like--pdbor anything supported bypytest --help.To run the tests with different versions of Python in managedvirtualenvs, usetox(see the configuration intox.ini):$ toxTo run integration tests:$ pytest integration_testsThey pull a Docker image and then run a container with a Trino server:the image is namedtrinodb/trino:${TRINO_VERSION}the container is namedaiotrino-python-client-tests-{uuid4()[:7]}Test setupSupported OS Ubuntu 22.04Installpyenvcurlhttps://pyenv.run|bashInstall required python versions# Install the latest of all supported versionspyenvinstall3.7,3.8,3.9,3.10,3.11,3.12Set the installed versions as default for the shell. This allowstoxto find them.List installed versions and update the following command as needed.pyenvversionspyenvshell3.12.13.11.33.10.113.9.163.8.163.7.16InstalltoxpipinstalltoxRuntoxtoxReleasingSet up your development environment.Change version inaiotrino/__init__.py.Commit and create an annotated tag (git tag -m '' current_version)Run the following:..venv/bin/activate&&pipinstalltwinewheelsetuptools&&rm-rfdist/&&./setup.pysdistbdist_wheel&&twineuploaddist/*&&openhttps://pypi.org/project/aiotrino/&&echo"Released!"Push the branch and the tag (git push upstream master current_version)Send release announcement.Need Help?Feel free to create an issue as it make your request visible to other users and contributors.If an interactive discussion would be better or if you just want to hangout and chat about the Trino Python client, you can join us on the#python-clientchannel onTrino Slack.
aiotrivia
aiotriviaAsync Wrapper for the OpenTDB APIInstallation$pipinstallgit+https://github.com/niztg/aiotriviaExample Usageimportasyncioimportaiotriviaclient=aiotrivia.TriviaClient()asyncdefmain():data=awaitclient.get_specific_question(category=20)foriindata:print('%s|%s'%(i.question,i.responses))awaitclient.close()# after you're done with everythingasyncio.get_event_loop().run_until_complete(main())Returns:Which figure from Greek mythology traveled to the underworld to return his wife Eurydice to the land of the living? | ['Daedalus', 'Hercules', 'Perseus', 'Orpheus']discord.py command usagefromaiotriviaimportTriviaClient,AiotriviaExceptionfromdiscord.extimportcommandsimportasyncioimportrandomclassTriviaCog(commands.Cog):def__init__(self,bot):self.bot=botself.trivia=TriviaClient()@commands.command()asyncdeftrivia(self,ctx,difficulty):try:question=awaitself.trivia.get_random_question(difficulty)exceptAiotriviaExceptionaserror:returnawaitctx.send(f"{error.__class__.__name__}:{error}")answers=question.responsesrandom.shuffle(answers)final_answers='\n'.join([f"{index}.{value}"forindex,valueinenumerate(answers,1)])message=awaitctx.send(f"**{question.question}**\n{final_answers}\n{question.type.capitalize()}Question about{question.category}")answer=answers.index(question.answer)+1awaitself.trivia.close()# cleaning uptry:whileTrue:msg=awaitself.client.wait_for('message',timeout=15,check=lambdam:m.id!=message.id)ifstr(answer)inmsg.content:returnawaitctx.send(f"{answer}was correct! ({question.answer})")exceptasyncio.TimeoutError:awaitctx.send(f"The correct answer was{question.answer}")defsetup(bot):bot.add_cog(TriviaCog(bot))For more info, read the documentationOr join the discord server
aiotriviapy
triviapytriviapy is an async API wrapper foropen trivia databasethis is still a WIP but currently can return questions from specific or all categories and select the number you want to return.SetupMake sure you have python installedDownload the repositoryMake sure you have aiohttp installedPlace the triviapy folder in your project folder and have fun.Quick StartA:First import Game from triviapy and construct a Game object:fromtriviapyimportGamegame=Game()(optional) Set a game token, this will prevent repeat questions from occuring:awaitgame.gen_token()To see the categories avaliable you can dogame.categories(), this returns the below array of category names and ID's, to use a category supply the number for the category you'd like questions from:[('General Knowledge',9),('Entertainment: Books',10),('Entertainment: Film',11),('Entertainment: Music',12),('Entertainment: Musicals & Theatres',13),('Entertainment: Television',14),('Entertainment: Video Games',15),('Entertainment: Board Games',16),('Science & Nature',17),('Science: Computers',18),('Science: Mathematics',19),('Mythology',20),('Sports',21),('Geography',22),('History',23),('Politics',24),('Art',25),('Celebrities',26),('Animals',27),('Vehicles',28),('Entertainment: Comics',29),('Science: Gadgets',30),('Entertainment: Japanese Anime & Manga',31),('Entertainment: Cartoon & Animations',32)]Create a round with question info, you can supplyqtyandcategoryas ints to specify the number of questions and what category you want. It defaults to one question of any category and returns aQuestionobject if only one if given or an array of them if multiple questions are requested.# This will give 10 questions from the music category.round_example=game.round(quantity=10,category=12)# This will give one question from a random categoryround_2=game.round()Question objects hold all the info needed about a question including: question, category, answers, correct answer, and difficulty:question=round_example[0]question_str=question.question# Returns the question as a stranswers=question.answers# Returns a preshuffled array with the 4 multiple choice answer posibilitiesanswer=question.answer# Returns the str of the answer, this is included in the answers array as well in the same str format.category=question.category# Returns the category of the question as a strdifficulty=question.difficulty# Returns the question difficulty (Easy, Medium or Hard)Error HandlingImporting errors:fromtriviapy.errorsimportTokenError,QuestionError,InvalidTokenError,CategoryErrorTokenErrorThis error will occur isgame.token()is unable to set a token, this error may be caused by opentdb outages or other errors.QuestionErrorThis error will occur if the number of questions exceeds that avaliable, when this occurs doawait game.reset()to reuse questions.InvalidTokenErrorThis error is raised due to an invalid or expired token, an api token will expire after 6 hours of no use. Do ``await game.gen_token``` to reset this.CategoryError:This error will occur if an invalid int is defined for a round category. To fix this double check what you are putting in.
aiotruenas-client
Python Module for TrueNAS Websocket APIThis python module utilizes theTrueNAS Websocket APIto get state from a TrueNAS instance.Installationpip install aiotruenas-clientUsagefromaiotruenas_clientimportCachingMachineasTrueNASMachinemachine=awaitTrueNASMachine.create("hostname.of.machine",api_key="someapikey")datasets=awaitmachine.get_datasets()disks=awaitmachine.get_disks()jails=awaitmachine.get_jails()pools=awaitmachine.get_pools()vms=awaitmachine.get_vms()Alternatively, a username and password may also be supplied.MachineObject representing a TrueNAS instance.DatasetAvailable frommachine.datasets, contains information about the datasets on the pools on the machine.DiskAvailable frommachine.disks, contains information about the disks attached to the machine.JailAvailable frommachine.jails, contains information about the jails available on the machine.PoolAvailable frommachine.pools, contains information about the ZFS pools known to the machine.VirturalMachineAvailable frommachine.vms, contains information about the virtural machines available on the machine.Each instance has the following methods availabe:vm.startvm.stopvm.restartDevelopmentSetuppython3.8 -m venv .venv source .venv/bin/activate # Install Requirements pip install -r requirements.txt # Install Dev Requirements pip install -r requirements-dev.txt # One-Time Install of Commit Hooks pre-commit installWorking With Methods & SubscriptionsWhen adding support for a new object, or updating existing code, it can be useful to see the raw response from the TrueNAS machine from time to time. In order to help do that easily, you can drop a.auth.yamlfile in the root of the repository, with the following content:host:"some.host.name"api_key:"someapikey"Usescripts/invoke_method.pyto call a method:python scripts/invoke_method.py disk.queryUsescripts/subscribe.pyto subscribe to a topic:python scripts/subscribe.py reporting.realtimeRun either with -h to see additional options.TestingTests are run withpytest.
aiotsl2591
aiotsl2591is a Python 3 module to read data asynchronously from TSL2591 luminosity 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
aiot-studio
AIoT StudioAIoT Studio is the official library to develop datasources, notebooks and dependency sets formnubo's AIoT Studio.InstallationRequirementsPython 2.7 or Python 3.4 and uprequestspandas≥ 0.20numpy$ pip install aiot-studioSimple datasource usagefromaiotstudio.searchimportto_pandasfromaiotstudio.loggingimportlogdefexecute(parameters):log.info("Hello aiot-studio")result=to_pandas({"from":"event","select":[{"count":"*"}]})returnresultConfigurationThe library needs to be configured with yourmnubo API credentials. The credentials can be shared as follows (by decreasing order of priority):Environment variables:MNUBO_CLIENT_ID,MNUBO_CLIENT_SECRET,MNUBO_API_URLLocal config file:application.confat the root of the project or anywhere indicated by theMNUBO_CONFIG_FILEenvironment variableGlobal config file:~/.settings/mnubo/application.conf(orC:\Users\<username>\.settings\mnubo\application.confon Windows)For the last two options, the configuration file should look like this:[DEFAULT] mnubo_client_id = {API_CLIENT_ID} mnubo_client_secret = {API_CLIENT_SECRET} mnubo_api_url = https://prod.api.mnubo.comAvailable packagesearchblobstoreloggingNotes:All "search" methods expect a MQL query as described in thesearch APIdocumentationBlob store methods are only available when the code runs inside mnubo's architecture, using it locally would throw aFeatureUnavailableError
aiotube
aiotubeA library to access YouTube Public Data without YouTubeAPIDiscordGitHubREST API (BETA)Table of ContentsInstallationBuildingQuick StartUsageChannelVideoPlaylistInstallingPython 3.6 or higher is required# Linux/macOSpython3-mpipinstall-Uaiotube# Windowspython-mpipinstall-UaiotubeBuild from sourcepipinstallgit+https://github.com/jnsougata/aiotubeQuick Startimportaiotubechannel=aiotube.Channel('UCU9FEimjiOV3zN_5kujbCMQ')print(channel.metadata)# channel metadata in dict formatvideo=aiotube.Video('WVDT4lSozHk')print(video.metadata)# video metadata in dict formatplaylist=aiotube.Playlist('PL-xXQjd8X_Q-xXQjd8X_Q-xXQjd8X_Q-')print(playlist.metadata)# playlist metadata in dict formatsearch=aiotube.Search.video('YouTube Rewind 2018')print(search.metadata)# searched video metadata in dict formatsearch=aiotube.Search.channel('PewDiePie')print(search.metadata)# searched channel metadata in dict formatsearch=aiotube.Search.playlist('Unlock Your Third Eye')print(search.metadata)# searched playlist metadata in dict formatUsageChannelMethodReturn TypeDescriptionlive()boolReturns True if the channel is livestreaming_now()VideoReturns the video the channel is streaming nowcurrent_streams()List[str]Returns a list of ids of currently streaming videosold_streams()List[str]Returns a list of ids of previously streaming videosvideo_count()intReturns the number of videos uploaded by the channelupcoming()VideoReturns a video object of the upcoming videoupcomings()List[str]Returns a list of ids of upcoming videosplaylists()List[str]Returns a Playlist objectuploads(limit: int)List[str]Returns a list of video ids of the uploaded videoslast_uploaded()VideoVideo object of the most recently uploaded videolast_streamed()VideoVideo object of the most recently streamed videoPropertiesReturn TypesDescriptionmetadatadictReturns the metadata of the channel in dict formatVideoPropertiesReturn TypesDescriptionmetadataDict[str, Any]dictionary of video metadataPlaylistPropertyReturn TypeDescriptionmetadataDict[str, Any]dictionary of playlist metadataSearchMethodsReturn TypesDescriptionchannel(name: str)ChannelChannel object of the channel with the given keywordsvideo(name: str)VideoVideo object of the video with the given keywordsplaylist(name: str)PlaylistPlaylist object of the playlist with the given keywordschannels(name: str, limit: int)List[str]list of channel ids of the channels found with the given keywordsvideos(name: str, limit: int)List[str]list of video ids of the videos found with the given keywordsplaylists(name: str, limit: int)List[str]list of playlist ids of the playlists found with the given keywords
aiotubes
AIOTUBEaiotubeAsynchronous YouTube APIExampleimportasynciofromaiotubeimportVideoasyncdefmain():client=Video("https://www.youtube.com/watch?v=MZ-cvXEvYI8")stream=(awaitclient.streams()).get_audio_only()awaitstream.download_filepath(filename="yeat.mp3")asyncio.run(main())
aiotus
aiotus - Asynchronous tus client libraryaiotusimplements the client-side of thetusprotocol.FeaturesImplements thecore protocolas well as thecreationandconcatenationextensions.Built-in retry support in case of communication errors.Extensive test bench, including tests against the referencetusdserver.Usageimportaiotuscreation_url="http://example.com/files"metadata={"Filename":"image.jpeg".encode(),"Content-Type":"image/jpeg".encode()}# Upload a file to a tus server.withopen("image.jpeg","rb")asf:location=awaitaiotus.upload(creation_url,f,metadata)# 'location' is the URL where the file was uploaded to.# Read back the metadata from the server.metadata=awaitaiotus.metadata(location)RequirementsPython≥ 3.8aiohttptenacityInstallationInstallaiotusfromPyPi:pip install aiotusDevelopment versions can be installed fromTestPyPi:pip install --index-url https://test.pypi.org/simple --extra-index-url https://pypi.org/simple aiotusDocumentationThe documentation can be found ataiotus.readthedocs.io.Licenseaiotusis licensed under the Apache 2.0 license.
aiotusclient
tus.io uploader for Python asyncioaiotusclient is a fork of tus-py-client rewritten for Python asyncio and aiohttp. It is used to communicate with storage proxies that handle large transfers for vfolder uploads and downloads.Package Structureaiotusclientclient: The client instance class which communicates between Backend.AI ManagerbaseuploaderanduploaderResponsible for chunking the file and asynchronously uploading to tus serverrequestHandles the uploading requestInstallationPrequisitesPython 3.7 or higher withpyenvandpyenv-virtualenv(optional but recommneded)Installation ProcessFirst, prepare the source clone of this agent:#gitclonehttps://github.com/lablup/aiotusclientFrom now on, let's assume all shell commands are executed inside the virtualenv. And we located in backend.ai root directory.Now install dependencies:#pipinstall-UaiotusclientWhen done, import into your code the aiotusclientfromaiotusclientimportclienttus_client=client.TusClient(session_create_url,session_upload_url,rqst.headers,params)ReferenceThis library was forked fromtus-py-clientand customized in order to facilitate asynchronous communication with our TUS server.
aiotuya
# aiotuyaaiotuya ia a Python library for LAN control of Tuya devices. It can detect, provisionand control devices that connect to the [Tuya Cloud](https://www.tuya.com).To make things easy to the user, aiotuya comes with an application key and secretthat were provided by [Tuya Cloud](https://www.tuya.com). We request that youdo not use these key and secret for any other purpose.# AcknowledgementAll credits for figuring out how those device communicate goes to [codetheweb](https://github.com/codetheweb/tuyapi)and all the participants to this [conversation](https://github.com/codetheweb/tuyapi/issues/5). All I did isport their work to Python with asyncio and added bugs.# InstallationComing soon... we will upload to PypiIn the meantime....``` shellpython3 setup.py install```# UsageThe easiest way to start is running the module``` shellpython3 -m aiotuya```Which, the first time around, will give you absolutely nothing. You want tostart with``` shellpython3 -m aiotuya -e [email protected] -p mypass -s WIFISSID -P WIFISECRET```After you hit the "Enter" you should get``` shellHit "Enter" to startUse Ctrl-C to quitSelect Device:[0] Provision new devices```Ready you devices for configuration and hit 0 followed by enter.Then wait, hiting the "Enter" key from time to time.You can also use the '-d' option to get debug messages. These are not suitable for human consumption and areknown to cause cancer in rats.## Provisioning CaveatFor provisioning to work, you must be able to send broadcast packets over WiFi.In my case, I was only able to use provisioning on a laptop connected to myhouse WiFi. Trying from a wired computer did not work. Apparently my router (Asus RT-AC5300)did not relay the packets. Your milage may vary.Provisioning is also working on a RPi3 connected through WiFi (Note that I use a USB WiFi dongle toconnect, not the RPi3 WiFi module)Provisioning is NOT YET working from a RPi2 (wire connected) with a WiFi dongle.## Remembering devices keysDuring the provisioning process, the device will register with the [Tuya Cloud](https://www.tuya.com).Once the registration has succeeded, the provisioning system will receive a key to be usedwhen communicating with the device. By default, aiotuya will save the pairs (device id, key) in a CSV filein your home directory. The default file name is .aiotuya# The devicesAt this time (Feb '19) aiotuya will handle 3 types of devices## SwitchA simple On/Off switch is provided by ``` TuyaSwitch ``` . It has 2 methods:* on()* off()And the status will be reported as``` python{'state': 'on'}{'state': 'off'}```## Open/Close/Idle SwitchThis is the kind of switch that can be used for curtains, garage doors and so on. It isprovided with ``` TuyaOCSwitch ```. It has 3 methods:* open()* close()* idle()And the state value can be one of:* closing* opening* idling## LED lightsThis is a colour LED light. It is provided by ``` TuyaLight ``` and offers the following methods:* on()* off()* set_white( brightness, K)* set_colour([hue, saturation, value])* set_colour_rgb([pred, green, blue])* transition_white([bright, K], duration)* transition_colour([h, s, v], duration)* fadein_white(bright, K, duration)* fadeout_white(duration)* fadein_colour([h, s, v], duration)* fadeout_colour(duration)## Other DevicesOther devices can be added, but I do not have the information needed to add them.## Devices caveataiotuya keeps a connection to the device, and send a heartbeat status request every timout secs(10 secs by default). This allows it to receive real time status messages upon changes in the device status(e.g. button pressed on a switch). The downside is that Tuya devices seem to only accept one such aconnection, so aiotuya has exclusive control of the device via LAN. Fortunately, the devices stop broacasting their presencewhen they have a network connection, so other application should not be able to find them. I have not tried to see if thecloud API was still working in that case.# How to use aiotuyaCreate a class to manage your devices. The class should have at least 4 methods:* register(self, device)This will be used to report when a new device has been found.* unregister(self,device)This is called when connection to a device is lost.* got_data(self, data)This is called when a device receive data. The data should be a dictionary. The 'devId' can be used to iscriminate which device received the data* got_error(self, device, data)This is called when an error is received. The device is passed as parameter.Subclass TuyaManager, if you want to persists the device keys, by overloading 2 methods:* load_keys(self)Loading the known keys in the dictionary self.known_devices. called in __init__* persist_keys(self)Save the keys, called when new keys are reported.After that``` pythonMyDevs= Devices()loop = aio.get_event_loop()manager = DevManager(dev_parent=MyDevs)scanner = tuya.TuyaScanner(parent=manager)scanner.start(loop)```## How does it workTuya devices, when they are not connected, broadcast their presence on the network, TuyaScanner listenfor those broadcasts and pass them on to TuyaManager.If the key is known, TuyaManager will create a TuyaDevice generic instance with raw_dps set, using itself as device manager.Upon receiving the device status data, Tuyamanager will try to figure out the type of device and create the proper instanceusing the application device manager to control the device.TuyaManager figures out the type of device it is dealing with by issuing a status request and inspecting the returned value.If an error is returned, ot will try sending a command. The reason for this is that my OC Switch, after powering up, will returna "json struct data unvalid" error to any status request until either, a button is pressed or a valid command is issued. The behaviourof Tuyamanager is meant to circumvent this problem.# Status0.1.0b1: Initial version. Works for me with a LED lightbulb and a Open/Close switch
aiotuyalan
Async Tuya LAN ControlIntegration withTuyaCloudsmart home devices using local LAN control and Python's asyncio library. This library was thrown together in a week to support some cheap bulbs that I bought expecting to useTuya-Converton, but got hit with thelatest firmwareversion from Tuya. At the time, I couldn't find any Python Tuya libraries supporting asyncio for local push use inHome Assistant.I only have tested Tuya lights with this library as that is the only device I own, I will include classes for the additional devices, but they will need to be tested to confirm usage.Example UsageThis library requires the device ID and the local key for the device you want to control. I found it easiest to snag the local key from anolder version of the Smart Life app's preferences.xml on a rooted Android phone. There are other methods you can read abouthere.fromaiotuyalanimportTuyaLightimportasyncioIP='192.168.1.26'LOCAL_KEY='fffff00000ffffff'DEVICE_ID='ffff000fff00f0f0f000'asyncdefmain():loop=asyncio.get_running_loop()device=TuyaLight(loop,IP,DEVICE_ID,LOCAL_KEY,version='3.3')asyncdefon_update():print("Received device update.")awaitdevice.set_color_temp(40)awaitdevice.set_brightness(255)awaitdevice.disconnect()asyncdefon_stop():print("Disconnected from device.")loop.stop()awaitdevice.set_on_update(on_update)awaitdevice.set_on_stop(on_stop)whileTrue:try:awaitdevice.connect()breakexceptExceptionaserr:print("Error occcured during connection: ",err)print("Trying again in 5 seconds...")awaitasyncio.sleep(5)print("Connected to device!")loop=asyncio.get_event_loop()try:asyncio.ensure_future(main())loop.run_forever()exceptKeyboardInterrupt:passfinally:loop.close()
aio-typesense
aio_typesenseAsync Library for Typesense with type hintspipinstallaio_typesenseUsage# examples/example.pyimportasynciofromtypingimportTypedDict,Listfromaio_typesenseimportClient,CollectionclassMovie(TypedDict):id:strname:stryear:intMOVIES:List[Movie]=[{"id":"id1","name":"Wonder Woman","year":2017,"year_facet":"2017"},{"id":"id2","name":"Justice League","year":2017,"year_facet":"2017"},{"id":"id3","name":"Wonder Woman 1984","year":2020,"year_facet":"2020"},{"id":"id4","name":"Death on the Nile","year":2021,"year_facet":"2021"},]asyncdefmain():client=Client(node_urls=["http://localhost:8108"],api_key="Rhsdhas2asasdasj2",)r=awaitclient.collections.create({"name":"movies","num_documents":0,"fields":[{"name":"name","type":"string",},{"name":"year","type":"int32",},{"name":"year_facet","type":"string","facet":True,},],"default_sorting_field":"year",})collection:Collection[Movie]=client.collections["movies"]r=awaitcollection.documents.create_many(documents=MOVIES)print(r)search_r=awaitcollection.documents.search({"q":"wonder woman 2021","query_by":"year_facet,name","query_by_weights":"1,1",})print(search_r["hits"])# [# {# "document": {# "id": "id3",# "name": "Wonder Woman 1984",# "year": 2020,# "year_facet": "2020",# },# "highlights": [# {# "field": "year_facet",# "matched_tokens": ["2020"],# "snippet": "<mark>2020</mark>",# }# ],# "text_match": 1125899907169635,# },# {# "document": {# "id": "id1",# "name": "Wonder Woman",# "year": 2017,# "year_facet": "2017",# },# "highlights": [# {# "field": "year_facet",# "matched_tokens": ["2017"],# "snippet": "<mark>2017</mark>",# }# ],# "text_match": 1125899907169379,# },# {# "document": {# "id": "id4",# "name": "Death on the Nile",# "year": 2021,# "year_facet": "2021",# },# "highlights": [# {# "field": "year_facet",# "matched_tokens": ["2021"],# "snippet": "<mark>2021</mark>",# }# ],# "text_match": 562949953552128,# },# {# "document": {# "id": "id2",# "name": "Justice League",# "year": 2017,# "year_facet": "2017",# },# "highlights": [# {# "field": "year_facet",# "matched_tokens": ["2017"],# "snippet": "<mark>2017</mark>",# }# ],# "text_match": 562949953551616,# },# ]if__name__=="__main__":asyncio.run(main())ContributingPrerequisites:poetrynoxnox-poetryInstall them on your system:pipinstallpoetrynoxnox-poetryRun tests:nox
aioudp
AioUDPA better API for asynchronous UDPAwebsockets-like API forUDPHere's an example echo server:importasyncioimportsignalimportaioudpasyncdefmain():asyncdefhandler(connection):asyncformessageinconnection:awaitconnection.send(message)# Optional. This is for properly exiting the server when Ctrl-C is pressed# or when the process is killed/terminatedloop=asyncio.get_running_loop()stop=loop.create_future()loop.add_signal_handler(signal.SIGTERM,stop.set_result,None)loop.add_signal_handler(signal.SIGINT,stop.set_result,None)# Serve the serverasyncwithaioudp.serve("localhost",9999,handler):awaitstop# Serve foreverif__name__=='__main__':asyncio.run(main())And a client to connect to the server:importasyncioimportaioudpasyncdefmain():asyncwithaioudp.connect("localhost",9999)asconnection:awaitconnection.send(b"Hello world!")assertawaitconnection.recv()==b"Hello world!"if__name__=='__main__':asyncio.run(main())InstallationYou can get this project viapip$pipinstallaioudpOr, if you're usingPoetry$poetryaddaioudp[!NOTE] This library provides no other abstractions over the existing UDP interface inasyncioother than theasync/await-based API. This means there is no implicit protocol handled in this library such asQUIC. You must write your own, or find another library.See alsoAnyIO, a broader asynchronous networking and concurrency library for abstracting over anyasyncIO implementation. It has asimilar API(which I didn't know about before I wrote this library)WebSockets, a library for Python to interact with WebSockets. Its API heavily inspired the design of AioUDP.QUIC, a faster protocol similar to TCP, built on UDP.AioQUIC, a Python implementation of QUIC.LicenseCopyright © 2021, Bryan HuThis project is licensed under theGNU GPL v3+.In short, this means you can do anything with it (distribute, modify, sell) but if you were to publish your changes, you must make the source code and build instructions readily available.If you are a company using this project and want an exception, email me [email protected] we can discuss.
aio-udp-server
Asyncio UDP serverYet another async UDP server. Based on bare sockets.Killer-feature: bandwidth throttling for uploading & downloading.UDPServer.__init__UDP server constructor.Arguments:upload_speed— maximum outgoing traffic speed in "byter per second" (default:0— unlimited);download_speed— maximum incoming traffic speed in "byter per second" (default:0— unlimited);recv_max_size— maximum socket window size for receiving (default:262144).UDPServer.runServer startup function.Arguments:host— socket bind host/interface (e.g. "0.0.0.0", "127.0.0.1" or "localhost");port— socket listen port;loop— event loop.UDPServer.sendEnqueue data for sending.Arguments:data—bytesorbytearraydata for sending;addr— tuple of host and port (e.g.("127.0.0.1", 9876)or("some.domain.com", 5556)).UDPServer.subscribeSubscribe coro or future on a datagram received event.Arguments:fut— coroutine or future with argumentsdataandaddr.UDPServer.unsubscribeUnsubscribe coro or future from a datagram received event.Arguments:fut— coroutine or future.Virtual eventsUDPServer._connection_made()— virtual method, call after socket bind successfully;UDPServer._socket_error(data, addr)— virtual method, call when got socket error;UDPServer._datagram_received(data, addr)— virtual method, call each time when server got incoming data, can be used for modify data before pass it to subscribers;UDPServer._notify_subscribers(data, addr)— virtual method, call with params returned from_datagram_received.ExampleimportasyncioimportdatetimefromaioudpimportUDPServerclassMyUDPServer:def__init__(self,server,loop):self.server=serverself.loop=loop# Subscribe for incoming udp packet eventself.server.subscribe(self.on_datagram_received)asyncio.ensure_future(self.do_send(),loop=self.loop)asyncdefon_datagram_received(self,data,addr):# Override virtual method and process incoming dataprint(datetime.datetime.now(),addr,data)asyncdefdo_send(self):whileTrue:# Any payloadpayload=b'd1:ad2:id20:k\xe7\x90\xcd\x0c_R\xfe\x82\xeb\xa8x\x14\xb4-\x8e0\xe5\x086:target20:\x11\x8e\xcc,\x89\xa4\x99\xf98E\x98\x7f!\xa7w\rz\x1b\x14de1:q9:find_node1:t2:#K1:y1:qe'# Delay for prevent tasks concurencyawaitasyncio.sleep(0.001)# Enqueue data for sendself.server.send(payload,("router.bittorrent.com",6881))asyncdefmain(loop):# Bandwidth speed is 100 bytes per secondudp=UDPServer(download_speed=100,upload_speed=100)udp.run("0.0.0.0",12346,loop=loop)server=MyUDPServer(server=udp,loop=loop)if__name__=='__main__':loop=asyncio.get_event_loop()loop.run_until_complete(main(loop))loop.run_forever()Output:2019-06-04 16:04:07.761576 ('67.215.246.10', 6881) b'd2:ip6:Z\x97\'X0:1:rd2:id20:2\xf5NisQ\xffJ\xec)\xcd\xba\xab\xf2\xfb\xe3F|\xc2g5:nodes416:\x02\xf7\xb7\x1d\x94\xb1\x00\xe8\x84\xca\x9c\xc3\xb09\xbb\x04*P\x8cQ\x1f\x7fF\xa9\x1a\xe1\x00\x13\x99W\x14\xb1\x99\x8b\xff\x8e\xda2\xb3 \xac\x82\xef0sCl\xda+G\xc4\x91\x17bO,\xe8\xbc\x9e\xeb+\xfc.\xe6\xf8\xb0\x82\xee~\x17 \xebvF\x83\xf8\x83\xc1\xdaK\x1b\x83\x17\xfb!\xab\x1e\x97T\xa3\xfa\x9a\x14Q$\x06)\\\xad>O\x03\xc4\x91\x9f/7\xf6>]|\xe0\xc6f\x1eq\xfd\xcc\x0e\xbe\xd0\x85\xde\xf9\xbeJc\xe3e\xe5\x9e\x9d\xca})P\xa5\xfd\x8c\xb66\xb9\xba\x0f\xfc\xb1\xb9\xa3 E\xc9*\x1f\xd1I\xb1r9\xfaI\xf1\xf1\xbb\xe9\xeb\xb3\xa6\xdb<\x87\x0c>\x99$^R\xbc\x85\xd3\xb3C\xab}\xbf6\xcc\x11\x7fv\xde\r\xed\xa4q\xdd\x04#\x8d\xd8j7$[\xe5e\\\xf9V\x166\xb1P\x7f\xa01v\xf49\xb9\x9a\x12*\xad<Q@\xa6\x8d\xd5\xe6wN\xa2\x87\xaf|\xb4KslP\xf5\xd0h\xaf\x1c\xb5\xb6\xc0\xc9\xfa\x0c\xfe\xe8\xb92\n\xb7\xda"8\x019\x95\xe8\xef\xc1u\xa4$\xe5\x0c!\xe2\x10j\xff\x10\xeb\xffu\x02\x87t\x9f\x01|\xa4b\x87\xc4\xa0.\xd2g\x9f\xf6\xd1\xc2\xfd\xef\xa1!a\x04\xdf<\x97)\xbe\xd1\x81l\xb1?W\t\xbb\xc1\xbd\x04\x8ec\xf8\x08\xcd\x1av\x1a\xa9\xb3R^\xb5{\x11\x1a\xe1C\xe1\xb43\x04\x03Wl\xd1E\xa6\x0f\xf7\xcbQ\t\x84W\xd6\xebD\'\xdd=\xb1\xc9\xed\xc6C\xf9\x7f\xfbg\xf9$\x0e\x0b~\xa5\xae\xfdnvr\xe7\xc4.\xf8(\x90\xa4\x84C\xe9\xccK4r\xc6=\xf1\xc09\xdf{\xfc\x10\xe9\xd9\xd8\xa5\xdd.\x00\x88\x0e\xe7]e1:t2:#K1:y1:re' 2019-06-04 16:04:12.622861 ('67.215.246.10', 6881) b'd2:ip6:Z\x97\'X0:1:rd2:id20:2\xf5NisQ\xffJ\xec)\xcd\xba\xab\xf2\xfb\xe3F|\xc2g5:nodes416:\x1e\xe4\xb8\x96\xf5E;\x13\r\x89\n\x1c\xdb\xae2 \x9aP\xee\xcb\xa0\xb0\xcbq\xa4X\x80\x8c>\x91:M\xb67%kY\xc7\xb5\xe1\xe7\x901_u\\\xbd(g\xeb[\xa7-\x1fl\x1e\xd6\x93\xe8g\xdam\n;\xa8y \xf4K\x18\xe0\x11z\xfe\xa6\xf6\xc9\xcfe\xcb\xf9\x7f+"92\xfb/\xd8C>K\x1a\xf9\xe8#\x86\x8dy\x07\xa1\x94>\x81\x17_\xcd\xe9\x03?\x96pX\x1c\xe8v{\xa5W,_ \x0f|Oi\x8bg\xc5J\xfd#\x9e\xf7\xdd\xc4\xa4\xb9\xd0\x8f\xbd\x9d\x98\xfaD\x91N}U{j\xd7\xfak\')\xcdr(\xc3\xdc\xc6\xd7\x9b=\x1d\x12/\xa4\xd5A\x8f[\x98\x07\x10EHq#\xcc\xb8\xae\xf00\xd4\xfd(\xe5fj\xbb\xdd\xa5s\x8b\xec:\xb1\x1d\x93%)S\xdf.\xb3\x17\x95\x9b\xc8\xc0\x95"\x86\x81\x16\x8d]\xdau\x15S\xbcN:\x9d\x83I+Vk\xc4\x91\x0b9t\xbdv`\xb2\x8d7\xae\t\xb1\x8c\x96\x9f\x1c\xa0B\xd0\x93\xbfd\x8e\xe7\xdf`\x14\x13\'<\x92Pn:u\xa0\n\xc3\xcd\x01\x12H\xc65\xeb\xa2X\xc8\xd6\x0b\x81\x1b\xcf\x89\xbco$\x8a\xf97\x920u\xb8i\xde\x15\x19\xc4\x8f\xfb\xc0\xb1\xcf\x99\xd9e1\xf6u\x01\xb7\x1e\xc4\x80\xca\x0e\xcawuv\xc9\xaf[\x0b\xd4\x99\xf4[\xf1\x8ck\x1a\xe1r\xc3\xb4(\xb8ba\x98\x8b\x1e\xb4TN"\xa7F5B\xcb\x0f\x05\x9e\xed-b\x82\xb8\x8d\xed\xf7\xaf?,\xc5)z\xd2f\xc1\xda`.\xf0.!\xf2H\xbezs\xf3\x8c\t\x9c\x9d\xe8\x87Q\xf4\xe9\x8fJ\x0c\x16\xa8\xc55Q\x878<\x04.0Bc!\xade1:t2:#K1:y1:re' 2019-06-04 16:04:17.483860 ('67.215.246.10', 6881) b'd2:ip6:Z\x97\'X0:1:rd2:id20:2\xf5NisQ\xffJ\xec)\xcd\xba\xab\xf2\xfb\xe3F|\xc2g5:nodes416:k*[\x0c1\x9a\xb1\xd6\xe5>G\x0c\xac\xe3v0\xd0\xc2\xb7\x8cI\x93\xb7\xcd\xa8\xf1\xca(\xf8\xc0\xe0\xa6\xd4\xda*\xd4\xf1\xedc\xb4\xdf\xdf\xe2Q\x1a\xe9^\t\x8f\xfa\x1a\xe1$Wr\xe18\x1e\x9a\xce\xabW}\xbfLY\x05\xbd\xce\xa0\x0e\xb1_\x19\xdf>\xcaJS\x00H\xdf\x8d\xeedn\xd7\x07-\x9f\x8at\xb0\x14\xbe\x8d\x1d\x0eO\xa7\x97\xa3\x83\xa9\xb2\xff\xc9K\x97\x01m\xbc\xcb\xc3\x001vR\'s\xffyr\x82UF\\z\xafG\x8f\xc8U\xcf}+\x97\x90\xa2\x1b\x11\xef\xbfs\x80Q\xff\x1dc\x14%\xe8\x87\xac!\xadz\xbd\xcc\xbfq\xaex0\x7f(}jY[W\xdcsx\n|F\x86\xed\xa3\x1a\xe1,\x03\x87to\xd2X\x12\x00\x90\t\xcfu\xec_m\x15\x02\xe1\xf6\xd4\x98\x93\xfa\x1a\xe1\xc8\xa1-tC!\xd1X\xb0\xc9M\xc8\xf2\x94|\xca\x80j\xb8\x04\x05\xceB"_\xc3H\xf1i\x86\xb6\x07Z=\xc2\xb1`m\xab\xbc\xbeB\xb8\nVM]Q\x1cp\xc2L\x83\xca\xe7\xed\x1e\x10\x9d\xc9\xde\xdc[c\xef\xc2_]+N\xaaJ\xc9E0\xf5\x1b\x16q\xe1/\x97w>a\x94\x10\x0f\x94\xc2"\xd6\x89+\xa7\x01\\w%\x90Z_\x1a\xe1\xd9\xf5\xff\xb5D\xf2\x8d\xbc^[j\x16\xb9H\xe3.+\r\x87\xa5aU\xafMT\xec\x80\x02\x9bP\xf5\xc7\xe9\x8e\x9e\x94\x96\xc8\xcdu\xa1\xc1.\xa7 \xb5I\x0b\x9d\xef\xd0\x8ff\x91+\xc2\xe0\xeb/\xbe\x05\x87\xac\xd8\xb8vA\xe8?V\xa3\xfdJ\xc1\x9f\xe8\xc4\x91=\xc4\x16H\xbdP\x1fv5x9\x02\'N]Zh\xed\xc9\xc3\xb5\xae:\x04\xc8\x04e1:t2:#K1:y1:re' 2019-06-04 16:04:22.345648 ('67.215.246.10', 6881) b'd2:ip6:Z\x97\'X0:1:rd2:id20:2\xf5NisQ\xffJ\xec)\xcd\xba\xab\xf2\xfb\xe3F|\xc2g5:nodes416:+S\xdc\x8c\xc8%~ \x12\xd3\xd9@\xa9X4\x9at\xcc\x8a\xf9z\x08\x1d\x16h/\xf2}\xb7I\xd9\x8fP\x81(\x9d\xed\xae\xa5\xe5\xe4S1,\xf0-\xaeavL\xc4\x91~\xd5\x01`o\xa8\xc4\xe0\xfa \xa5\xf0\xf1~`\x0c\x19[+\x85\xbb\xd0\x0bp\xf3\x8c\xe98S\xcd`=n|\xa8\x8c\xa4~\xfc\xedg\xce\xff\x8f\x13}g\xfc\xc9)\xa8\x89L&]\\\xb3M\xc6NUE\x7f\xb8CQ\x82\xe1{C\xba\xaf\x884g\x9a\xf3\x8c\x1a\xe0\xbb\x1a\x12\xafCQ\x1e\x18\x91;\x80P\xee\xf0\xdc\t\xc1m.\xe4\x04\xda1\xff\x93?\xa0r\xc5\x1d\x9c\x1f\xc7\xf2\x0e[\xc9\tV4\x94\x02w\xc2\\b\x03+\x1a\xe1\xc4\x80#z0\x14\x9d}Kj\xbe\xf2>\xa5\xf8k\x12\x9a|u\xb0:\xc1,U\r\xc7kE\xa1UY\x1e~:r\x14\xb6p&\xd7\xdf\xaf>\x9b\xa5b\xb5\xcd\x1f\xc4\x91Z\xdf\x1a\x1f\xdb\x9a\x84\tu\xff\xda(\xddqy}nT\xaa\x8f%\x06.\xc9\xda\xe4\xc0\x9a\x03\x9c\x12?\xf1s[\xb1\xd7;\xe3)\xb9[o\r\xb6=\xb57\x98&\xc4\x91.\xd1\x87)5\xf5s\xb8\xc9z\xc4\x9d\x063Kw\xaf\xcc\x046\xdbN\xcf,\xf3\x8c\xaa\x85\xee\xd0e\xfa\xca\xd2\x93\x82\xe2\x98\xeaA\xdc\xbd\xaf\x97F\xe9r\x19\xb4i\xde~>\x82\xfb\xe9y#vJ\xe4\x8e\x0e\xd1\xee]\xe0qk(\xb2\x92\x95\xff\x02\n\x98\x9c"\xcaY\x8d\xb6\x81a\xa1\xf9\xc1\nX\xb4\x9e\xcfo\xbf\xa3j\x8fH1\'7\xc4\x91v\xd1_\xec\xe4\xe1\x1f\xcb\xd5\xbd\xf43\x0c\'"\x04\xa5\xa2\x0f\xd0\x05>+\xb1 Xe1:t2:#K1:y1:re'
aiounfurl
[![Build Status](https://travis-ci.org/TigorC/aiounfurl.svg?branch=master)](https://travis-ci.org/TigorC/aiounfurl)[![Coverage Status](https://coveralls.io/repos/github/TigorC/aiounfurl/badge.svg?branch=master)](https://coveralls.io/github/TigorC/aiounfurl?branch=master)## aiounfurlUsing this library you can extract meta information from web pages and create site preview.The library uses four sources of information:1. [oEmbed](http://oembed.com)2. [Open Graph](http://ogp.me)3. [Twitter Cards](https://dev.twitter.com/cards/overview)4. HTML meta tags## Requirements* python 3.5* aiohttp* beautifulsoup4* html5lib## Installation```bashpip install aiounfurl```## Example of usingTo extract all site data:```pythonimport asyncioimport aiohttpfrom pprint import pprintfrom aiounfurl.views import get_preview_data, fetch_allasync def get_links_data(links, loop):results = []async with aiohttp.ClientSession() as session:tasks = [fetch_all(session, l, loop) for l in links]results = await asyncio.gather(*tasks, loop=loop, return_exceptions=True)return [{'link':l, 'data': d} for l, d in zip(links, results)]links = ['https://habrahabr.ru/post/314606/','https://www.youtube.com/watch?v=9EftQMnuhvU','https://medium.freecodecamp.com/million-requests-per-second-with-python-95c137af319']loop = asyncio.get_event_loop()result = loop.run_until_complete(get_links_data(links, loop))loop.close()pprint(result)```## Server example.Full example you can find [here](https://github.com/TigorC/aiounfurl/blob/master/example/srv.py).Install required packages for running example:```bashpip install -r example/requirements.txt```Run `python srv.py runserver`, then open http://127.0.0.1:8080/## Running the example in DockerI added a docker image with the example in http://hub.docker.com/ to run the sample as a separate independent service.Running in the background:```bashdocker run --name aiounfurl -p 8080:8080 -d tigorc/aiounfurl```then you can open our example [http://127.0.0.1:8080/](http://127.0.0.1:8080/).Using the list of oEmbed providers (a json file with a list of providers /path_to_file/providers.json has to be preliminarily created):```bashdocker run --name aiounfurl -p 8080:8080 -e "OEMBED_PROVIDERS_FILE=/srv/app/providers.json" -v /path_to_file/providers.json:/srv/app/providers.json -d tigorc/aiounfurl```## TestsInstall the `tox` package and run command:```bashtox```
aiounifi
aiounifiAsynchronous library to communicate with Unifi ControllerAcknowledgementsPaulus Schoutsen (balloob) creator of aiohue which most of this code repository is modeled after.
aiounifiedagent
This is a security placeholder package. If you want to claim this name for legitimate purposes, please contact us [email protected]@yandex-team.ru
aiounittest
aiounittestInfoTheaiounittestis a helper library to ease of your pain (and boilerplate), when writing a test of the asynchronous code (asyncio). You can test:synchronous code (same as theunittest.TestCase)asynchronous code, it supports syntax withasync/await(Python 3.5+) andasyncio.coroutine/yield from(Python 3.4)In the Python 3.8 (release note) and newer consider to use theunittest.IsolatedAsyncioTestCase. Builtinunittestmodule is now asyncio-featured.InstallationUse pip:pip install aiounittestUsageIt’s as simple as use ofunittest.TestCase. Full docs athttp://aiounittest.readthedocs.io.importasyncioimportaiounittestasyncdefadd(x,y):awaitasyncio.sleep(0.1)returnx+yclassMyTest(aiounittest.AsyncTestCase):asyncdeftest_async_add(self):ret=awaitadd(5,6)self.assertEqual(ret,11)# or 3.4 [email protected]_sleep(self):ret=yield fromadd(5,6)self.assertEqual(ret,11)# some regular test codedeftest_something(self):self.assertTrue(True)Library provides some additional tooling:async_test,AsyncMockIteratormocking forasync for,futurizedmock for coroutines.LicenseMIT
aiounittest-tornado
No description available on PyPI.
aiounu
aiounuAn asyncio module forunuin Python3 using aiohttp. Forked fromvcinex/unu.InstallpipinstallaiounuUseimportaiounuasunutest_url="https://example.com/?test=52e838e8-0943-4ccb-bfd8-ae6bb3173bd2"unu_resp=awaitunu.shorten(url=test_url,output_format="dot",keyword="")print(unu_resp.shorturl)Example ResultIfoutput_formatis set todot(The default), the resulting JSON object properties will be accessible (Thanks tomo-dots) by both dot.notation and dict['notation'].{"url":{"keyword":"kfuns","url":"https://example.com/?test=52e838e8-0943-4ccb-bfd8-ae6bb3173bd2","title":"Example Domain","date":"2020-12-22 08:44:33","ip":"22.42.219.59"},"status":"error","message":"https://example.com/?test=52e838e8-0943-4ccb-bfd8-ae6bb[...] added to database<br/>(Could not check Google Safe Browsing: Bad Request)","title":"Example Domain","shorturl":"https://u.nu/kfuns","statusCode":200}Only theurlvariable is necessary. For a runnable example, seetests/test_shorten.pyor clone the repo and runpytest.MIT License
aioupbit
No description available on PyPI.
aioupnp
[UPnP for asyncioaioupnpis a python 3.6-8 library and command line tool to interact with UPnP gateways using asyncio.aioupnprequires thenetifacesanddefusedxmlmodules.Supported devicesInstallationVerify python is version 3.6-8python --versionInstallation for normal usagepip install aioupnpInstallation for developmentgit clone https://github.com/lbryio/aioupnp.git cd aioupnp pip install -e .Usageaioupnp [-h] [--debug_logging] [--interface=<interface>] [--gateway_address=<gateway_address>] [--lan_address=<lan_address>] [--timeout=<timeout>] [(--<case sensitive m-search header>=<value>)...] command [--<arg name>=<arg>]...Commandshelpget_external_ipm_searchadd_port_mappingget_port_mapping_by_indexget_redirectsget_specific_port_mappingdelete_port_mappingget_next_mappinggather_debug_infoTo get the documentation for a commandaioupnp help get_external_ipTo get the external ip addressaioupnp get_external_ipTo list the active port mappings on the gatewayaioupnp get_redirectsTo set up a TCP port mappingaioupnp add_port_mapping --external_port=1234 --internal_port=1234 --lan_address=<lan_addr> --description=test --protocol=TCPTo delete a TCP port mappingaioupnp delete_port_mapping --external_port=1234 --protocol=TCPM-Search headersUPnP uses a multicast protocol (SSDP) to locate the gateway. Gateway discovery is automatic by default, but you may provide specific headers for the search to use to override automatic discovery.If m-search headers are provided as keyword arguments then all of the headers to be used must be provided, in the order they are to be used. For example:aioupnp --HOST=239.255.255.250:1900 --MAN=\"ssdp:discover\" --MX=1 --ST=upnp:rootdevice m_searchUsing non-default network interfacesBy default, the network device will be automatically discovered. The interface may instead be specified with the--interface, provided before the command to be run. The gateway used on the interface network may be specified with the--gateway_addressargument.aioupnp --interface=wlp4s0 --gateway_address=192.168.1.6 m_searchExample usage from pythonfrom aioupnp.upnp import UPnP async def main(): upnp = await UPnP.discover() print(await upnp.get_external_ip()) print(await upnp.get_redirects()) print("adding a port mapping") await upnp.add_port_mapping(1234, 'TCP', 1234, upnp.lan_address, 'test mapping') print(await upnp.get_redirects()) print("deleting the port mapping") await upnp.delete_port_mapping(1234, 'TCP') print(await upnp.get_redirects()) asyncio.run(main())TroubleshootingIfaioupnpis failing with m-search timeouts this means the UPnP gateway (the router) isn't being found at all. To see if this error is expected try running m_search with debug logging, which will print out the packets sent and received:aioupnp --debug_logging m_searchIf you only see packets being sent or the replies are only from devices that aren't your router (smart devices, speakers, etc), then there are three options:your router does not support UPnP (this is unlikely)UPnP is turned off in the web gui for your router (more likely)aioupnphas a bug (very likely if you don't see your router manufacturer doing well in the supported devices table)If you see replies from the router but it still fails, then it's likely a bug in aioupnp.If there are no replies and UPnP is certainly turned on, then a local firewall is the likely culprit.Sending a bug reportIf it still doesn't work, you can send a bug report using an included script. This script will try finding the UPnP gateway usingaioupnpas well asminiupnpcand then try add and remove a port mapping using each library. The script does this while capturing the packets sent/received, which makes figuring out what went wrong possible. The script will create a file with this packet capture (aioupnp-bug-report.json) and automatically send it.Note: the bug report script currently does not work on MacOSgit clone https://github.com/lbryio/aioupnp.git cd aioupnp python3 -m pip install -e . python3 -m pip install --user certifi aiohttp miniupnpc sudo -E python3 generate_bug_report.pyLicenseThis project is MIT licensed. For the full license, seeLICENSE.ContactThe primary contact for this project is@jackrobison
aiouring
aiouringAn io_uring adapter for asyncio, depends on liburing.so
aiourllib
UNKNOWN
aiourlshortener
# aiourlshorteneraiourlshortener is a [asyncio](https://pypi.python.org/pypi/asyncio) python3 compatible library for URL shorting using [Googl](https://goo.gl/), [Bitly](https://bitly.com/) API# Installing```pip3 install aiourlshortener```# Requirements* [asyncio](https://pypi.python.org/pypi/asyncio) or Python 3.4+* [aiohttp](https://pypi.python.org/pypi/aiohttp)# UsageCreate a Shortener instance passing the engine as an argument.## Goo.gl Shortener`api_key` required```pythonimport asynciofrom asyncio import coroutinefrom aiourlshortener import Shortener@coroutinedef main():shortener = Shortener('Google', api_key='API_KEY')url = 'https://github.com/blikenoother/aiourlshortener'# shortshort_url = yield from shortener.short(url)print('short url: {}'.format(short_url))# expandlong_url = yield from shortener.expand(short_url)print('long url: {}'.format(long_url))if __name__ == '__main__':loop = asyncio.get_event_loop()loop.run_until_complete(main())```## Bit.ly Shortener`access_token` required```pythonimport asynciofrom asyncio import coroutinefrom aiourlshortener import Shortener@coroutinedef main():shortener = Shortener('Bitly', access_token='ACCESS_TOKEN')url = 'https://github.com/blikenoother/aiourlshortener'# shortshort_url = yield from shortener.short(url)print('short url: {}'.format(short_url))# expandlong_url = yield from shortener.expand(short_url)print('long url: {}'.format(long_url))if __name__ == '__main__':loop = asyncio.get_event_loop()loop.run_until_complete(main())```
aio-usb-hotplug
aio-usb-hotplugaio-usb-hotplugis a Python library that provides asynchronous generators yielding detected hotplug events on the USB buses.Requires Python >= 3.8.Works withasyncioandtrio.InstallationUse the package managerpipto installaio-usb-hotplug.pipinstallaio-usb-hotplugaio-usb-hotplugdepends onPyUSB, which in turn requireslibusboropenusb. An easy way to satisfy this requirement is to installlibusb-package, which supplies pre-compiled binaries for most platforms:pipinstalllibusb-packageaio-usb-hotplugwill make use oflibusb-packageif it is installed in the current Python environment.UsageDump all hotplug events related to a specific USB devicefromaio_usb_hotplugimportHotplugDetectorfromtrioimportrun# ...or asyncioasyncdefdump_events():detector=HotplugDetector.for_device(vid="1050",pid="0407")asyncforeventindetector.events():print(repr(event))trio.run(dump_events)Run an async task for each USB device matching a VID/PID pairfromaio_usb_hotplugimportHotplugDetectorfromtrioimportsleep_foreverasyncdefhandle_device(device):print("Handling device:",repr(device))try:# Do something meaningful with the device. The task gets cancelled# when the device is unplugged.awaitsleep_forever()finally:# Device unplugged or an exception happenedprint("Stopped handling device:",repr(device))asyncdefhandle_detected_devices():detector=HotplugDetector.for_device(vid="1050",pid="0407")awaitdetector.run_for_each_device(handle_device)trio.run(handle_detected_devices)ContributingPull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.Please make sure to update tests as appropriate.LicenseMIT
aiousps
This is a simple async Python wrapper for the USPS API. It was forked from theusps-apiproject to make an async version. Instead of having to deal with XML, use this library and receive well formatted dictionaries back for tracking shipments, creating shipments, and validating addresses.InstallationNOTE:aiouspsis not yet published on pypi, so you’ll have to install from source.To install usps-api, use pip:pip install aiouspsOr to install from source:python setup.py installConfigurationNote: In order to use any of these APIs, you need to register with USPS and get aUSERID. For the create_shipment endpoint, you will also need to request further permissions by [email protected] Label API access.The USPS developer guide is available athttps://www.usps.com/business/web-tools-apis/general-api-developer-guide.htmUsageTrack ShipmentsfromuspsimportUSPSApiusps=USPSApi('XXXXXXXXXXXX')track=usps.track('00000000000000000000')print(track.result)Create ShipmentThecreate_shipmentfunction needs a to and from address, weight (in ounces), service type and label type. Service types and lable types can be found inusps/constants.py. Defaults areSERVICE_PRIORITYandLABEL_ZPL.fromuspsimportUSPSApi,AddressfromuspsimportSERVICE_PRIORITY,LABEL_ZPLto_address=Address(name='Tobin Brown',address_1='1234 Test Ave.',city='Test',state='NE',zipcode='55555')from_address=Address(name='Tobin Brown',address_1='1234 Test Ave.',city='Test',state='NE',zipcode='55555')weight=12# weight in ouncesusps=USPSApi('XXXXXXXXXXXX',test=True)label=usps.create_label(to_address,from_address,weight,SERVICE_PRIORITY,LABEL_ZPL)print(label.result)Validate AddressfromuspsimportUSPSApi,Addressaddress=Address(name='Tobin Brown',address_1='1234 Test Ave.',city='Test',state='NE',zipcode='55555')usps=USPSApi('XXXXXXXXXXXX',test=True)validation=usps.validate_address(address)print(validation.result)LicenseMIT. SeeLICENSEfor more details.
aioutilities
aioutilitiesasyncio-powered coroutine worker pool. No more juggling bounded semaphores and annoying timeouts, and allows you to run through millions of pieces of data efficiently.Installationpython-mpipinstall-UaioutilitiesCreditsThis is refactored and built on top ofhttps://github.com/CaliDog/asyncpoolExample UsagefromasyncioimportQueue,ensure_future,run,sleepfromaioutilities.poolimportAioPoolasyncdefexample_coro(initial_number:int,result_queue:Queue[int])->None:result=initial_number*2print(f"Processing Value! ->{initial_number}* 2 ={result}")awaitsleep(1)awaitresult_queue.put(initial_number*2)asyncdefresult_reader(queue:Queue[int|None])->None:whileTrue:value=awaitqueue.get()ifvalueisNone:breakprint(f"Got value! ->{value}")asyncdefexample()->None:result_queue=Queue[int|None]()reader_future=ensure_future(result_reader(result_queue))# Start a worker pool with 10 coroutines, invokes `example_coro` and waits for# it to complete or 5 minutes to pass.pool=AioPool[int](name="ExamplePool",task=example_coro,worker_qty=10,timeout=300,)asyncwithpool.spawn()asworkers:foriinrange(50):awaitworkers.push(i,result_queue)awaitresult_queue.put(None)awaitreader_futuredefrun_example()->None:run(example())
aioutils
## History### 2015.03.120.3.10 releasedo not raise asyncio.InvalidStateError### 2015.03.110.3.9 releasefix a bug will cause yielder stuck### 2015.03.050.3.8 releasewhen GeneratorExit cancel all pending tasksyielder related status cleanups### 2015.03.020.3.4-0.3.7 releasecreate new event loop if using in a threadfix semaphore order so that loop must existadd test to test this behaviourcleanup _safe_yield_from that are not needed anymoreuse is_running (how can I not using that!!)### 2015.02.280.3.3 releasefixed Pool’s potential thread unsafe problemfixed Yielder hangs when no items to yieldadd pool size argument to yielder family### 2015.02.270.3.2 releasetypo fix0.3.1 releaseadd put method for manually yield items0.3.0 releaseadd Yielder and OrderedYielder to replace Bag and OrderedBagfix thread safe problem #2 in Yielder and Group mixed usage### 2015.02.260.2.1 releasefix thread unsafe problem### 2015.02.260.2.0 releaseadd Bag and OrderedBagrename to “aioutils”### 2015.02.250.1.2 releasefix some release problems0.1.1 releasebasic group and pool implemenation### 2015.02.23ideas, prototypes
aiouv
No description available on PyPI.
aiovalidator
Exampleimport asyncio from aiohttp import web from aiovalidator import ( validator_factory, middleware_exception, IntegerField ) async def foo_validator(value): await asyncio.sleep(1) return value def foo_default(value): async def default(): return value return default class Hello(web.View): class Field: field1 = IntegerField() field2 = IntegerField(required=False, methods={'GET'}, verbose_name='Field method get') field3 = IntegerField(validator=foo_validator, ) field4 = IntegerField(default=foo_default) @asyncio.coroutine def get(self): fields = self.request['fields'] print(fields) return web.json_response() app = web.Application(middlewares=[validator_factory(), middleware_exception]) app.router.add_get('/{user_id}/', Hello) web.run_app(app, port=8000)My fields exampleimport phonenumbers from aiovalidator import StrField, abort class PhoneField(StrField): def get_value(self, value): value = super().get_value(value) try: value = phonenumbers.parse(value, 'RU') region = phonenumbers.region_code_for_number(value) regions = phonenumbers.COUNTRY_CODE_TO_REGION_CODE[7] if not phonenumbers.is_valid_number(value): abort(status=400, text='Field {} not format phone'.format(self.name)) if region not in regions: abort(status=400, text='Field {} not format phone'.format(self.name)) value = phonenumbers.format_number( value, phonenumbers.PhoneNumberFormat.E164 )[1:] return value except phonenumbers.NumberParseException: abort(status=400, text='Field {} not valid'.format(self.name))
aiovalorant
No description available on PyPI.
aiovantage
aiovantageaiovantage is a Python library for interacting with and controlling Vantage InFusion home automation controllers.Uses acontrollerpattern inspired heavily by theaiohuelibrary.This open-source, non-commercial library is not affiliated, associated, authorized, endorsed by, or in any way officially connected with Vantage, and is provided for interoperability purposes only.Table of contentsExampleFeaturesSupported objects typesInstallationUsageExamplefromaiovantageimportVantageasyncwithVantage("192.168.1.2","username","password")asvantage:asyncforloadinvantage.loads:print(f"{load.name}is at{load.level}%")See theexamplesfolder for more examples.FeaturesUses Python asyncio for non-blocking I/O.Exposes "controllers" to make fetching and controlling various objects easy.Uses SSL connections by default, with automatic reconnection.Fetch objects lazily (withasync for obj in controller).Alternatively, eager-fetch objects withcontroller.initialize.Supported objects typesThe following interfaces/controllers are currently supported.TypeDescriptionControllerExamplesAnemoSensorWind speed sensorsvantage.anemo_sensorsExamplesAreaRooms, etcvantage.areasExamplesBlindShades, blindsvantage.blindsExamplesBlindGroupsGroups of blindsvantage.blind_groupsExamplesButtonsKeypad buttonsvantage.buttonsExamplesDryContactsMotion sensors, etcvantage.dry_contactsExamplesGMemVantage variablesvantage.gmemExamplesLightSensorLight sensorsvantage.light_sensorsExamplesLoadLights, relays, etcvantage.loadsExamplesLoadGroupGroups of loadsvantage.load_groupsExamplesMasterVantage controllersvantage.mastersExamplesModuleDimmer modulesvantage.modulesOmniSensorPower, current, etcvantage.omni_sensorsExamplesPowerProfileLoad power profilesvantage.power_profilesExamplesRGBLoadRGB lightsvantage.rgb_loadsExamplesStationsKeypads, etcvantage.stationsExamplesTasksVantage tasksvantage.tasksExamplesTemperatureTemperature sensorsvantage.temperature_sensorsExamplesThermostatThermostatsvantage.thermostatsExamplesIf you have an object that you expect to show up in one of these controllers but is missing, pleasecreate an issueorsubmit a pull request.InstallationAddaiovantageas a dependency to your project, or install it directly:pipinstallaiovantageUsageCreating a clientBegin by importing theVantageclass:fromaiovantageimportVantageThe most convenient way to create a client is by using the async context manager:asyncwithVantage("hostname","username","password")asvantage:# ...use the vantage clientAlternatively, you can manage the lifecycle of the client yourself:fromaiovantageimportVantagevantage=Vantage("hostname","username","password")# ...use the vantage clientvantage.close()Querying objectsTheVantageclass exposes a number ofcontrollers, which can be used to query objects. Controllers can either be populated lazily (by usingasync for), or eagerly (by usingcontroller.initialize()).For example, to get a list of all loads:asyncwithVantage("hostname","username","password")asvantage:asyncforloadinvantage.loads:print(f"{load.name}is at{load.level}%")Alternatively, you can usecontroller.initialize()to eagerly fetch all objects:asyncwithVantage("hostname","username","password")asvantage:awaitvantage.loads.initialize()forloadinvantage.loads:print(f"{load.name}is at{load.level}%")If you aren't interested in the state of the objects, you can callcontroller.initialize(fetch_state=False)to slightly speed up the initialization:asyncwithVantage("hostname","username","password")asvantage:awaitvantage.loads.initialize(fetch_state=False)forloadinvantage.loads:print(f"{load.name}")All controllers implement a django-like query interface, which can be used to filter objects. You can either query by matching attributes:asyncwithVantage("hostname","username","password")asvantage:asyncforloadinvantage.loads.filter(name="Kitchen"):print(f"{load.name}is at{load.level}%")Or by using a filter predicate:asyncwithVantage("hostname","username","password")asvantage:asyncforloadinvantage.loads.filter(lambdaload:load.level>50):print(f"{load.name}is at{load.level}%")Fetching a single objectYou can fetch a single object by id, by callingcontroller.aget()orcontroller.get():asyncwithVantage("hostname","username","password")asvantage:load=awaitvantage.loads.aget(118)print(f"{load.name}is at{load.level}%")These functions also implement the same query interface ascontroller.filter()for querying by attributes or filter predicate:asyncwithVantage("hostname","username","password")asvantage:load=awaitvantage.loads.aget(name="Kitchen")print(f"{load.name}is at{load.level}%")Controlling objectsMost controllers expose a various methods for controlling the state of objects. The first parameter to these methods is always the vantage id of the object to control.For example, to turn on a load:asyncwithVantage("hostname","username","password")asvantage:awaitvantage.loads.turn_on(118)Subscribing to state changesYou can subscribe to state changes by using thecontroller.subscribe()method:defon_load_state_change(event,load,data):print(f"{load.name}is at{load.level}%")asyncwithVantage("hostname","username","password")asvantage:vantage.loads.subscribe(on_load_state_change)awaitvantage.loads.initialize()Note that a subscription will only receive state changes for objects that have populated into the controller.
aiovast
VastA utility to easily scale functionalityTable of ContentsRequirementsInstallationInformationVastVast Event LoopVastSessionVast Bulk RequestsVast Bulk GetVast Bulk PostVast Bulk PutVast Bulk DeleteVast Bulk HeadExamplesRequirementsPython3.6+InstallationCreate a new virtual environment with python 3.6+Install the aiovast library$gitclonehttps://www.github.com/tannerburns/aiovast $cdaiovast $pip3install.InformationDetails about the aiovast utilityVastMain variablesloop: asyncio.new_event_loopmax_async_pool: int, default=32max_futures_pool: int, default=10000Vast Event LoopMain methodrun_in_eventlooparg1: functionObject, Callablethe function to run in the event looparg2: listOfArgs, listthe list of arguments to be mapped to the function in the event loopkwarg: report, default= Falsereturns results and statistics about the event loop runtimekwarg: disable_progress_bar, default= Falsedisables the progress bar from printing while the event loop runskwarg: progress_bar_color, default= greenprovide another color for the progress bar templateVastSessionVariablesloop: asyncio.new_event_loopmax_async_pool: int, default=32max_futures_pool: int, default=10000self.session: requests.sessionVast Bulk RequestsA function that can handle any method requests will acceptbulk_requestsarg1: listOfCalls, listformat: [ [[method: string, url: string], options: dictionary], [[method: string, url: string], options: dictionary], .. ]Function calls for single method typesVast Bulk Getbulk_get_requestsarg1: listOfCalls, listformat: [ [[url: string], options: dictionary], [[url: string], options: dictionary], .. ]Vast Bulk Postbulk_post_requestsarg1: listOfCalls, listformat: [ [[url: string], options: dictionary], [[url: string], options: dictionary], .. ]Vast Bulk Putbulk_put_requestsarg1: listOfCalls, listformat: [ [[url: string], options: dictionary], [[url: string], options: dictionary], .. ]Vast Bulk Deletebulk_delete_requestsarg1: listOfCalls, listformat: [ [[url: string], options: dictionary], [[url: string], options: dictionary], .. ]Vast Bulk Headbulk_head_requestsarg1: listOfCalls, listformat: [ [[url: string], options: dictionary], [[url: string], options: dictionary], .. ]Examples#Basic add exampledefadd(x,y):returnx+yif__name__=='__main__':rets=[add(x,y)forxinrange(0,5)foryinrange(5,10)]#Example bulk add using aiovast classfromaiovastimportVastdefadd(x,y):returnx+yif__name__=='__main__':aiovast=Vast()args=[[[x,y]]forxinrange(0,5)foryinrange(5,10)]rets=aiovast.run_in_eventloop(add,args)#Example using Vast context managerfromaiovastimportVastdefadd(x,y):returnx+yif__name__=='__main__':args=[[[x,y]]forxinrange(0,5)foryinrange(5,10)]withVast()asaiovast:rets=aiovast.run_in_eventloop(add,args)#Example bulk add using decoratorfromaiovast.decoratorsimportvast_loop@aiovast_loop(max_async_pool=16)defadd_in_bulk(x,y):returnx+yif__name__=='__main__':args=[[[x,y]]forxinrange(0,5)foryinrange(5,10)]rets=add_in_bulk(args)#Vast session for sending bulk requestsfromaiovast.requestsimportVastSessionsession=VastSession(max_async_pool=4)calls=[(['get','https://www.google.com'],{'headers':{'User-Agent':'custom'}}),(['post','https://www.github.com'],)]responses=session.bulk_requests(calls)
aiovault
aiovault 1.1.1 releaseMinor bugfixesaiovault 1.0.0 releaseFirst major release. Should be pretty stable… all the tests pass so cant be too bad.This library is mainly just a glorified wrapper around aiohttp calling the many Vault URLs. Eventually I want to add some helper methods to make using vault with microservices easier, like having a coroutine which will just sit there renewing tokens/secrets etc…ExampleSimple example of authenticating with vault and then writing then reading a secretimportaiovaultwithaiovault.VaultClient(token='6c84fb90-12c4-11e1-840d-7b25c5ee775a')asclient:is_authed=awaitclient.is_authenticated()print(is_authed)# Trueawaitclient.secrets.generic.create('some_secret',key1='value1',key2='value2')secret=awaitclient.secrets.generic.read('some_secret')print(secret['key1'])# value1print(secret['key2'])# value2Documentationhttps://pyaiovault.readthedocs.io/en/latest/FeaturesToken, GitHub, AppRole, LDAP, RADIUS and User/Password Authentication backendsGeneric Secret, Consul, TOTP and Transit backendsFile and Syslog Audit backendsPolicy managementBackend renamingInitialization, seal and health managementTODO (Near future)Improve code coverageSecret backends: Databases, RabbitMQ, CubbyholeAuth backends: Okta, AWS (hopefully)TODO (Long term)More docs, more examplesPossibly utility functions like a coroutine to keep renewing a token/secretPolicy validation with hcl library?Socket audit backendTLS auth supportPKI, SSH secret supportTestingAs many of the unit tests that can, interact directly with Vault/Consul/LDAP/RADIUS without mocking. Currently my reasoning is that this way, if we change the variable that determins the vault version and incompatabilites in the REST interface were introduced they would appear immediatly in the masses of failing unit tests.CreditsI used the _Cookiecutter package to setup the initial project. Was pretty good.And most of the credit goes to the wonderful _aiohttp library which this library is pretty much a wrapper around.LicenseFree software: GNU General Public License v3Documentation:https://aiovault.readthedocs.io.History1.1.1 (2017-11-16)Updated readme1.1.0 (2017-11-16)Fixed verify=False bug1.0.0 (2017-07-29)First stable release0.2.0 (2017-07-20)Switched to use the dev version of Python 2.6Fixed link target in READMEFixed typo in README code exampleAdded AppRole authentication backendAdded Transit secret backendCreated test harness for running Vault in non dev modeAdded Seal/Unseal, initialization and health methods0.1.3 (2017-07-17)Fixed rendering of README on PyPI0.1.2 (2017-07-17)Mostly repository maintenance.Updated requirements_dev.txt and setup.pyFixed issue where tox was not passing environment variablesLimited coverage scope to the library not test suite0.1.1 (2017-07-17)First release on PyPI.
aiovcf
AsyncIO enabled Variant Call Format parser.todoQuick StartExplain Asynchronous GeneratorsExplain Antlr4 Grammar
aiovemmio
No description available on PyPI.
aiovertica
aioverticaSmall asynchronous driver for Vertica based onvertica_python.WARNINGThis project was written "in haste" literally overnight, so it may not be stable. Of course, most of the mechanisms are identical to the "project", but in any case, tests have not yet been written to be sure of this at least to some extent.At the moment, the project has rewritten the mechanisms responsible for working with the network from a synchronous model to an asynchronous one, as well as in theConnectionandCursormodules, the synchronous methods have been replaced by asynchronous ones (where necessary), the code formatting has been slightly improved and type annotations have been added (but not always correct).ForewordI would really like to see a ready-made library, ideally the same asasyncpg, but unfortunately it is not there. I would like to express my deep gratitude to the team that worked on thevertica_pythonfor writing at least a synchronous driver - this greatly simplified the work. I have tried to keep all the licenses and the list of authors from the original project.I would also be glad if the guys fromvertica_pythonadded something similar to the official driver and we would have a simple opportunity to work with the driver in asynchronous mode as well.Perhaps in the future I will create a PR in the official driver (I have several proposals for the architecture), but at the moment it would take too long to implement the "correct" embedding into the existing implementation - the code was needed "yesterday".I will be glad for any help in the development of the project. TheIssuesandPRssections are looking forward to seeing you :).InstallationTo install vertica-python with pip:# Latest release versionpipinstallaiovertica# Latest commit on master branchpipinstallgit+https://github.com/i8enn/aiovertica.git@masterTo install vertica-python from source, run the following command from the root directory:python setup.py installSource code for vertica-python can be found at:https://github.com/i8enn/aioverticaUsing Kerberos authenticationWARNING:Kerberosnot supported in currently versionvertica-python has optional Kerberos authentication support for Unix-like systems, which requires you to install thekerberospackage:pip install kerberosNote thatkerberosis a python extension module, which means you need to installpython-dev. The command depends on the package manager and will look likesudo [yum|apt-get|etc] install python-devUsageCreate connectionimportaioverticaconn_info={'host':'127.0.0.1','port':5433,'user':'some_user','password':'some_password','database':'a_database',# autogenerated session label by default,'session_label':'some_label',# default throw error on invalid UTF-8 results'unicode_error':'strict',# SSL is disabled by default'ssl':False,# autocommit is off by default'autocommit':True,# using server-side prepared statements is disabled by default'use_prepared_statements':False,# connection timeout is not enabled by default# 5 seconds timeout for a socket operation (Establishing a TCP connection or read/write operation)'connection_timeout':5}# simple connection, with manual closetry:connection=awaitaiovertica.connect(**conn_info)# do thingsfinally:awaitconnection.close()# using with for auto connection closing after usageasyncwithvertica_python.connect(**conn_info)asconnection:# do thingsYou can pass anssl.SSLContexttosslto customize the SSL connection options. For example,importaioverticaimportsslssl_context=ssl.SSLContext(ssl.PROTOCOL_SSLv23)ssl_context.verify_mode=ssl.CERT_REQUIREDssl_context.check_hostname=Truessl_context.load_verify_locations(cafile='/path/to/ca_file.pem')conn_info={'host':'127.0.0.1','port':5433,'user':'some_user','password':'some_password','database':'a_database','ssl':ssl_context}connection=awaitaiovertica.connect(**conn_info)See more on SSL optionshere.WARNING:Kerberosnot supported in currently versionIn order to use Kerberos authentication, installdependenciesfirst, and it is the user's responsibility to ensure that an Ticket-Granting Ticket (TGT) is available and valid. Whether a TGT is available can be easily determined by running theklistcommand. If no TGT is available, then it first must be obtained by running thekinitcommand or by logging in. You can pass in optional arguments to customize the authentication. The arguments arekerberos_service_name, which defaults to "vertica", andkerberos_host_name, which defaults to the value of argumenthost. For example,importaioverticaconn_info={'host':'127.0.0.1','port':5433,'user':'some_user','password':'some_password','database':'a_database',# The service name portion of the Vertica Kerberos principal'kerberos_service_name':'vertica_krb',# The instance or host name portion of the Vertica Kerberos principal'kerberos_host_name':'vcluster.example.com'}asyncwithaiovertica.connect(**conn_info)asconn:# do thingsLogging is disabled by default if you do not pass values to bothlog_levelandlog_path. The default value oflog_levelis logging.WARNING. You can find all levelshere. The default value oflog_pathis 'vertica_python.log', the log file will be in the current execution directory. Iflog_pathis set to''(empty string) orNone, no file handler is set, logs will be processed by root handlers. For example,importaioverticaimportlogging## Example 1: write DEBUG level logs to './vertica_python.log'conn_info={'host':'127.0.0.1','port':5433,'user':'some_user','password':'some_password','database':'a_database','log_level':logging.DEBUG}asyncwithaiovertica.connect(**conn_info)asconnection:# do things## Example 2: write WARNING level logs to './path/to/logs/client.log'conn_info={'host':'127.0.0.1','port':5433,'user':'some_user','password':'some_password','database':'a_database','log_path':'path/to/logs/client.log'}asyncwithaiovertica.connect(**conn_info)asconnection:# do things## Example 3: write INFO level logs to '/home/admin/logs/vClient.log'conn_info={'host':'127.0.0.1','port':5433,'user':'some_user','password':'some_password','database':'a_database','log_level':logging.INFO,'log_path':'/home/admin/logs/vClient.log'}asyncwithaiovertica.connect(**conn_info)asconnection:# do things## Example 4: use root handlers to process logs by setting 'log_path' to '' (empty string)conn_info={'host':'127.0.0.1','port':5433,'user':'some_user','password':'some_password','database':'a_database','log_level':logging.DEBUG,'log_path':''}asyncwithaiovertica.connect(**conn_info)asconnection:# do thingsConnection Failover: Supply a list of backup hosts tobackup_server_nodefor the client to try if the primary host you specify in the connection parameters (host,port) is unreachable. Each item in the list should be either a host string (using default port 5433) or a (host, port) tuple. A host can be a host name or an IP address.importaioverticaconn_info={'host':'unreachable.server.com','port':888,'user':'some_user','password':'some_password','database':'a_database','backup_server_node':['123.456.789.123','invalid.com',('10.20.82.77',6000)]}connection=awaitaiovertica.connect(**conn_info)Connection Load Balancing helps automatically spread the overhead caused by client connections across the cluster by having hosts redirect client connections to other hosts. Both the server and the client need to enable load balancing for it to function. If the server disables connection load balancing, the load balancing request from client will be ignored.importaioverticaconn_info={'host':'127.0.0.1','port':5433,'user':'some_user','password':'some_password','database':'vdb','connection_load_balance':True}# Server enables load balancingasyncwithaiovertica.connect(**conn_info)asconn:cur=conn.cursor()awaitcur.execute("SELECT NODE_NAME FROM V_MONITOR.CURRENT_SESSION")result=awaitcur.fetchone()print("Client connects to primary node:",result[0])awaitcur.execute("SELECT SET_LOAD_BALANCE_POLICY('ROUNDROBIN')")asyncwithaiovertica.connect(**conn_info)asconn:cur=conn.cursor()awaitcur.execute("SELECT NODE_NAME FROM V_MONITOR.CURRENT_SESSION")result=awaitcur.fetchone()print("Client redirects to node:",result[0])## Output# Client connects to primary node: v_vdb_node0003# Client redirects to node: v_vdb_node0005Another way to set connection properties is passing a connection string to the keyword parameterdsnofvertica_python.connect(dsn='...', **kwargs). The connection string is of the form:vertica://(user):(password)@(host):(port)/(database)?(arg1=val1&arg2=val2&...)The connection string would be parsed byvertica_python.parse_dsn(connection_str), and the parsing result (a dictionary of keywords and values) would be merged withkwargs. If the same keyword is specified in both the sources, thekwargsvalue overrides the parseddsnvalue. The(arg1=val1&arg2=val2&...)section can handle string/numeric/boolean values, blank and invalid value would be ignored.importaioverticaconnection_str=('vertica://admin@localhost:5433/db1?connection_load_balance=True&connection_timeout=1.5&session_label=vpclient+123%7E456')print(aiovertica.parse_dsn(connection_str))# {'user': 'admin', 'host': 'localhost', 'port': 5433, 'database': 'db1',# 'connection_load_balance': True, 'connection_timeout': 1.5, 'session_label': 'vpclient 123~456'}additional_info={'password':'some_password','backup_server_node':['10.6.7.123',('10.20.82.77',6000)]# invalid value to be set in a connection string}asyncwithaiovertica.connect(dsn=connection_str,**additional_info)asconn:# do thingsStream query results:cur=connection.cursor()awaitcur.execute("SELECT * FROM a_table LIMIT 2")asyncforrowincur.iterate():print(row)# [ 1, 'some text', datetime.datetime(2014, 5, 18, 6, 47, 1, 928014) ]# [ 2, 'something else', None ]Streaming is recommended if you want to further process each row, save the results in a non-list/dict format (e.g. Pandas DataFrame), or save the results in a file.In-memory results as list:cur=connection.cursor()awaitcur.execute("SELECT * FROM a_table LIMIT 2")awaitcur.fetchall()# [ [1, 'something'], [2, 'something_else'] ]In-memory results as dictionary:cur=connection.cursor('dict')awaitcur.execute("SELECT * FROM a_table LIMIT 2")awaitcur.fetchall()# [ {'id': 1, 'value': 'something'}, {'id': 2, 'value': 'something_else'} ]awaitconnection.close()Query using named parameters or format parameters:vertica-python can automatically convert Python objects to SQL literals: using this feature your code will be more robust and reliable to prevent SQL injection attacks.Prerequisites: Only SQL literals (i.e. query values) should be bound via these methods: they shouldn’t be used to merge table or field names to the query (vertica-pythonwill try quoting the table name as a string value, generating invalid SQL as it is actually a SQL Identifier). If you need to generate dynamically SQL queries (for instance choosing dynamically a table name) you have to construct the full query yourself.Variables can be specified with named (:name) placeholders.cur=connection.cursor()data={'propA':1,'propB':'stringValue'}awaitcur.execute("SELECT * FROM a_table WHERE a = :propA AND b = :propB",data)# converted into a SQL command similar to: "SELECT * FROM a_table WHERE a = 1 AND b = 'stringValue'"awaitcur.fetchall()# [ [1, 'stringValue'] ]Variables can also be specified with positional format (%s) placeholders. The placeholdermust always be a %s, even if a different placeholder (such as a %d for integers or %f for floats) may look more appropriate.Neveruse Python string concatenation (+) or string parameters interpolation (%) to pass variables to a SQL query string.cur=connection.cursor()data=(1,"O'Reilly")awaitcur.execute("SELECT * FROM a_table WHERE a =%sAND b =%s"%data)# WRONG: % operatorawaitcur.execute("SELECT * FROM a_table WHERE a =%dAND b =%s",data)# WRONG: %d placeholderawaitcur.execute("SELECT * FROM a_table WHERE a =%sAND b =%s",data)# correct# converted into a SQL command similar to: "SELECT * FROM a_table WHERE a = 1 AND b = 'O''Reilly'"awaitcur.fetchall()# [ [1, "O'Reilly"] ]The placeholder must not be quoted.vertica-pythonwill add quotes where needed.cur=connection.cursor()awaitcur.execute("INSERT INTO table VALUES (':propA')",{'propA':"someString"})# WRONGawaitcur.execute("INSERT INTO table VALUES (:propA)",{'propA':"someString"})# correctawaitcur.execute("INSERT INTO table VALUES ('%s')",("someString",))# WRONGawaitcur.execute("INSERT INTO table VALUES (%s)",("someString",))# correctvertica-pythonsupports default mapping for many standard Python types. It is possible to adapt new Python types to SQL literals viaCursor.register_sql_literal_adapter(py_class_or_type, adapter_function)function. Example:classPoint(object):def__init__(self,x,y):self.x=xself.y=y# Adapter should return a string valuedefadapt_point(point):return"STV_GeometryPoint({},{})".format(point.x,point.y)cur=conn.cursor()cur.register_sql_literal_adapter(Point,adapt_point)awaitcur.execute("INSERT INTO geom_data (geom) VALUES (%s)",[Point(1.23,4.56)])awaitcur.execute("select ST_asText(geom) from geom_data")awaitcur.fetchall()# [['POINT (1.23 4.56)']]To help you debug the binding process during Cursor.execute*(),Cursor.object_to_sql_literal(py_object)function can be used to inspect the SQL literal string converted from a Python object.cur=conn.cursorcur.object_to_sql_literal("O'Reilly")# "'O''Reilly'"cur.object_to_sql_literal(None)# "NULL"cur.object_to_sql_literal(True)# "True"cur.object_to_sql_literal(Decimal("10.00000"))# "10.00000"cur.object_to_sql_literal(datetime.date(2018,9,7))# "'2018-09-07'"cur.object_to_sql_literal(Point(-71.13,42.36))# "STV_GeometryPoint(-71.13,42.36)" if you registered in previous stepQuery using server-side prepared statements:Vertica server-side prepared statements let you define a statement once and then run it many times with different parameters. Placeholders in the statement are represented by question marks (?). Server-side prepared statements are useful for preventing SQL injection attacks.importaiovertica# Enable using server-side prepared statements at connection levelconn_info={'host':'127.0.0.1','user':'some_user','password':'some_password','database':'a_database','use_prepared_statements':True,}asyncwithaiovertica.connect(**conn_info)asconnection:cur=connection.cursor()awaitcur.execute("CREATE TABLE tbl (a INT, b VARCHAR)")awaitcur.execute("INSERT INTO tbl VALUES (?, ?)",[1,'aa'])awaitcur.execute("INSERT INTO tbl VALUES (?, ?)",[2,'bb'])awaitcur.executemany("INSERT INTO tbl VALUES (?, ?)",[(3,'foo'),(4,'xx'),(5,'bar')])awaitcur.execute("COMMIT")awaitcur.execute("SELECT * FROM tbl WHERE a>=? AND a<=? ORDER BY a",(2,4))awaitcur.fetchall()# [[2, 'bb'], [3, 'foo'], [4, 'xx']]Vertica does not support executing a command string containing multiple statements using server-side prepared statements. You can setuse_prepared_statementsoption incursor.execute*()functions to override the connection level setting.importaiovertica# Enable using server-side prepared statements at connection levelconn_info={'host':'127.0.0.1','user':'some_user','password':'some_password','database':'a_database','use_prepared_statements':True,}asyncwithaiovertica.connect(**conn_info)asconnection:cur=connection.cursor()awaitcur.execute("CREATE TABLE tbl (a INT, b VARCHAR)")# Executing compound statementsawaitcur.execute("INSERT INTO tbl VALUES (?, ?); COMMIT",[1,'aa'])# Error message: Cannot insert multiple commands into a prepared statement# Disable prepared statements but forget to change placeholders (?)awaitcur.execute("INSERT INTO tbl VALUES (?, ?); COMMIT;",[1,'aa'],use_prepared_statements=False)# TypeError: not all arguments converted during string formattingawaitcur.execute("INSERT INTO tbl VALUES (%s,%s); COMMIT;",[1,'aa'],use_prepared_statements=False)awaitcur.execute("INSERT INTO tbl VALUES (:a, :b); COMMIT;",{'a':2,'b':'bb'},use_prepared_statements=False)# Disable using server-side prepared statements at connection levelconn_info['use_prepared_statements']=Falseasyncwithaiovertica.connect(**conn_info)asconnection:cur=connection.cursor()# Try using prepared statementsawaitcur.execute("INSERT INTO tbl VALUES (?, ?)",[3,'foo'])# TypeError: not all arguments converted during string formattingawaitcur.execute("INSERT INTO tbl VALUES (?, ?)",[3,'foo'],use_prepared_statements=True)# Query using named parametersawaitcur.execute("SELECT * FROM tbl WHERE a>=:n1 AND a<=:n2 ORDER BY a",{'n1':2,'n2':4})awaitcur.fetchall()# [[2, 'bb'], [3, 'foo']]Note: In other drivers, the batch insert is converted into a COPY statement by using prepared statements. vertica-python currently does not support that.Insert and commits:cur=connection.cursor()# inline commit (when 'use_prepared_statements' is False)awaitcur.execute("INSERT INTO a_table (a, b) VALUES (1, 'aa'); commit;")# commit in executionawaitcur.execute("INSERT INTO a_table (a, b) VALUES (1, 'aa')")awaitcur.execute("INSERT INTO a_table (a, b) VALUES (2, 'bb')")awaitcur.execute("commit;")# connection.commit()awaitcur.execute("INSERT INTO a_table (a, b) VALUES (1, 'aa')")awaitconnection.commit()# connection.rollback()awaitcur.execute("INSERT INTO a_table (a, b) VALUES (0, 'bad')")awaitconnection.rollback()Autocommit:Session parameter AUTOCOMMIT can be configured by the connection option and theConnection.autocommitread/write attribute:importaiovertica# Enable autocommit at startupconn_info={'host':'127.0.0.1','user':'some_user','password':'some_password','database':'a_database',# autocommit is off by default'autocommit':True,}asyncwithaiovertica.connect(**conn_info)asconnection:# Check current session autocommit settingprint(connection.autocommit)# should be True# If autocommit is True, statements automatically commit their transactions when they complete.# Set autocommit setting with attributeconnection.autocommit=Falseprint(connection.autocommit)# should be False# If autocommit is False, the methods commit() or rollback() must be manually invoked to terminate the transaction.WARNING: set attrautocommitwith instance may not work correctly in the current versionTo set AUTOCOMMIT to a new value, vertica-python usesCursor.execute()to execute a command internally, and that would clear your previous query results, so be sure to callCursor.fetch*()to save your results before you set autocommit.Copy:There are 2 methods to do copy:Method 1: "COPY FROM STDIN" sql with Cursor.copy()cur=connection.cursor()awaitcur.copy("COPY test_copy (id, name) from stdin DELIMITER ',' ",csv)Wherecsvis either a string or a file-like object (specifically, any object with aread()method). If using a file, the data is streamed (in chunks ofbuffer_sizebytes, which defaults to 128 * 2 ** 10).withopen("/tmp/binary_file.csv","rb")asfs:awaitcursor.copy("COPY table(field1, field2) FROM STDIN DELIMITER ',' ENCLOSED BY '\"'",fs,buffer_size=65536)Method 2: "COPY FROM LOCAL" sql with Cursor.execute()importsysimportaioverticaconn_info={'host':'127.0.0.1','user':'some_user','password':'some_password','database':'a_database',# False by default#'disable_copy_local': True,# Don't support executing COPY LOCAL operations with prepared statements'use_prepared_statements':False}asyncwithaiovertica.connect(**conn_info)asconnection:cur=connection.cursor()# Copy from local fileawaitcur.execute("COPY table(field1, field2) FROM LOCAL"" 'data_Jan_*.csv','data_Feb_01.csv' DELIMITER ','"" REJECTED DATA 'path/to/write/rejects.txt'"" EXCEPTIONS 'path/to/write/exceptions.txt'",buffer_size=65536)result=awaitcur.fetchall()print("Rows loaded:",result)# Copy from local stdinawaitcur.execute("COPY table(field1, field2) FROM LOCAL STDIN DELIMITER ','",copy_stdin=sys.stdin)result=awaitcur.fetchall()print("Rows loaded:",result)# Copy from local stdin (compound statements)withopen('f1.csv','r')asfs1,open('f2.csv','r')asfs2:awaitcur.execute("COPY tlb1(field1, field2) FROM LOCAL STDIN DELIMITER ',';""COPY tlb2(field1, field2) FROM LOCAL STDIN DELIMITER ',';",copy_stdin=[fs1,fs2],buffer_size=65536)result=awaitcur.fetchall()print("Rows loaded 1:",result)awaitcur.nextset()result=awaitcur.fetchall()print("Rows loaded 2:",result)When connection optiondisable_copy_localset to True, disables COPY LOCAL operations, including copying data from local files/stdin and using local files to store data and exceptions. You can use this property to prevent users from writing to and copying from files on a Vertica host, including an MC host. Note that this property doesn't apply toCursor.copy().The data for copying from/writing to local files is streamed in chunks ofbuffer_sizebytes, which defaults to 128 * 2 ** 10.When executing "COPY FROM LOCAL STDIN",copy_stdinshould be a file-like object or a list of file-like objects (specifically, any object with aread()method).Cancel the current database operation:Connection.cancel()interrupts the processing of the current operation. Interrupting query execution will cause the cancelled method to raise avertica_python.errors.QueryCanceled. If no query is being executed, it does nothing. You can call this function from a different thread/process than the one currently executing a database operation.frommultiprocessingimportProcessimportasyncioimportaioverticaasyncdefcancel_query(connection,timeout=5):awaitasyncio.sleep(timeout)awaitconnection.cancel()# Example 1: Cancel the query before Cursor.execute() return.# The query stops executing in a shorter time after the cancel message is sent.asyncwithaiovertica.connect(**conn_info)asconn:cur=conn.cursor()# Call cancel() from a different processp1=Process(target=cancel_query,args=(conn,))p1.start()try:cur.execute("<Long running query>")exceptaiovertica.errors.QueryCanceledase:passp1.join()# Example 2: Cancel the query after Cursor.execute() return.# Less number of rows read after the cancel message is sent.withaiovertica.connect(**conn_info)asconn:cur=conn.cursor()awaitcur.execute("SELECT id, time FROM large_table")nCount=0try:result=awaitcur.fetchone()whileresult:nCount+=1ifnCount==100:conn.cancel()result=awaitcur.fetchone()exceptaiovertica.errors.QueryCanceledase:pass# nCount is less than the number of rows in large_tableRowcount odditiesvertica_python behaves a bit differently than dbapi when returning rowcounts.After a select execution, the rowcount will be -1, indicating that the row count is unknown. The rowcount value will be updated as data is streamed.awaitcur.execute('SELECT 10 things')cur.rowcount==-1# indicates unknown rowcountawaitcur.fetchone()cur.rowcount==1awaitcur.fetchone()cur.rowcount==2awaitcur.fetchall()cur.rowcount==10After an insert/update/delete, the rowcount will be returned as a single element row:awaitcur.execute("DELETE 3 things")cur.rowcount==-1# indicates unknown rowcountresult=awaitcur.fetchone()result[0]==3NextsetIf you execute multiple statements in a single call to execute(), you can use cursor.nextset() to retrieve all of the data.awaitcur.execute('SELECT 1; SELECT 2;')awaitcur.fetchone()# [1]awaitcur.fetchone()# Noneawaitcur.nextset()# Trueawaitcur.fetchone()# [2]awaitcur.fetchone()# Noneawaitcur.nextset()# NoneUTF-8 encoding issuesWhile Vertica expects varchars stored to be UTF-8 encoded, sometimes invalid strings get into the database. You can specify how to handle reading these characters using the unicode_error connection option. This uses the same values as the unicode type (https://docs.python.org/2/library/functions.html#unicode)importaioverticaconn=awaitaiovertica.connect({...,'unicode_error':'strict'})cur=conn.cursor()awaitcur.execute(r"SELECT E'\xC2'")awaitcur.fetchone()# caught 'utf8' codec can't decode byte 0xc2 in position 0: unexpected end of dataconn=awaitaiovertica.connect({...,'unicode_error':'strict'})cur=conn.cursor()awaitcur.execute(r"SELECT E'\xC2'")awaitcur.fetchone()# �conn=awaitaiovertica.connect({...,'unicode_error':'strict'})cur=conn.cursor()awaitcur.execute(r"SELECT E'\xC2'")awaitcur.fetchone()#LicenseApache 2.0 License, please seeLICENSEfor details.Contributing guidelinesHave a bug or an idea? Please seeCONTRIBUTING.mdfor details.AcknowledgementsI would like to express my deep gratitude to the team that worked on thevertica_pythonfor writing at least a synchronous driver - this greatly simplified the work. I have tried to keep all the licenses and the list of authors from the original project.
aioviber
No description available on PyPI.
aioviberbot
Viber Python Bot Async APIThis is async version ofviberbotpackage. Fully compatible with sync package version. Use this library to develop a bot for Viber platform.The library is available onGitHubas well as a package onPyPI.This package can be imported using pip by adding the following to yourrequirements.txt:aioviberbot==0.5.0LicenseThis library is released under the terms of the Apache 2.0 license. SeeLicensefor more information.Library Prerequisitespython >= 3.7.0An Active Viber account on a platform which supports Public Accounts/ bots (iOS/Android). This account will automatically be set as the account administrator during the account creation process.Active Public Account/bot - Create an accounthere.Account authentication token - unique account identifier used to validate your account in all API requests. Once your account is created your authentication token will appear in the account’s “edit info” screen (for admins only). Each request posted to Viber by the account will need to contain the token.Webhook - Please use a server endpoint URL that supports HTTPS. If you deploy on your own custom server, you'll need a trusted (ca.pem) certificate, not self-signed. Read ourblog poston how to test your bot locally.ContributingIf you think that there's a bug or there's anything else needed to be changed and you want to change it yourself, you can always create a new Pull request.Please make sure that your change doesn't break anything and all the unit tests passes.Also, please make sure that the current tests cover your change, if not please add tests.We are using pytest, so if you want to run the tests from the commandline just follow the relevant steps after cloning the repo and creating your branch:# installing the dependencies: python setup.py develop # run the unit tests pytest tests/Let's get started!InstallingCreating a basic Viber bot is simple:Install the library with pippip install aioviberbotImportaioviberbot.apilibrary to your projectCreate a Public Account or bot and use the API key fromhttps://developers.viber.comConfigure your bot as described in the documentation belowStart your web serverCallset_webhook(url)with your web server urlA simple Echo BotFirstly, let's import and configure our botfromaioviberbotimportApifromaioviberbot.api.bot_configurationimportBotConfigurationbot_configuration=BotConfiguration(name='PythonSampleBot',avatar='http://viber.com/avatar.jpg',auth_token='YOUR_AUTH_TOKEN_HERE',)viber=Api(bot_configuration)Create an HTTPS serverNext thing you should do is starting a https server. and yes, as we said in the prerequisites it has to be https server. Create a server however you like, for example withaiohttp:fromaiohttpimportwebasyncdefwebhook(request:web.Request)->web.Response:request_data=awaitrequest.read()logger.debug('Received request. Post data:%s',request_data)# handle the request herereturnweb.json_response({'ok':True})if__name__=='__main__':app=web.Application()app.router.add_route('POST','/webhook',webhook),web.run_app(app)Setting a webhookAfter the server is up and running you can set a webhook. Viber will push messages sent to this URL. web server should be internet-facing.awaitviber.set_webhook('https://mybotwebserver.com:443/')LoggingThis library uses the standard python logger. If you want to see its logs you can configure the logger:logger=logging.getLogger('aioviberbot')logger.setLevel(logging.DEBUG)handler=logging.StreamHandler()formatter=logging.Formatter('%(asctime)s-%(name)s-%(levelname)s-%(message)s')handler.setFormatter(formatter)logger.addHandler(handler)Do you supply a basic types of messages?Well, funny you ask. Yes we do. All the Message types are located inaioviberbot.api.messagespackage. Here's some examples:fromaioviberbot.api.messagesimport(TextMessage,ContactMessage,PictureMessage,VideoMessage,)fromaioviberbot.api.messages.data_types.contactimportContact# creation of text messagetext_message=TextMessage(text='sample text message!')# creation of contact messagecontact=Contact(name='Viber user',phone_number='0123456789')contact_message=ContactMessage(contact=contact)# creation of picture messagepicture_message=PictureMessage(text='Check this',media='http://site.com/img.jpg')# creation of video messagevideo_message=VideoMessage(media='http://mediaserver.com/video.mp4',size=4324)Have you noticed how we created theTextMessage? There's all bunch of message types you should get familiar with.Text MessageUrl MessageContact MessagePicture MessageVideo MessageLocation MessageSticker MessageRich Media MessageKeyboard MessageCreating them is easy! Every message object has it's own unique constructor corresponding to it's API implementation, click on them to see it! Check out the full API documentation for more advanced uses.Let's add it all up and reply with a message!fromaiohttpimportwebfromaioviberbotimportApifromaioviberbot.api.bot_configurationimportBotConfigurationfromaioviberbot.api.messages.text_messageimportTextMessagefromaioviberbot.api.viber_requestsimportViberConversationStartedRequestfromaioviberbot.api.viber_requestsimportViberMessageRequestfromaioviberbot.api.viber_requestsimportViberSubscribedRequestviber=Api(BotConfiguration(name='PythonSampleBot',avatar='http://viber.com/avatar.jpg',auth_token='YOUR_AUTH_TOKEN_HERE'))asyncdefwebhook(request:web.Request)->web.Response:request_data=awaitrequest.read()signature=request.headers.get('X-Viber-Content-Signature')ifnotviber.verify_signature(request_data,signature):raiseweb.HTTPForbiddenviber_request=viber.parse_request(request_data)ifisinstance(viber_request,ViberMessageRequest):# echo messageawaitviber.send_messages(viber_request.sender.id,[viber_request.message],)elifisinstance(viber_request,ViberSubscribedRequest):awaitviber.send_messages(viber_request.user.id,[TextMessage(text='Thanks for subscribing!')],)elifisinstance(viber_request,ViberConversationStartedRequest):awaitviber.send_messages(viber_request.user.id,[TextMessage(text='Thanks for starting conversation!')],)returnweb.json_response({'ok':True})asyncdefset_webhook_signal(app:web.Application):awaitviber.set_webhook('https://mybotwebserver.com/webhhok')if__name__=='__main__':app=web.Application()app.on_startup.append(set_webhook_signal)app.router.add_route('POST','/webhook',webhook),web.run_app(app)As you can see there's a bunch ofRequesttypes here's a list of them.Viber APIApi classfrom aioviberbot import ApiApiinit(bot_configuration, client_session).set_webhook(url, webhook_events)⇒List of registered event_types.unset_webhook()⇒None.get_account_info()⇒object.verify_signature(request_data, signature)⇒boolean.parse_request(request_data)⇒ViberRequest.send_messages(to, messages)⇒list of message tokens sent.broadcast_messages(broadcast_list, messages)⇒list of message tokens sent.get_online(viber_user_ids)⇒dictionary of users status.get_user_details(viber_user_id)⇒dictionary of user's data.post_messages_to_public_account(to, messages)⇒list of message tokens sentNew Api()ParamTypeDescriptionbot_configurationobjectBotConfigurationclient_sessionobjectOptionalaiohttp.ClientSession, pass if you want to use your own session for api requestsApi.set_webhook(url)ParamTypeDescriptionurlstringYour web server urlwebhook_eventslistoptional list of subscribed eventsReturnsList of registered event_types.event_types=awaitviber.set_webhook('https://example.com/webhook')Api.unset_webhook()ReturnsNone.awaitviber.unset_webhook()Api.get_account_info()Returns anobjectwith the following JSON.account_info=awaitviber.get_account_info()Api.verify_signature(request_data, signature)ParamTypeDescriptionrequest_datastringthe post data from requestsignaturestringsent as headerX-Viber-Content-SignatureReturns abooleansuggesting if the signature is valid.ifnotviber.verify_signature(awaitrequest.read(),request.headers.get('X-Viber-Content-Signature')):raiseweb.HTTPForbiddenApi.parse_request(request_data)ParamTypeDescriptionrequest_datastringthe post data from requestReturns aViberRequestobject.There's a list ofViberRequest objectsviber_request=viber.parse_request(awaitrequest.read())Api.send_messages(to, messages)ParamTypeDescriptiontostringViber user idmessageslistlist ofMessageobjectsReturnslistof message tokens of the messages sent.tokens=awaitviber.send_messages(to=viber_request.sender.id,messages=[TextMessage(text='sample message')],)Api.broadcast_messages(broadcast_list, messages)ParamTypeDescriptionbroadcast_listlistlist of Viber user idsmessageslistlist ofMessageobjectsReturnslistof message tokens of the messages sent.tokens=awaitviber.broadcast_messages(broadcast_list=["ABB102akPCRKFaqxWnafEIA==","ABB102akPCRKFaqxWna111==","ABB102akPCRKFaqxWnaf222==",],messages=[TextMessage(text='sample message')],)Api.post_messages_to_public_account(to, messages)ParamTypeDescriptionsenderstringViber user idmessageslistlist ofMessageobjectsReturnslistof message tokens of the messages sent.tokens=awaitviber.post_messages_to_public_account(sender=viber_request.sender.id,messages=[TextMessage(text='sample message')],)Api.get_online(viber_user_ids)ParamTypeDescriptionviber_user_idsarray of stringsArray of Viber user idsReturns adictionary of users.users=awaitviber.get_online(['user1id','user2id'])Api.get_user_details(viber_user_id)ParamTypeDescriptionviber_user_idsstringViber user idTheget_user_detailsfunction will fetch the details of a specific Viber user based on his unique user ID. The user ID can be obtained from the callbacks sent to the account regarding user's actions. This request can be sent twice during a 12 hours period for each user ID.user_data=awaitviber.get_user_details('userId')Request objectParamTypeNotesevent_typestringaccording toEventTypesenumtimestamplongEpoch of request timeViberRequest.event_type ⇒string.timestamp ⇒longViberConversationStartedRequest objectInherits fromViberRequestConversation started event fires when a user opens a conversation with the Public Account/ bot using the “message” button (found on the account’s info screen) or using adeep link.This event isnotconsidered a subscribe event and doesn't allow the account to send messages to the user; however, it will allow sending one "welcome message" to the user. Seesending a welcome messagebelow for more information.ParamTypeNotesevent_typestringalways equals to the value ofEventType.CONVERSATION_STARTEDmessage_tokenstringUnique ID of the messagetypestringThe specific type ofconversation_startedevent.contextstringAny additional parameters added to the deep link used to access the conversation passed as a stringuserUserProfilethe user started the conversationUserProfilesubscribedbooleanIndicates whether a user is already subscribedViberConversationStartedRequestmessage_token ⇒stringtype ⇒stringcontext ⇒stringuser ⇒UserProfileViberDeliveredRequest objectInherits fromViberRequestParamTypeNotesevent_typestringalways equals to the value ofEventType.DELIVEREDmessage_tokenstringUnique ID of the messageuser_idstringUnique Viber user idViberDeliveredRequestmessage_token ⇒stringuser_id ⇒stringViberFailedRequest objectInherits fromViberRequestParamTypeNotesevent_typestringalways equals to the value ofEventType.FAILEDmessage_tokenstringUnique ID of the messageuser_idstringUnique Viber user iddescstringFailure descriptionViberFailedRequestmessage_token ⇒stringuser_id ⇒stringdesc ⇒stringViberMessageRequest objectInherits fromViberRequestParamTypeNotesevent_typestringalways equals to the value ofEventType.MESSAGEmessage_tokenstringUnique ID of the messagemessageMessageMessageobjectsenderUserProfilethe user started the conversationUserProfileViberMessageRequestmessage_token ⇒stringmessage ⇒Messagesender ⇒UserProfileViberSeenRequest objectInherits fromViberRequestParamTypeNotesevent_typestringalways equals to the value ofEventType.SEENmessage_tokenstringUnique ID of the messageuser_idstringUnique Viber user idViberSeenRequestmessage_token ⇒stringuser_id ⇒stringViberSubscribedRequest objectInherits fromViberRequestParamTypeNotesevent_typestringalways equals to the value ofEventType.SUBSCRIBEDuserUserProfilethe user started the conversationUserProfileViberSubscribedRequestuser ⇒UserProfileViberUnsubscribedRequest objectInherits fromViberRequestParamTypeNotesevent_typestringalways equals to the value ofEventType.UNSUBSCRIBEDuser_idstringUnique Viber user idViberUnsubscribedRequestget_user_id() ⇒stringUserProfile objectParamTypeNotesidstring---namestring---avatarstringAvatar URLcountrystringcurrently set inCONVERSATION_STARTEDevent onlylanguagestringcurrently set inCONVERSATION_STARTEDevent onlyMessage ObjectCommon Members forMessageinterface:ParamTypeDescriptiontimestamplongEpoch timekeyboardJSONkeyboard JSONtrackingDataJSONJSON Tracking Data from Viber ClientCommon Constructor ArgumentsMessageinterface:ParamTypeDescriptionoptionalKeyboardJSONWriting Custom KeyboardsoptionalTrackingDataJSONData to be saved on Viber Client device, and sent back each time message is receivedTextMessage objectMemberTypetextstringmessage=TextMessage(text='my text message')URLMessage objectMemberTypeDescriptionmediastringURL stringmessage=URLMessage(media='http://my.siteurl.com')ContactMessage objectMemberTypecontactContactfromaioviberbot.api.messages.data_types.contactimportContactcontact=Contact(name='Viber user',phone_number='+0015648979',avatar='http://link.to.avatar')contact_message=ContactMessage(contact=contact)PictureMessage objectMemberTypeDescriptionmediastringurl of the message (jpeg only)textstringthumbnailstringmessage=PictureMessage(media='http://www.thehindubusinessline.com/multimedia/dynamic/01458/viber_logo_JPG_1458024f.jpg',text='Viber logo')VideoMessage objectMemberTypeDescriptionmediastringurl of the videosizeintthumbnailstringdurationintmessage=VideoMessage(media='http://site.com/video.mp4',size=21499)LocationMessage objectMemberTypelocationLocationfromaioviberbot.api.messages.data_types.locationimportLocationlocation=Location(lat=0.0,lon=0.0)location_message=LocationMessage(location=location)StickerMessage objectMemberTypesticker_idintmessage=StickerMessage(sticker_id=40100)FileMessage objectMemberTypemediastringsizelongfile_namestringmessage=FileMessage(media=url,size=size_in_bytes,file_name=file_name)RichMediaMessage objectMemberTyperich_mediastring(JSON)SAMPLE_RICH_MEDIA="""{"BgColor": "#69C48A","Buttons": [{"Columns": 6,"Rows": 1,"BgColor": "#454545","BgMediaType": "gif","BgMedia": "http://www.url.by/test.gif","BgLoop": true,"ActionType": "open-url","Silent": true,"ActionBody": "www.tut.by","Image": "www.tut.by/img.jpg","TextVAlign": "middle","TextHAlign": "left","Text": "<b>example</b> button","TextOpacity": 10,"TextSize": "regular"}]}"""SAMPLE_ALT_TEXT='upgrade now!'message=RichMediaMessage(rich_media=SAMPLE_RICH_MEDIA,alt_text=SAMPLE_ALT_TEXT)KeyboardMessage objectMemberTypekeyboardJSONtracking_dataJSONmessage=KeyboardMessage(tracking_data=tracking_data,keyboard=keyboard)Sending a welcome messageThe Viber API allows sending messages to users only after they subscribe to the account. However, Viber will allow the account to send one “welcome message” to a user as the user opens the conversation, before the user subscribes.The welcome message will be sent as a response to aconversation_startedcallback, which will be received from Viber once the user opens the conversation with the account. To learn more about this event and when is it triggered seeConversation startedin the callbacks section.Welcome message flowSending a welcome message will be done according to the following flow:User opens 1-on-1 conversation with account.Viber server sendconversation_startedeven to PA’s webhook.The account receives theconversation_startedand responds with an HTTP response which includes the welcome message as the response body.The welcome message will be a JSON constructed according to the send_message requests structure, but without thereceiverparameter. An example welcome message would look like this:asyncdefwebhook(request:web.Request)->web.Response:request_data=awaitrequest.read()viber_request=viber.parse_request(request_data)ifisinstance(viber_request,ViberConversationStartedRequest):awaitviber.send_messages(viber_request.user.id,[TextMessage(text='Welcome!')],)returnweb.json_response({'ok':True})CommunityJoin the conversation onGitter.
aiovideo
Salom! ushbu kutubxona yordamida siz Youtube platformasidan videolarni MP3 va video ko’rinishida yuklab olishingiz mumkin!
aio-videoindexer
aio-videoindexerOverviewAn async video indexer package for queryingMicrosoft Media Services Video Indexerin Python.aio-videoindexer is available under theMIT Licence.InstallationThe package can be found onPyPyand can be installed using pip.$pipinstallaio-videoindexerDocumentationFor more information including usage examples, seehttps://aio-videoindexer.readthedocs.io/en/latest/.ContactFeel free to contact meon Twitter. For bugs, pleaseraise an issue on GitHub.BackgroundThis library is forked from aTeams Vidproject, designed to use video to connect people during the pandemic.ContributingContributions are more than welcome.Create a fork.Create a feature branchgit checkout -b feature/featurenamein theGitflow style.Commit your changesgit commit -am 'Bug: Fixed a bug'usingsemantic commits.Push to the branchgit push.Create a newpull requestfor review when ready, relating tothe issue.
aiovk
vk.com API python wrapper for asynciofor old version of python you can usehttps://github.com/dimka665/vkFeaturesasynchronoussupport python 3.5+ versionshave only one dependency -aiohttp 3+support two-factor authenticationsupport socks proxy withaiohttp-sockssupport rate limit of requestssupport Long Poll connectionTODOneed refactoring tests forAsyncVkExecuteRequestPoolInstallpipinstallaiovkExamplesAnnotationIn all the examples below, I will give only the{code}asyncdeffunc():{code}loop=asyncio.get_event_loop()loop.run_until_complete(func())AuthorizationTokenSession- if you already have token or you use requests which don’t require tokensession=TokenSession()session=TokenSession(access_token='asdf123..')ImplicitSession- client authorization in js apps and standalone (desktop and mobile) apps>>>session=ImplicitSession(USER_LOGIN,USER_PASSWORD,APP_ID)>>>awaitsession.authorize()>>>session.access_tokenasdfa2321afsdf12eadasf123...With scopes:ImplicitSession(USER_LOGIN,USER_PASSWORD,APP_ID,'notify')ImplicitSession(USER_LOGIN,USER_PASSWORD,APP_ID,'notify,friends')ImplicitSession(USER_LOGIN,USER_PASSWORD,APP_ID,['notify','friends'])ImplicitSession(USER_LOGIN,USER_PASSWORD,APP_ID,3)# notify and friendsAlso you can useSimpleImplicitSessionMixinfor entering confirmation code or captcha keyAuthorizationCodeSession- authorization for server apps or Open APISeehttps://vk.com/dev/authcode_flow_userfor getting the CODE>>>session=AuthorizationCodeSession(APP_ID,APP_SECRET,REDIRECT_URI,CODE)>>>awaitsession.authorize()>>>session.access_tokenasdfa2321afsdf12eadasf123...Or:>>>session=AuthorizationCodeSession(APP_ID,APP_SECRET,REDIRECT_URI)>>>awaitsession.authorize(CODE)>>>session.access_tokenasdfa2321afsdf12eadasf123...Authorization using context manager- you won’t need to use session.close() after workasyncwithaiovk.TokenSession(access_token=YOUR_VK_TOKEN)asses:api=API(ses)...And your session will be closed after all done or code fail(similar to simple “with” usage) Works with all types of authorizationDriversHttpDriver- default driver for usingaiohttp>>>driver=HttpDriver()>>>driver=HttpDriver(timeout=10)# default timeout for all requests>>>driver=ProxyDriver(PROXY_ADDRESS,PORT)# 1234 is port>>>driver=ProxyDriver(PROXY_ADDRESS,PORT,timeout=10)>>>driver=ProxyDriver(PROXY_ADDRESS,PORT,PROXY_LOGIN,PROXY_PASSWORD,timeout=10)How to use custom driver with session:>>>session=TokenSession(...,driver=HttpDriver())How to use driver with own loop:>>>loop=asyncio.get_event_loop()>>>asyncio.set_event_loop(None)>>>session=TokenSession(driver=HttpDriver(loop=loop))# or ProxyDriverHow to use driver with custom http session object:Solve next problem:https://stackoverflow.com/questions/29827642/asynchronous-aiohttp-requests-fails-but-synchronous-requests-succeed>>>connector=aiohttp.TCPConnector(verify_ssl=False)>>>session=aiohttp.ClientSession(connector=connector)>>>driver=HttpDriver(loop=loop,session=session)LimitRateDriverMixin- mixin class what allow you create new drivers with speed rate limits>>>classExampleDriver(LimitRateDriverMixin,HttpDriver):...requests_per_period=3...period=1#secondsVK APIFirst variant:>>>session=TokenSession()>>>api=API(session)>>>awaitapi.users.get(user_ids=1)[{'first_name':'Pavel','last_name':'Durov','id':1}]Second variant:>>>session=TokenSession()>>>api=API(session)>>>awaitapi('users.get',user_ids=1)[{'first_name':'Pavel','last_name':'Durov','id':1}]Also you can addtimeoutargument for each request or define it in the sessionSeehttps://vk.com/dev/methodsfor detailed API guide.Lazy VK APIIt is useful when a bot has a large message flow>>>session=TokenSession()>>>api=LazyAPI(session)>>>message=api.users.get(user_ids=1)>>>awaitmessage()[{'first_name':'Pavel','last_name':'Durov','id':1}]Supports both variants like API objectUser Long PollFor documentation, see:https://vk.com/dev/using_longpollUse exist API object>>>api=API(session)>>>lp=UserLongPoll(api,mode=2)# default wait=25>>>awaitlp.wait(){"ts":1820350345,"updates":[...]}>>>awaitlp.wait(){"ts":1820351011,"updates":[...]}Use Session object>>>lp=UserLongPoll(session,mode=2)# default wait=25>>>awaitlp.wait(){"ts":1820350345,"updates":[...]}>>>awaitlp.get_pts()# return pts191231223>>>awaitlp.get_pts(need_ts=True)# return pts, ts191231223,1820350345You can iterate over events>>>asyncforeventinlp.iter():...print(event){"type":...,"object":{...}}Notice thatwaitvalue only for long pool connection.Real pause could be morewaittime because of need time for authorization (if needed), reconnect and etc.Bots Long PollFor documentation, see:https://vk.com/dev/bots_longpollUse exist API object>>>api=API(session)>>>lp=BotsLongPoll(api,group_id=1)# default wait=25>>>awaitlp.wait(){"ts":345,"updates":[...]}>>>awaitlp.wait(){"ts":346,"updates":[...]}Use Session object>>>lp=BotsLongPoll(session,group_id=1)# default wait=25>>>awaitlp.wait(){"ts":78455,"updates":[...]}>>>awaitlp.get_pts()# return pts191231223>>>awaitlp.get_pts(need_ts=True)# return pts, ts191231223,1820350345BotsLongPoll supports iterating too>>>asyncforeventinlp.iter():...print(event){"type":...,"object":{...}}Notice thatwaitvalue only for long pool connection.Real pause could be morewaittime because of need time for authorization (if needed), reconnect and etc.Async execute request poolFor documentation, see:https://vk.com/dev/executefromaiovk.poolsimportAsyncVkExecuteRequestPoolasyncwithAsyncVkExecuteRequestPool()aspool:response=pool.add_call('users.get','YOUR_TOKEN',{'user_ids':1})response2=pool.add_call('users.get','YOUR_TOKEN',{'user_ids':2})response3=pool.add_call('users.get','ANOTHER_TOKEN',{'user_ids':1})response4=pool.add_call('users.get','ANOTHER_TOKEN',{'user_ids':-1})>>>print(response.ok)True>>>print(response.result)[{'id':1,'first_name':'Павел','last_name':'Дуров'}]>>>print(response2.result)[{'id':2,'first_name':'Александра','last_name':'Владимирова'}]>>>print(response3.result)[{'id':1,'first_name':'Павел','last_name':'Дуров'}]>>>print(response4.ok)False>>>print(response4.error){'method':'users.get','error_code':113,'error_msg':'Invalid user id'}orfromaiovk.poolsimportAsyncVkExecuteRequestPoolpool=AsyncVkExecuteRequestPool()response=pool.add_call('users.get','YOUR_TOKEN',{'user_ids':1})response2=pool.add_call('users.get','YOUR_TOKEN',{'user_ids':2})response3=pool.add_call('users.get','ANOTHER_TOKEN',{'user_ids':1})response4=pool.add_call('users.get','ANOTHER_TOKEN',{'user_ids':-1})awaitpool.execute()...
aiovk2
vk.com API python wrapper for asyncioThis is a fork ofhttps://github.com/Fahreeve/aiovkpackage which looks currently outdated and unmaintainedfor old version of python you can usehttps://github.com/dimka665/vkFeaturesasynchronoussupport python 3.5+ versionshave only one dependency -aiohttp 3+support two-factor authenticationsupport socks proxy withaiohttp-sockssupport rate limit of requestssupport Long Poll connectionTODOneed refactoring tests forAsyncVkExecuteRequestPoolInstallpipinstallaiovk2ExamplesAnnotationIn all the examples below, I will give only the{code}asyncdeffunc():{code}loop=asyncio.get_event_loop()loop.run_until_complete(func())AuthorizationTokenSession- if you already have token or you use requests which don’t require tokensession=TokenSession()session=TokenSession(access_token='asdf123..')ImplicitSession- client authorization in js apps and standalone (desktop and mobile) apps>>>session=ImplicitSession(USER_LOGIN,USER_PASSWORD,APP_ID)>>>awaitsession.authorize()>>>session.access_tokenasdfa2321afsdf12eadasf123...With scopes:ImplicitSession(USER_LOGIN,USER_PASSWORD,APP_ID,'notify')ImplicitSession(USER_LOGIN,USER_PASSWORD,APP_ID,'notify,friends')ImplicitSession(USER_LOGIN,USER_PASSWORD,APP_ID,['notify','friends'])ImplicitSession(USER_LOGIN,USER_PASSWORD,APP_ID,3)# notify and friendsAlso you can useSimpleImplicitSessionMixinfor entering confirmation code or captcha keyAuthorizationCodeSession- authorization for server apps or Open APISeehttps://vk.com/dev/authcode_flow_userfor getting the CODE>>>session=AuthorizationCodeSession(APP_ID,APP_SECRET,REDIRECT_URI,CODE)>>>awaitsession.authorize()>>>session.access_tokenasdfa2321afsdf12eadasf123...Or:>>>session=AuthorizationCodeSession(APP_ID,APP_SECRET,REDIRECT_URI)>>>awaitsession.authorize(CODE)>>>session.access_tokenasdfa2321afsdf12eadasf123...Authorization using context manager- you won’t need to use session.close() after workasyncwithaiovk2.TokenSession(access_token=YOUR_VK_TOKEN)asses:api=API(ses)...And your session will be closed after all done or code fail(similar to simple “with” usage) Works with all types of authorizationDriversHttpDriver- default driver for usingaiohttp>>>driver=HttpDriver()>>>driver=HttpDriver(timeout=10)# default timeout for all requests>>>driver=ProxyDriver(PROXY_ADDRESS,PORT)# 1234 is port>>>driver=ProxyDriver(PROXY_ADDRESS,PORT,timeout=10)>>>driver=ProxyDriver(PROXY_ADDRESS,PORT,PROXY_LOGIN,PROXY_PASSWORD,timeout=10)How to use custom driver with session:>>>session=TokenSession(...,driver=HttpDriver())How to use driver with own loop:>>>loop=asyncio.get_event_loop()>>>asyncio.set_event_loop(None)>>>session=TokenSession(driver=HttpDriver(loop=loop))# or ProxyDriverHow to use driver with custom http session object:Solve next problem:https://stackoverflow.com/questions/29827642/asynchronous-aiohttp-requests-fails-but-synchronous-requests-succeed>>>connector=aiohttp.TCPConnector(verify_ssl=False)>>>session=aiohttp.ClientSession(connector=connector)>>>driver=HttpDriver(loop=loop,session=session)LimitRateDriverMixin- mixin class what allow you create new drivers with speed rate limits>>>classExampleDriver(LimitRateDriverMixin,HttpDriver):...requests_per_period=3...period=1#secondsVK APIFirst variant:>>>session=TokenSession()>>>api=API(session)>>>awaitapi.users.get(user_ids=1)[{'first_name':'Pavel','last_name':'Durov','id':1}]Second variant:>>>session=TokenSession()>>>api=API(session)>>>awaitapi('users.get',user_ids=1)[{'first_name':'Pavel','last_name':'Durov','id':1}]Also you can addtimeoutargument for each request or define it in the sessionSeehttps://vk.com/dev/methodsfor detailed API guide.Lazy VK APIIt is useful when a bot has a large message flow>>>session=TokenSession()>>>api=LazyAPI(session)>>>message=api.users.get(user_ids=1)>>>awaitmessage()[{'first_name':'Pavel','last_name':'Durov','id':1}]Supports both variants like API objectUser Long PollFor documentation, see:https://vk.com/dev/using_longpollUse exist API object>>>api=API(session)>>>lp=UserLongPoll(api,mode=2)# default wait=25>>>awaitlp.wait(){"ts":1820350345,"updates":[...]}>>>awaitlp.wait(){"ts":1820351011,"updates":[...]}Use Session object>>>lp=UserLongPoll(session,mode=2)# default wait=25>>>awaitlp.wait(){"ts":1820350345,"updates":[...]}>>>awaitlp.get_pts()# return pts191231223>>>awaitlp.get_pts(need_ts=True)# return pts, ts191231223,1820350345You can iterate over events>>>asyncforeventinlp.iter():...print(event){"type":...,"object":{...}}Notice thatwaitvalue only for long pool connection.Real pause could be morewaittime because of need time for authorization (if needed), reconnect and etc.Bots Long PollFor documentation, see:https://vk.com/dev/bots_longpollUse exist API object>>>api=API(session)>>>lp=BotsLongPoll(api,group_id=1)# default wait=25>>>awaitlp.wait(){"ts":345,"updates":[...]}>>>awaitlp.wait(){"ts":346,"updates":[...]}Use Session object>>>lp=BotsLongPoll(session,group_id=1)# default wait=25>>>awaitlp.wait(){"ts":78455,"updates":[...]}>>>awaitlp.get_pts()# return pts191231223>>>awaitlp.get_pts(need_ts=True)# return pts, ts191231223,1820350345BotsLongPoll supports iterating too>>>asyncforeventinlp.iter():...print(event){"type":...,"object":{...}}Notice thatwaitvalue only for long pool connection.Real pause could be morewaittime because of need time for authorization (if needed), reconnect and etc.Async execute request poolFor documentation, see:https://vk.com/dev/executefromaiovk2.poolsimportAsyncVkExecuteRequestPoolasyncwithAsyncVkExecuteRequestPool()aspool:response=pool.add_call('users.get','YOUR_TOKEN',{'user_ids':1})response2=pool.add_call('users.get','YOUR_TOKEN',{'user_ids':2})response3=pool.add_call('users.get','ANOTHER_TOKEN',{'user_ids':1})response4=pool.add_call('users.get','ANOTHER_TOKEN',{'user_ids':-1})>>>print(response.ok)True>>>print(response.result)[{'id':1,'first_name':'Павел','last_name':'Дуров'}]>>>print(response2.result)[{'id':2,'first_name':'Александра','last_name':'Владимирова'}]>>>print(response3.result)[{'id':1,'first_name':'Павел','last_name':'Дуров'}]>>>print(response4.ok)False>>>print(response4.error){'method':'users.get','error_code':113,'error_msg':'Invalid user id'}orfromaiovk2.poolsimportAsyncVkExecuteRequestPoolpool=AsyncVkExecuteRequestPool()response=pool.add_call('users.get','YOUR_TOKEN',{'user_ids':1})response2=pool.add_call('users.get','YOUR_TOKEN',{'user_ids':2})response3=pool.add_call('users.get','ANOTHER_TOKEN',{'user_ids':1})response4=pool.add_call('users.get','ANOTHER_TOKEN',{'user_ids':-1})awaitpool.execute()...
aiovkapi
No description available on PyPI.
aiovkcom
aiovkcomaiovkcom is a pythonvk.com APIwrapper. The main features are:authorization (Authorization Code,Implicit Flow)REST APImethodsUsageTo usevk.com APIyou need a registered app andvk.comaccount. For more details, seeaiovkcom Documentation.fromaiovkcomimportTokenSession,APIsession=TokenSession(access_token,v='5.101')api=API(session)events=awaitapi.wall.get()friends=awaitapi.friends.get()Passaccess_tokenthat was received after authorization. For more details, seeaiovkcom Documentation.Installation$pipinstallaiovkcomor$pythonsetup.pyinstallSupported Python VersionsPython 3.5, 3.6, 3.7 and 3.8 are supported.TestRun all tests.$pythonsetup.pytestRun tests with PyTest.$python-mpytest[-kTEST_NAME]Licenseaiovkcom is released under the BSD 2-Clause License.
aiovkmusic
aiovkmusicОписаниеPython пакет для поиска музыки и плейлистов в VK с возможностью асинхронного скачивания аудиозаписей.Что нового в последней версии?УстановкаaiovkmusicсредствамиPyPi:pip install aiovkmusicИ убедитесь, что на ваш компьютер установленffmpeg.Сразу же перейдём к примерам использования:importasynciofromaiovkmusicimportMusic,VKSession,Track,Playlistasyncdefmain():# Создание сессии.# ВАЖНО: подключаемый аккаунт ВК должен быть БЕЗ двухэтапной аутентификации.# (Если переживаете - используйте фейк.)session=VKSession(login='<номер_телефона/электронная_почта>',password='<пароль_от_вконтакте>',session_file_path='session.json')# Получение интерфейса к vk music api.music=Music(user='<ссылка_на_профиль>',session=session)# Получение всех плейлистов указанного пользователя.playlists=music.playlists()# -> [Playlists]forplaylistinplaylists:print(playlist.title)# pyrokinesis# GAME OVER# Live Rock# Получение аудиозаписей указанного плейлиста.playlist_tracks=music.playlist_tracks(playlists[0])# -> [Track]fortrackinplaylist_tracks:print(track.fullname)# 99 Problems - Big Baby Tape kizaru# So Icy Nihao - Big Baby Tape kizaru# Big Tymers - Big Baby Tape kizaru# Поиск по названию (аналогично поиску в VK).tracks=music.search('Три дня дождя',count=5,offset=0,official=True)# -> [Track]fortrackintracks:print(track.fullname)# Вина - Три дня дождя# Демоны - Три дня дождя# Привычка - Три дня дождя# Не выводи меня - МУККА Три дня дождя# Не Киряй - МУККА Три дня дождя# Загрузка переданных аудиозаписей по указанному пути.downloaded_tracks=awaitmusic.download(tracks,bitrate=320,path='music')# -> [Track]fortrackindownloaded_tracks:print(track.path)# music/108481371.mp3# music/62163423.mp3# music/106817510.mp3# music/60284123.mp3# music/105514252.mp3## <--- NEW IN VERSION 1.1.0! --->## Получение аудиозаписей указанного пользователя.user_tracks=music.user_tracks()# -> [Track]asyncio.run(main())Используемые представления данных:classPlaylist:id:intowner_id:inttitle:strplays:inturl:straccess_hash:strclassTrack:id:intowner_id:intcover_url:strurl:strartist:strtitle:strduration:intpath:strfullname:strHow to contact the maintainer:
aiovkmusic_x
aiovkmusic_xОписаниеАсинхронная python библиотека для работы с VK музыкой, является форком aiovkmusic.Установкаaiovkmusic-xсредствамиPyPi:pip install aiovkmusic-xДля работы необходимffmpeg.Примеры использования:importasynciofromaiovkmusic_ximportMusic,VKSession,Track,Playlistasyncdefmain():# Создание сессии.# Двухэтапная аутентификация не поддерживаетсяsession=VKSession(login='<номер_телефона/электронная_почта>',password='<пароль_от_вконтакте>',session_file_path='session.json')# self позволяет взять айди из сессииmusic=Music(user='self',session=session)tracks=music.search("Geoxor",official=True)fortrackintracks:awaitmusic.download(track)asyncio.run(main())Используемые представления данных:classPlaylist:id:intowner_id:inttitle:strplays:inturl:straccess_hash:strclassTrack:id:intowner_id:intcover_url:strurl:strartist:strtitle:strduration:intpath:strfullname:str
aiovk-new
No description available on PyPI.
aiovkrmq
aiovkrmq
aiovk-varnar-fork
vk.com API python wrapper for asynciofor old version of python you can usehttps://github.com/dimka665/vkFeaturesasynchronoussupport python 3.5+ versionshave only one dependency -aiohttpsupport two-factor authenticationsupport socks proxy withaiosockssupport rate limit of requestssupport Long Poll connectionInstallpipinstallaiovkExamplesAnnotationIn all the examples below, I will give only the{code}asyncdeffunc():{code}loop=asyncio.get_event_loop()loop.run_until_complete(func())AuthorizationTokenSession- if you already have token or you use requests which don’t require tokensession=TokenSession()session=TokenSession(access_token='asdf123..')ImplicitSession- client authorization in js apps and standalone (desktop and mobile) apps>>>session=ImplicitSession(USER_LOGIN,USER_PASSWORD,APP_ID)>>>awaitsession.authorize()>>>session.access_tokenasdfa2321afsdf12eadasf123...With scopes:ImplicitSession(USER_LOGIN,USER_PASSWORD,APP_ID,'notify')ImplicitSession(USER_LOGIN,USER_PASSWORD,APP_ID,'notify,friends')ImplicitSession(USER_LOGIN,USER_PASSWORD,APP_ID,['notify','friends'])ImplicitSession(USER_LOGIN,USER_PASSWORD,APP_ID,3)# notify and friendsAlso you can useSimpleImplicitSessionMixinfor entering confirmation code or captcha keyAuthorizationCodeSession- authorization for server apps or Open APISeehttps://vk.com/dev/authcode_flow_userfor getting the CODE>>>session=AuthorizationCodeSession(APP_ID,APP_SECRET,REDIRECT_URI,CODE)>>>awaitsession.authorize()>>>session.access_tokenasdfa2321afsdf12eadasf123...Or:>>>session=AuthorizationCodeSession(APP_ID,APP_SECRET,REDIRECT_URI)>>>awaitsession.authorize(CODE)>>>session.access_tokenasdfa2321afsdf12eadasf123...Authorization using context manager- you won’t need to use session.close() after workasyncwithaiovk.TokenSession(access_token=YOUR_VK_TOKEN)asses:api=API(ses)...And your session will be closed after all done or code fail(similar to simple “with” usage) Works with all types of authorizationDriversHttpDriver- default driver for usingaiohttp>>>driver=HttpDriver()>>>driver=HttpDriver(timeout=10)# default timeout for all requests>>>driver=Socks5Driver(PROXY_ADDRESS,PORT)# 1234 is port>>>driver=Socks5Driver(PROXY_ADDRESS,PORT,timeout=10)>>>driver=Socks5Driver(PROXY_ADDRESS,PORT,PROXY_LOGIN,PROXY_PASSWORD,timeout=10)How to use custom driver with session:>>>session=TokenSession(...,driver=HttpDriver())How to use driver with own loop:>>>loop=asyncio.get_event_loop()>>>asyncio.set_event_loop(None)>>>session=TokenSession(driver=HttpDriver(loop=loop))# or Socks5DriverHow to use driver with custom http session object:Solve next problem:https://stackoverflow.com/questions/29827642/asynchronous-aiohttp-requests-fails-but-synchronous-requests-succeed>>>connector=aiohttp.TCPConnector(verify_ssl=False)>>>session=aiohttp.ClientSession(connector=connector)>>>driver=HttpDriver(loop=loop,session=session)LimitRateDriverMixin- mixin class what allow you create new drivers with speed rate limits>>>classExampleDriver(LimitRateDriverMixin,HttpDriver):...requests_per_period=3...period=1#secondsVK APIFirst variant:>>>session=TokenSession()>>>api=API(session)>>>awaitapi.users.get(user_ids=1)[{'first_name':'Pavel','last_name':'Durov','id':1}]Second variant:>>>session=TokenSession()>>>api=API(session)>>>awaitapi('users.get',user_ids=1)[{'first_name':'Pavel','last_name':'Durov','id':1}]Also you can addtimeoutargument for each request or define it in the sessionSeehttps://vk.com/dev/methodsfor detailed API guide.Lazy VK APIIt is useful when a bot has a large message flow>>>session=TokenSession()>>>api=LazyAPI(session)>>>message=api.users.get(user_ids=1)>>>awaitmessage()[{'first_name':'Pavel','last_name':'Durov','id':1}]Supports both variants like API objectLong PollUse exist API object>>>api=API(session)>>>lp=LongPoll(api,mode=2)# default wait=25>>>awaitlp.wait(){"ts":1820350345,"updates":[...]}>>>awaitlp.wait(){"ts":1820351011,"updates":[...]}Use Session object>>>lp=LongPoll(session,mode=2)# default wait=25>>>awaitlp.wait(){"ts":1820350345,"updates":[...]}>>>awaitlp.get_pts()# return pts191231223>>>awaitlp.get_pts(need_ts=True)# return pts, ts191231223,1820350345Notice thatwaitvalue only for long pool connection.Real pause could be morewaittime because of need time for authorization (if needed), reconnect and etc.
aiovlc
aiovlcControl VLC over telnet connection using asyncioInstallationInstall this via pip (or your favourite package manager):pip install aiovlcCreditsThis package was created withCopierand thebrowniebroke/pypackage-templateproject template.