package
stringlengths
1
122
pacakge-description
stringlengths
0
1.3M
aiohttp-sse-client
SSE ClientA Server-Sent Event python client base on aiohttp, provides a simple interface to processServer-Sent Event.Free software: Apache Software License 2.0Documentation:https://aiohttp-sse-client.readthedocs.io.FeaturesFull asyncio supportEasy to integrate with other aiohttp based projectAuto-reconnect for network issueSupport python 3.6 and aboveUsagefromaiohttp_sse_clientimportclientassse_clientasyncwithsse_client.EventSource('https://stream.wikimedia.org/v2/stream/recentchange')asevent_source:try:asyncforeventinevent_source:print(event)exceptConnectionError:passCreditsThis project was inspired byaiosseclient,sseclient, andsseclient-py.This package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.History0.2.1 (2021-02-27)Allow sending request with different HTTP methods (by @paulefoe)Migrate to GitHub Actions0.2.0 (2020-10-20)Breaking ChangesDrop Python 3.5 supportAdd Python 3.8 supportNon functional changesClarify the license (Apache Software License 2.0), thanks @fabaffUpdate dependency packages0.1.7 (2020-03-30)Allow passing kwargs without specifying headers0.1.6 (2019-08-06)Fix Unicode NULL handling in event id field0.1.5 (2019-08-06)Fix last id reconnection (by @Ronserruya)0.1.4 (2018-10-04)Switch to Apache Software License 2.00.1.3 (2018-10-03)Change the error handling, better fit the live specification.0.1.2 (2018-10-03)Implement auto-reconnect feature.0.1.1 (2018-10-02)First release on PyPI.
aiohttp-sse-client2
This is a fork of theaiohttp-sse-clientproject by Jason Hu. The motivations for the fork are:Better error messages when the request fails (#190)Update the library to support new Python versionsThe fork will be retired if the upstream package comes back alive.Fork changelog0.3.0 (February 7, 2023) * Drop support for Python 3.6 * Support Python 3.10 and 3.11 * Include response body in exception for non-200 response codesOriginal README follows:SSE ClientA Server-Sent Event python client base on aiohttp, provides a simple interface to processServer-Sent Event.Free software: Apache Software License 2.0Documentation:https://aiohttp-sse-client.readthedocs.io.FeaturesFull asyncio supportEasy to integrate with other aiohttp based projectAuto-reconnect for network issueSupport python 3.6 and aboveUsagefromaiohttp_sse_client2importclientassse_clientasyncwithsse_client.EventSource('https://stream.wikimedia.org/v2/stream/recentchange')asevent_source:try:asyncforeventinevent_source:print(event)exceptConnectionError:passCreditsThis project was inspired byaiosseclient,sseclient, andsseclient-py.This package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.History0.2.1 (2021-02-27)Allow sending request with different HTTP methods (by @paulefoe)Migrate to GitHub Actions0.2.0 (2020-10-20)Breaking ChangesDrop Python 3.5 supportAdd Python 3.8 supportNon functional changesClarify the license (Apache Software License 2.0), thanks @fabaffUpdate dependency packages0.1.7 (2020-03-30)Allow passing kwargs without specifying headers0.1.6 (2019-08-06)Fix Unicode NULL handling in event id field0.1.5 (2019-08-06)Fix last id reconnection (by @Ronserruya)0.1.4 (2018-10-04)Switch to Apache Software License 2.00.1.3 (2018-10-03)Change the error handling, better fit the live specification.0.1.2 (2018-10-03)Implement auto-reconnect feature.0.1.1 (2018-10-02)First release on PyPI.
aiohttp-swagger
aiohttp-swaggerLOOCKING FOR MAINTAINERS!!!!!aiohttp-swagger: Swagger API Documentation builder for aiohttp serverDocumentationhttp://aiohttp-swagger.readthedocs.io/en/latest/Codehttps://github.com/cr0hn/aiohttp-swaggerIssueshttps://github.com/cr0hn/aiohttp-swagger/issues/Python versionPython 3.4 and aboveWhat's aiohttp-swaggeraiohttp-swagger is a plugin for aiohttp.web server that allow to document APIs using Swagger show the Swagger-ui console.What's new?Version 1.0.0First version releasedYou can read entire list inCHANGELOGfile.
aiohttp-swagger3
aiohttp-swagger3AboutPackage for displaying swagger docs via different UI backends and optionally validating/parsing aiohttp requests using swagger specification 3.0, known as OpenAPI3.Supported UI backendsMultiple UI backends can be used or UI backend can be disabled at all if only needed validation without being able to view documentation.Swagger UI -https://github.com/swagger-api/swagger-uiReDoc -https://github.com/Redocly/redocRapiDoc -https://github.com/mrin9/RapiDocDocumentationhttps://aiohttp-swagger3.readthedocs.io/en/latest/Disable validationPassvalidate=FalsetoSwaggerDocs/SwaggerFileclass, the default isTrueAlso, sometimes validation has to be disabled for a route, to do this you have to passvalidate=Falseduring the initialization of the route.ex.web.post("/route",handler, validate=False), the default isTrueRequirementspython >= 3.8aiohttp >= 3.8.0pyyaml >= 5.4attrs >= 19.3.0python-fastjsonschema >= 2.15.0rfc3339-validator >= 0.1.4Limitationsonly application/json and application/x-www-form-urlencoded supported for now, but you can create ownhandlerheader/query parameters only supported simple/form array serialization, e.g. 1,2,3,4see TODO belowInstallationpip installaiohttp-swagger3Examplefromaiohttpimportwebfromaiohttp_swagger3importSwaggerDocs,SwaggerInfo,SwaggerUiSettingsasyncdefget_one_pet(request:web.Request,pet_id:int)->web.Response:""" Optional route description --- summary: Info for a specific pet tags: - pets parameters: - name: pet_id in: path required: true description: The id of the pet to retrieve schema: type: integer format: int32 responses: '200': description: Expected response to a valid request content: application/json: schema: $ref: "#/components/schemas/Pet" """ifpet_idnotinrequest.app['storage']:raiseweb.HTTPNotFound()returnweb.json_response(request.app['storage'][pet_id])defmain():app=web.Application()swagger=SwaggerDocs(app,swagger_ui_settings=SwaggerUiSettings(path="/docs/"),info=SwaggerInfo(title="Swagger Petstore",version="1.0.0",),components="components.yaml")swagger.add_routes([web.get("/pets/{pet_id}",get_one_pet),])app['storage']={}web.run_app(app)MoreexamplesHow it helpsFeaturesapplication/jsonapplication/x-www-form-urlencoded (except array and object)itemspropertiespatternrequiredenumminimum, maximumexclusiveMinimum, exclusiveMaximumminLength, maxLengthminItems, maxItemsuniqueItemsminProperties, maxPropertiesdefault (only primitives)additionalPropertiesnullablereadOnlyallOf, oneOf, anyOfstring formats: date, date-time, byte, email, uuid, hostname, ipv4, ipv6custom string format validatorsTODO (raise an issue if needed)multipleOfnotallowEmptyValueCommon Parameters for All Methods of a Path (spec file only)more serialization methods, see:https://swagger.io/docs/specification/serialization/encodingform data serialization (array, object)default (array, object)
aiohttp-swagger-fix
LOOCKING FOR MAINTAINERS!!!!!![Logo](doc/source/_static/logo.png)[![Build Status](https://travis-ci.org/cr0hn/aiohttp-swagger.svg?branch=master)](https://travis-ci.org/cr0hn/aiohttp-swagger) [![codecov.io](https://codecov.io/github/cr0hn/aiohttp-swagger/coverage.svg?branch=master)](https://codecov.io/github/cr0hn/aiohttp-swagger)aiohttp-swagger: Swagger API Documentation builder for aiohttp serverDocumentation |http://aiohttp-swagger.readthedocs.io/en/latest/————- | ————————————————- Code |https://github.com/cr0hn/aiohttp-swaggerIssues |https://github.com/cr0hn/aiohttp-swagger/issues/Python version | Python 3.4 and aboveWhat’s aiohttp-swaggeraiohttp-swagger is a plugin for aiohttp.web server that allow to document APIs using Swagger show the Swagger-ui console.What’s new?### Version 1.0.0First version releasedYou can read entire list in [CHANGELOG](https://github.com/cr0hn/aiohttp-swagger/blob/master/CHANGELOG) file.
aiohttp_swaggerify
aiohttp_swaggerifyLibrary to automatically generate swagger2.0 definition for aiohttp endpointsFree software: MIT licenseDocumentation:https://aiohttp-swaggerify.readthedocs.io.FeaturesTODOCreditsThis package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.History0.1.0 (2016-10-12)First release on PyPI.
aiohttp-tal
aiohttp_talTALChameleontemplate engine renderer foraiohttp.web. Based onaiohttp_jinja2.InstallationInstall from PyPI:pip install aiohttp-talDevelopingInstall requirement and launch tests:pip install -r requirements-dev.txt pytest testsUsageFor more details on usage, seehttps://aiohttp-tal.readthedocs.io/en/latest/usage.html.Before template rendering you have to setupTAL environmentfirst:app=web.Application()aiohttp_tal.setup(app,loader=chameleon.PageTemplateLoader('/path/to/templates/folder'))Import:importaiohttp_talimportchameleonAfter that you may to use template engine in yourweb-handlers. The most convenient way is to decorate aweb-handler.Using the function based web handlers:@aiohttp_tal.template('tmpl.pt')defhandler(request):return{'name':'Andrew','surname':'Svetlov'}Licenseaiohttp_talis offered under the GPLv3 license.This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.CHANGES0.1.0 (2019-03-28)Initial release. Based on aiohttp-jinja2 copyright by Andrew Svetlo and aio-libs team.
aiohttp_tests
Unittest helper utilities for aiohttp-based applications.Example usage:importasyncioimporttimefromunittestimportmockimportaiohttp_testsasatfromaiohttpimportwebsettings=mock.Mock()@at.override_settings(settings,SETTINGS_VALUE='new_value')classExampleTestCase(at.BaseTestCase):""" Aiohttp tests utilities example"""@asyncio.coroutinedefsample_view(self,request):text=yield fromself.sample_async_method()returnweb.Response(text=text)@asyncio.coroutinedefsample_async_method(self):yield fromasyncio.sleep(0.1)return'OK'definit_app(self,loop):""" You must initialize aiohttp application correctly."""app=web.Application(loop=loop)app.router.add_route('GET','/',self.sample_view)returnappdefinit_patchers(self):super().init_patchers()# Short alias for mock.patch that stores patcher and mock objects# locally. Patchers are stopped automatically on teardown.# Method is called by BaseTestCase.setUpself.mock('time.time',return_value=self.now)defsetUp(self):self.now=time.time()super().setUp()deftestMockUtils(self):""" Shows usage of get_mock and get_patcher methods."""self.assertEqual(time.time(),self.now)self.get_mock('time.time').return_value=self.now-1self.assertEqual(time.time(),self.now-1)self.get_patcher('time.time').stop()self.assertGreater(time.time(),self.now)deftestOverrideSettings(self):""" Django-style override_settings decorator for any settings module."""self.assertEqual(settings.SETTINGS_VALUE,'new_value')withat.override_settings(settings,SETTINGS_VALUE='other_value'):self.assertEqual(settings.SETTINGS_VALUE,'other_value')deftestSyncClient(self):""" Synchronous execution of requests, with new event loop every time. Other HTTP methods, HTTP headers, request body or form/data are also supported. """response=self.client.get('/',headers={'Accept':'application/json'})self.assertEqual(response.status,200)self.assertEqual(response.text,'OK')self.assertEqual(response.headers.get('content-type'),'text/plain; charset=utf-8')# other HTTP methodsresponse=self.client.post('/',body='POST body')self.assertEqual(response.status,405)# urlencoded form/data also supportedresponse=self.client.request('PUT','/',data={'field':'value'})self.assertEqual(response.status,405)@at.async_testdeftestAsyncClient(self):""" test client requests could be done async, if needed."""# you can mock any coroutine to return a 'done' Future with custom# result.done_future=self.empty_result("async response")# mock.patck.object shortcutself.mock_object(self,'sample_async_method',return_value=done_future)response=yield fromself.client.get('/')self.assertEqual(response.text,"async response")
aiohttp-test-utils
This library is not intended for public use.
aiohttp-theme
Based on Alabasterhttp://alabaster.readthedocs.io
aiohttp_themes
Author:Scott TorborgTheme and frontend asset management for aiohttp.
aiohttp-things
Modest utility collection for development withAIOHTTPframework.Documentationhttps://aiohttp-things.readthedocs.ioInstallationInstallingaiohttp-thingswith pip:pip install aiohttp-thingsSimple exampleExample of AIOHTTP applicationimportjsonimportuuidimportaiohttp_thingsasahthfromaiohttpimportwebdefsafe_json_value(value):try:json.dumps(value)returnvalueexcept(TypeError,OverflowError):returnstr(value)classBase(web.View,ahth.JSONMixin,ahth.PrimaryKeyMixin):asyncdefget(self):self.context['Type of primary key']=safe_json_value(type(self.pk))self.context['Value of primary key']=safe_json_value(self.pk)returnawaitself.finalize_response()classIntegerExample(Base):pk_adapter=intclassUUIDExample(Base):pk_adapter=uuid.UUIDUUID='[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}'ROUTES=[web.view('/integer/{pk:[0-9]+}',IntegerExample),web.view(f'/uuid/{{pk:{UUID}}}',UUIDExample),]asyncdefapp_factory():app=web.Application()app.add_routes(ROUTES)returnappif__name__=='__main__':web.run_app(app_factory())Examples HTTP requests and responsehttp://0.0.0.0:8080/integer/1{"Type of primary key":"<class 'int'>","Value of primary key":1}http://0.0.0.0:8080/integer/9999999999999{"Type of primary key":"<class 'int'>","Value of primary key":9999999999999}http://0.0.0.0:8080/integer/a352da04-c1af-4a44-8a94-c37f8f37b2bc404: Not Foundhttp://0.0.0.0:8080/integer/abc404: Not Foundhttp://0.0.0.0:8080/uuid/a352da04-c1af-4a44-8a94-c37f8f37b2bc{"Type of primary key":"<class 'uuid.UUID'>","Value of primary key":"a352da04-c1af-4a44-8a94-c37f8f37b2bc"}http://0.0.0.0:8080/uuid/13d1d0e0-4787-4feb-8684-b3da32609743{"Type of primary key":"<class 'uuid.UUID'>","Value of primary key":"13d1d0e0-4787-4feb-8684-b3da32609743"}http://0.0.0.0:8080/uuid/1404: Not Foundhttp://0.0.0.0:8080/uuid/abc404: Not Found
aiohttp-tokenauth
aiohttp-tokenauthAiohttp simple token auth middleware that can check any token that assign to user or group of users in database or some another place.Installationpipinstallaiohttp_tokenauthDocumentationBasic usageFirst of all, let's create a simple app.# Full text in example/simple_app.pyfromaiohttpimportwebfromaiohttp_tokenauthimporttoken_auth_middlewareasyncdefexample_resource(request):returnweb.json_response(request['user'])asyncdefinit():asyncdefuser_loader(token:str):"""Checks that token is validIt's the callback that will get the token from "Authorization" header.It can check that token is exist in a database or some another place.Args:token (str): A token from "Authorization" http header.Returns:Dict or something else. If the callback returns None thenthe aiohttp.web.HTTPForbidden will be raised."""user=Noneiftoken=='fake-token':user={'uuid':'fake-uuid'}returnuserapp=web.Application(middlewares=[token_auth_middleware(user_loader)])app.router.add_get('/',example_resource)returnappif__name__=='__main__':web.run_app(init())Then, run the aiohttp app.$pythonexample/simple_app.py========Runningonhttp://0.0.0.0:8080========(PressCTRL+Ctoquit)Now try to get access to url with token in "Authorization" header.$curl-H'Authorization: Bearer fake-token'http://0.0.0.0:8080{"uuid":"fake-uuid"}And result without token.$curlhttp://0.0.0.0:8080401:MissingauthorizationheaderIgnoring routes and http methodsYou can ignore specific routes, app the paths to "exclude_routes".app=web.Application(middlewares=[token_auth_middleware(user_loader=user_loader,# You can use regular expressions hereexclude_routes=('/exclude',r'/exclude/\w+/info'),exclude_methods=('POST',),),])Change auth schemeFor changing the scheme (prefix in "Authorization" header) useauth_schemeargument.app=web.Application(middlewares=[token_auth_middleware(user_loader=user_loader,auth_scheme='Token',),])Now such request is valid:$curl-H'Authorization: Token fake-token'http://0.0.0.0:8080{"uuid":"fake-uuid"}
aiohttp-toolbox
Tools for aiohttp I want to reuse.InstallationRequirespython 3.7.pipinstallaiohttp-toolboxTo test:atoolbox --root tests/demo webHistoryv0.6.3 (2019-12-12)addparse_requestmethod toExecViewv0.6.2 (2019-10-23)uprev. pydantic to Version 1v0.6.1 (2019-10-17)fixDummyPgPoolto not allow direct transactions.v0.6.0 (2019-10-08)drop and recreate schema with a different connection before populating the databasefix CSRF failure on file upload on firefox by allowing no Origin for uploadsv0.5.3 (2019-08-21)Switch to direct usage of sentry-sdk (sigh)v0.5.2 (2019-08-20)switch from raven to sentry-sdkv0.5.1 (2019-08-20)upgrade pypi deploy to use API tokensv0.5 (2019-08-20)reprand timeout forDummyPgPoolimprove error middleware for better fingerprint inlog_warningimprove error middleware for better compatibility with sentryv0.4.4 (2019-07-31)addshellcommandtweak dummy server request logging, add response codeupgradearqtov0.16upgradepydantictov0.31.1v0.4.1 (2019-04-29)404 for.well-known/*urls inspa_static_handlerallow google recaptcha test keysv0.4.0 (2019-04-09)addspa_static_handlerv0.3.3 (2019-03-21)tweakpatch_pathsv0.3.2 (2019-03-15)addpatch_pathsto settingsexc_infoadding middleware warningv0.3.1 (2019-03-13)addautocommand to CLIv0.3.0 (2019-03-08)supportarq >= 0.16andpydantic > 0.20, #12v0.2.2 (2019-02-13)pg_middlewarenow respectspg_middleware_checkfunction, fix #10v0.2.1 (2019-02-07)tweak imports, repr method forJsonErrorsv0.2.0 (2019-02-04)improvedclass_viewsuseargparsein clifix logging setupallow patches to not be coroutinesaddskip_if_offlinepytest decoratorv0.1.0 (2019-01-24)improve logging output #9cleanup cliadd commands:flush_redisandcheck_web, implementwait_for_services#7v0.0.11 (2018-12-27)uprev aiohttp-sessionsupport latest aiohttpv0.0.9 (2018-12-16)allow settings and redis and postgres to be optional when creating appsv0.0.8 (2018-12-12)optionalconnonViewimproveraw_json_responseaddJsonErrors.HTTPAcceptedrenameparse_request->parse_request_jsonaddparse_request_queryv0.0.7 (2018-11-28)improved CSRFv0.0.6 (2018-11-22)allow for requests without aconnv0.0.5 (2018-11-22)improve bread, usehandlenotcheck_permissionsv0.0.4 (2018-11-21)addcheck_grecaptchaimprove middlewarev0.0.3 (2018-11-20)tweak cli and how worker is runv0.0.2 (2018-11-19)change module namev0.0.1 (2018-11-19)first release
aiohttp-tools
It contains:url_for- flask-like url reverserjsonify- flask-like json-dumper with support ofdatetime, andObjectIdredirect- django-like redirectget_argument- tornado-like util to get GET / POST argumentsstatic_url- tornado-like url-wrapper to add version hast to static assetflash- simple flash messages, usage described bellowget_client_ip- client IP addressfix_host- middleware for redirect requests by IP to right domaintemplate_handler- handler that just render templateurl_for_processor- context processor for usingurl_forwithout passing requestsession_processor- context_processor foraiohttp_sessionLook at theexamplefolder for working example.Installationpip install aiohttp_toolsRepository:https://github.com/imbolc/aiohttp_toolsFlash messagesfromaiohttp_tools.flashimportflash# you should include session middleware before flash middlewareaiohttp_session.setup(app,...)app.middlewares.append(aiohttp_tools.flash.middleware)context_processors.append(aiohttp_tools.flash.context_processor)asyncdefhandler(request):flash.message(request,'Message','level')# shortcutsflash.info(request,'Some message')flash.success(...)flash.warning(...)flash.error(...){% for message, level in get_flashed_messages() %}<divclass="flash {{ level }}">{{ message }}</div>{% endfor %}
aiohttp_trailers
This is a security placeholder package. If you want to claim this name for legitimate purposes, please contact us [email protected]@yandex-team.ru
aiohttp-transmute
NOTE: this library is now deprecated, with transute-core supporting aiohttp directly. See https://transmute-core.readthedocs.io/
aiohttp_traversal
No description available on PyPI.
aiohttp-tus
tus.ioserver implementation foraiohttp.webapplications.For uploading large files, please consider usingaiotus(Python 3.7+) library instead.Works on Python 3.6+Works with aiohttp 3.5+BSD licensedLatest documentationon Read The DocsSource, issues, and pull requestson GitHubQuickstartCode belows shows how to enable tus-compatible uploads on/uploadsURL foraiohttp.webapplication. After upload, files will be available at../uploadsdirectory.frompathlibimportPathfromaiohttpimportwebfromaiohttp_tusimportsetup_tusapp=setup_tus(web.Application(),upload_url="/uploads",upload_path=Path(__file__).parent.parent/"uploads",)Chunk SizePlease, make sure to configureclient_max_sizeforaiohttp.webApplication and supply properchunkSizefor Uppy.io or other tus.io client.DocumentationCORS HeadersTo setup CORS headers you need to usecors_middlewarefromaiohttp-middlewarespackage.aiohttp-corslibrary not supported cause ofaio-libs/aiohttp-cors#241issue.DocumentationReverse proxy and HTTPSWhenaiohttpapplication deployed under the reverse proxy (such as nginx) with HTTPS support, it is needed to usehttps_middlewarefromaiohttp-middlewarespackage to ensure thatweb.Requestinstance has proper schema.DocumentationExamplesexamples/directory contains several examples, which illustrate how to useaiohttp-tuswith some tus.io clients, such astus.pyandUppy.io.
aiohttp-ultrajson
Integrates UltraJSON with your aiohttp application.
aiohttp-utils
aiohttp-utilsprovides handy utilities for buildingaiohttp.webapplications.Method-based handlers (“resources”)Routing utilitiesContent negotiation with JSON rendering by defaultEverything is optional. You can use as much (or as little) of this toolkit as you need.fromaiohttpimportwebfromaiohttp_utilsimportResponse,routing,negotiationapp=web.Application(router=routing.ResourceRouter())# Method-based handlersclassHelloResource:asyncdefget(self,request):name=request.GET.get('name','World')returnResponse({'message':'Hello '+name})app.router.add_resource_object('/',HelloResource())# Content negotiationnegotiation.setup(app,renderers={'application/json':negotiation.render_json})Install$ pip install aiohttp-utilsDocumentationFull documentation is available athttps://aiohttp-utils.readthedocs.io/.Project LinksDocs:https://aiohttp-utils.readthedocs.io/Changelog:https://aiohttp-utils.readthedocs.io/en/latest/changelog.htmlPyPI:https://pypi.python.org/pypi/aiohttp-utilsIssues:https://github.com/sloria/aiohttp-utils/issuesLicenseMIT licensed. See the bundledLICENSEfile for more details.
aiohttp-valera-validator
aiohttp-valera-validatorRequest validation foraiohttp(viavalera)Installation$pip3installaiohttp-valera-validatorUsagefromaiohttp.webimportApplication,json_response,route,run_appfromdistrict42importschemafromaiohttp_valera_validatorimportvalidateParamsSchema=schema.dict({"q":schema.str.len(1,...)})@validate(params=ParamsSchema)asyncdefhandler(request):q=request.query["q"]returnjson_response({"q":q})app=Application()app.add_routes([route("GET","/users",handler)])run_app(app)// http /users?q=Bob{"q":"Bob"}// http /users{"errors":["Value <class 'str'> at _['q'] must have at least 1 element, but it has 0 elements"]}DocsQuery params validationfromdistrict42importschemafromaiohttp_valera_validatorimportvalidate# schema.dict is strict by default (all keys must be present)ParamsSchema=schema.dict({"q":schema.str.len(1,...)})@routes.get("/users")@validate(params=ParamsSchema)asyncdefhandler(request):q=request.query["q"]returnjson_response({"q":q})Headers validationfromdistrict42importschemafromaiohttp_valera_validatorimportvalidatefrommultidictimportistr# "..." means that there can be any other keys# headers are case-insensitive, so we use istr forHeadersSchema=schema.dict({istr("User-Agent"):schema.str.len(1,...),...:...})@routes.get("/users")@validate(headers=HeadersSchema)asyncdefhandler(request):user_agent=request.headers["User-Agent"]returnjson_response({"user_agent":user_agent})JSON body validationfromdistrict42importschemafromaiohttp_valera_validatorimportvalidateBodySchema=schema.dict({"id":schema.int.min(1),"name":schema.str.len(1,...),})@routes.post("/users")@validate(json=BodySchema)asyncdefhandler(request):payload=awaitrequest.json()returnjson_response({"id":payload["id"],"name":payload["name"]})URL segments validationSegments — is a variable part of URL path (aiohttpusesmatch_infofor it)fromdistrict42importschemafromaiohttp_valera_validatorimportvalidateSegmentsSchema=schema.dict({"user_id":schema.str.regex(r"[1-9][0-9]*"),})@routes.get("/users/{user_id}")@validate(segments=SegmentsSchema)asyncdefhandler(request):user_id=int(request.match_info["user_id"])returnjson_response({"user_id":user_id})Custom responsefromhttpimportHTTPStatusfromaiohttp.webimportRequest,Responsefromaiohttp_valera_validatorimportvalidateasvalidate_origclassvalidate(validate_orig):defcreate_error_response(self,request:Request,errors:List[str])->Response:status=HTTPStatus.UNPROCESSABLE_ENTITYbody="<ul>"+"".join(f"<li>{error}</li>"forerrorinerrors)+"</ul>"returnResponse(status=status,text=body,headers={"Content-Type":"text/html"})—Fore more information readvalera docs
aiohttp_validate
aiohttp_validateSimple library that helps you validate your API endpoints requests/responses withjsonschema. Documentation is also available here athttps://aiohttp-validate.readthedocs.io.InstallationInstall from PyPI:pip install aiohttp_validateUsageComplete example of validation fortext tokenization microservice:from aiohttp_validate import validate @validate( request_schema={ "type": "object", "properties": { "text": {"type": "string"}, }, "required": ["text"], "additionalProperties": False }, response_schema={ "type": "array", "items": { "type": "array", "items": { "type": "array", "items": {"type": "string"} } } } ) async def tokenize_text_handler(request, *args): return tokenize_text(request["text"])FeaturesThe decorator to (optionally) validate the request to your aiohttp endpoint and it’s response.Easily integrates withaiohttp_swaggerifyto automatically document your endpoints with swagger.Validation errors are standardized and can be easily parsed by the clients of your service and also human-readable.DevelopingInstall requirement and launch tests:pip install -r requirements-dev.txt py.testCreditsThat package is influenced byTornado-JSONwritten by Hamza Faran Code to parse errors is written byRuslan KaralkinLicenseFree software: MIT licenseHistory1.0.0 (2016-12-12)Better documentation.Updated requirements.Out of alpha!0.1.0 (2016-10-12)First release on PyPI.
aiohttp-validator
aiohttp-validatoraiohttp simple pydantic http request validatorInstallationpipinstallaiohttp-validatorA Simple ExampleimportdatetimeasdtfromtypingimportAny,Dict,List,TypedDictfromuuidimportUUIDimportpydanticfromaiohttpimportwebimportaiohttp_validatorasvalidatorroutes=web.RouteTableDef()@routes.get('/posts')@validator.validated()asyncdefget_posts(request:web.Request,tags:List[str],limit:pydantic.conint(gt=0,le=100),offset:int=0):assertisinstance(tags,list)assertisinstance(limit,int)assertisinstance(offset,int)# your code here ...returnweb.Response(status=200)classRequestHeaders(TypedDict):requestId:intclassUser(pydantic.BaseModel):name:strsurname:strclassPost(pydantic.BaseModel):title:strtext:strtimestamp:floatauthor:Usertags:List[str]=pydantic.Field(default_factory=list)@routes.post('/posts/{section}/{date}')@validator.validated(config=pydantic.ConfigDict(extra='forbid'))asyncdefcreate_post(request:web.Request,body:Post,headers:RequestHeaders,section:str,date:dt.date):assertisinstance(body,Post)assertisinstance(headers,dict)assertisinstance(date,dt.date)assertisinstance(section,str)# your code here ...returnweb.Response(status=201)classAuthCookies(pydantic.BaseModel):tokenId:[email protected]('/users')@validator.validated(config=pydantic.ConfigDict(extra='forbid'))asyncdefcreate_user(request:web.Request,body:Dict[str,Any],headers:RequestHeaders,cookies:AuthCookies):assertisinstance(body,dict)assertisinstance(headers,RequestHeaders)assertisinstance(cookies,AuthCookies)# your code here ...returnweb.Response(status=201)app=web.Application()app.add_routes(routes)web.run_app(app,port=8080)If any path or query parameter name are clashes with body, headers or cookies argument for some reason the last can be renamed:@routes.post('/{cookies}')@validator.validated(cookies_argname='_cookies')asyncdefmethod(request:web.Request,body:Dict[str,Any],_cookies:AuthCookies,cookies:str):# your code here ...returnweb.Response(status=201)If any argname isNonethe corresponding request part will not be passed to the function and argname can be used as a path or query [email protected]('/{body}/{headers}')@validator.validated(body_argname=None,headers_argname=None,cookies_argname=None)asyncdefmethod(request:web.Request,body:str,headers:str,cookies:str=''):# your code here ...returnweb.Response(status=201)
aiohttp-webpack
Utility for load static in AioHttp web framework from Webpack with help of webpack-bundle-tracker JS plugin.Also this can be used with VueJS.Usage:settings.py:STATIC_URL='/static/'STATIC_PATH='./static/'WEBPACK_MANIFEST_PATH='./frontend/webpack_manifest.json'main.py:fromaiohttpimportwebimportaiohttp_jinja2importjinja2fromaiohttp_webpackimportWebpackManifestfromsettingsimport*@aiohttp_jinja2.template('index.html')asyncdefindex(request):context={'webpack':webpack_manifest.get_links(),}returncontextif__name__=='__main__':loop=asyncio.get_event_loop()app=web.Application()aiohttp_jinja2.setup(app,loader=jinja2.FileSystemLoader('./templates'))webpack_manifest=WebpackManifest(WEBPACK_MANIFEST_PATH,STATIC_URL,STATIC_PATH)app.add_routes([web.get('/',index),web.get('/static/{path:.*}',webpack_manifest.handle_static),])web.run_app(app)index.html:<html><head><metacharset="utf-8"><linkrel="stylesheet"href="/static/index.css">{# here you can use non webpack static too #} {{ webpack.css | safe }}</head><body><divid="app"></div>{# if you use VueJS #} {{ webpack.js | safe }}</body></html>
aiohttp-wrapper
UNKNOWN
aiohttp-ws
aiohttp_ws - aiohttp websockets==========================Nano-framework for working with websockets powered by aiohttp and redisTo start example app```bashmake venvsource activatepython -m example_app.app```Attention! Work In Progress==
aiohttp-wsconnhandler
aiohttp-wsconnhandlerThe package implements theWSConnectionHandlerclass that provides receive and send queues when handling WebSocket communication with aiohttp.Work-in-ProgressThe repository contains a module extracted from my other project and was refactored as a separate package.Currently, the plan is to rewrite it as a "general purpose" module that could be used in other WebSocket client and server apps.Usage ExamplesWebSocket Clientfrom aiohttp_wsconnhandler import WSConnectionHandler ...WebSocket Serverfrom aiohttp_wsconnhandler import WSConnectionHandler ...
aiohttp-wsgi
No description available on PyPI.
aiohttp-wsrpc
Remote Procedure call through WebSocket between browser and tornado.FeaturesInitiating call client function from server side.Calling the server method from the client.Transferring any exceptions from a client side to the server side and vise versa.The frontend-library are well done for usage without any modification.Fully asynchronous server-side functions.Thread-based websocket handler for writing fully-synchronous code (for synchronous database drivers etc.)Protected server-side methods (starts with underline never will be call from clients-side directly)Asynchronous connection protocol. Server or client can call multiple methods with unpredictable ordering of answers.InstallationInstall via pip:pip install wsrpc-tornadoInstall ujson if you want:pip install ujsonSimple usageAdd the backend sidefromtimeimporttime## If you want write async tornado code import it# from from wsrpc import WebSocketRoute, WebSocket, wsrpc_static## else you should use thread-base handlerfromwsrpcimportWebSocketRoute,WebSocketThreadedasWebSocket,wsrpc_statictornado.web.Application((# js static files will available as "/js/wsrpc.min.js".wsrpc_static(r'/js/(.*)'),# WebSocket handler. Client will connect here.(r"/ws/",WebSocket),# Serve other static files(r'/(.*)',tornado.web.StaticFileHandler,{'path':os.path.join(project_root,'static'),'default_filename':'index.html'}),))# This class should be call by client.# Connection object will be have the instance of this class when will call route-alias.classTestRoute(WebSocketRoute):# This method will be executed when client will call route-alias first time.definit(self,**kwargs):# the python __init__ must be return "self". This method might return anything.returnkwargsdefgetEpoch(self):# this method named by camelCase because the client can call it.returntime()# stateful request# this is the route alias TestRoute as "test1"WebSocket.ROUTES['test1']=TestRoute# stateless requestWebSocket.ROUTES['test2']=lambda*a,**kw:True# initialize ThreadPool. Needed when using WebSocketThreaded.WebSocket.init_pool()Add the frontend side<scripttype="text/javascript"src="/js/q.min.js"></script><scripttype="text/javascript"src="/js/wsrpc.min.js"></script><script>varurl=window.location.protocol==="https:"?"wss://":"ws://"+window.location.host+'/ws/';RPC=WSRPC(url,5000);RPC.addRoute('test',function(data){return"Test called";});RPC.connect();RPC.call('test1.getEpoch').then(function(data){console.log(data);},function(error){alert(error);}).done();RPC.call('test2').then(function(data){console.log(data);}).done();</script>ExampleExample running theredemo.
aiohttpx
aiohttpxA Python Wrapper for httpx that combines the httpx.AsyncClient with the httpx.Client to allow both async and sync requestsLatest Version:Installation# Install from pypipipinstall--upgradeaiohttpx# Install from Githubpipinstall--upgradegit+https://github.com/trisongz/aiohttpxUsageaiohttpxis a wrapper aroundhttpxthat provides a unifiedasync+syncinterface for making HTTP requests. This is useful for making HTTP requests in bothasyncandsynccodebases.Additionally, it includes aProxyClientthat can be used for scraping / high volume requests that would otherwise be blocked by the target server by using a rotating proxy pool throughAWS API Gateway.importasyncioimportaiohttpxasyncdeftest_requests():# Notice it utilizes async context manager but can use sync methods.asyncwithaiohttpx.Client()asclient:# Make an Async GET requestresponse=awaitclient.async_get("https://httpbin.org/get")print(response.json())# Make a Sync GET requestresponse=client.get("https://httpbin.org/get")print(response.json())# The same applies with the sync context managerwithaiohttpx.Client()asclient:# Make an Async GET requestresponse=awaitclient.async_get("https://httpbin.org/get")print(response.json())# Make a Sync GET requestresponse=client.get("https://httpbin.org/get")print(response.json())asyncdeftest_proxies():# Here we will test the ProxyClient# some magic/notes:# there is a wrapper for BeautifulSoup that is enabled for GET# requests. This can be triggered by passing `soup_enabled=True`# to the request method.# the ProxyClient will automatically terminate the api gateways upon# exit from the context manager in both sync and async.# however if no context manager is used, then the ProxyClient will# need to be manually terminated by calling# `client.shutdown()` | `await client.async_shutdown()`# You can choose to perserve the api gateways by passing# `reuse_gateways=True` to the ProxyClient constructor.# This is useful if you want to reuse the same api gateways# for multiple requests.# You can also increase the number of gateways per region to# increase the number of concurrent requests. This can be done by# passing `gateways_per_region=10` to the ProxyClient constructor.# by default the ProxyClient will use the `us-east-1` region.# You can change this by passing `regions=["us-west-2"]` or# `regions="us"` for all us regions to the ProxyClient constructor.base_url="https://www.google.com"asyncwithaiohttpx.ProxyClient(base_url=base_url)asclient:# Make an Async GET requestresponse=awaitclient.async_get("/search",params={"q":"httpx"},soup_enabled=True)print(response.soup)print(response.soup.title.text)# Make a Sync GET requestresponse=client.get("/search",params={"q":"httpx"},soup_enabled=True)print(response.soup)print(response.soup.title.text)# Upon exiting the context manager, the api gateways will be terminated.asyncdefrun_tests():awaitasyncio.gather(test_requests(),test_proxies())asyncio.run(run_tests())
aiohttp-xmlrpc
XML-RPC server and client implementation based on aiohttp. Using lxml and aiohttp.Client.Server examplefromaiohttpimportwebfromaiohttp_xmlrpcimporthandlerfromaiohttp_xmlrpc.handlerimportrenameclassXMLRPCExample(handler.XMLRPCView):@rename("nested.test")defrpc_test(self):returnNonedefrpc_args(self,*args):returnlen(args)defrpc_kwargs(self,**kwargs):returnlen(kwargs)defrpc_args_kwargs(self,*args,**kwargs):returnlen(args)+len(kwargs)@rename("nested.exception")defrpc_exception(self):raiseException("YEEEEEE!!!")app=web.Application()app.router.add_route('*','/',XMLRPCExample)if__name__=="__main__":web.run_app(app)Client exampleimportasynciofromaiohttp_xmlrpc.clientimportServerProxyloop=asyncio.get_event_loop()client=ServerProxy("http://127.0.0.1:8080/",loop=loop)asyncdefmain():# 'nested.test' method callprint(awaitclient.nested.test())# 'args' method callprint(awaitclient.args(1,2,3))client.close()if__name__=="__main__":loop.run_until_complete(main())
aiohttp-zlib-ng
aiohttp-zlib-ngSource Code:https://github.com/bdraco/aiohttp-zlib-ngEnable zlib_ng on aiohttpzlib is be a bottleneck for aiohttp, especially for websocket connections.aiohttp-zlib-ngreplaces usage ofzlibinaiohttpwithzlib-ngwhich is a drop-in faster replacement.Ifisalis available, this library will try to useisal, and will fallback to the slowerzlib_ngif it is not available.InstallationInstall this via pip (or your favorite package manager):pip install aiohttp-zlib-ngTo install the optionalisalspeed up:pip install aiohttp-zlib-ng[isal]UsageEnablezlib-ngsupport in aiohttp by callingenable_zlib_ngimportaiohttp_zlib_ngaiohttp_zlib_ng.enable_zlib_ng()aiohttp_zlib_ng.disable_zlib_ng()Contributors ✨Thanks goes to these wonderful people (emoji key):This project follows theall-contributorsspecification. Contributions of any kind welcome!CreditsThis package was created withCopierand thebrowniebroke/pypackage-templateproject template.
aiohttp-zora
This is a security placeholder package. If you want to claim this name for legitimate purposes, please contact us [email protected]@yandex-team.ru
aiohttp-zorro
This is a security placeholder package. If you want to claim this name for legitimate purposes, please contact us [email protected]@yandex-team.ru
aiohubot
aiohubotPorting from Hubot with asyncio enabled.
aiohubot-flowdock
No description available on PyPI.
aiohue
AiohueAsynchronous library to control Philips HueRequires Python 3.10+ and uses asyncio and aiohttp.For usage examples, see the examples folder.Hue Bridge versionThis library supports both the new style V2 API (only available on V2 bridges) and the old style V1 API. The biggest advantage of the V2 API is that it supports event based updates so polling is not required.Contribution guidelinesObject hierarchy and property/method names should match the Philips Hue API.
aiohue-BenoitAnastay
AiohueAsynchronous library to control Philips HueRequires Python 3.8+ and uses asyncio and aiohttp.For usage examples, see the examples folder.Hue Bridge versionThis library supports both the new style V2 API (only available on V2 bridges) and the old style V1 API. The biggest advantage of the V2 API is that it supports event based updates so polling is not required.Contribution guidelinesObject hierarchy and property/method names should match the Philips Hue API.
aiohuesyncbox
AIOHUESYNCBOXAsyncio package to communicate with Philips Hue Play HDMI Sync Box. This package is aimed at basic control of the box. Initial setup and configuration is assumed to done with the official Hue app.Installationpython3-mpipinstallaiohuesyncboxUsageInstantiate the HueSyncBox class and access the API.For more details on the API see the official API documentation onhttps://developers.meethue.comNote on changing bridgeChanging a bridge is a bit more involved than other calls. After callingbox.hue.set_bridge()the syncbox will start switching which takes a while (seems to take about 15 seconds). You will have to wait until the attributes match the expected endstate, but the status displayed on the API can be a bit confusing during the process.These are the status changes I see when switching from bridge A to bridge B.ID: Bridge A, IP: Bridge A, Status: connectedCallbox.hue.set_bridge()with info for bridge BID: Bridge B, IP: Bridge A, Status: connectingID: Bridge B, IP: Bridge B, Status: disconnectedID: Bridge B, IP: Bridge B, Status: connected or ID: Bridge B, IP: Bridge B, Status: invalidgroupExamplesThe examples below are available as a runnable script in the repository. There is also an example on usingzeroconffor device discovery.RegistrationfromaiohuesyncboximportHueSyncBox,InvalidState# host and id can be obtained through mDNS/zeroconf discovery# (or for testing look them up in the official Hue app)# The ID is the number that looks like C43212345678box=HueSyncBox(host,id)print("Press the button on the box for a few seconds until the light blinks green.")registration_info=Nonewhilenotregistration_info:try:registration_info=awaitbox.register("Your application","Your device")exceptInvalidState:# Indicates the button was not pressedpassawaitasyncio.sleep(1)# Save registration_info somewhere and use the 'access_token' when instantiating HueSyncBox next timeprint(registration_info)# Unregister by registration ID.# HueSyncBox needs to use the associated `access_token` to execute this request.awaitbox.unregister(registration_info['registration_id'])Basic usagefromaiohuesyncboximportHueSyncBox# host and id can be obtained through mDNS/zeroconf discovery# (or for testing look them up in the official Hue app)box=HueSyncBox(host,id,access_token_from_registration_info)# Call initialize before interacting with the boxawaitbox.initialize()print(box.device.name)print(box.execution.sync_active)print(box.execution.mode)# Turn the box on, start syncing with video mode on input 4awaitbox.execution.set_state(sync_active=True,mode="video",hdmi_source="input4")# Call update() to update with latest status from the boxawaitbox.execution.update()print(box.execution.sync_active)print(box.execution.mode)
aiohug
aiohugGoals:Unpack aiohttp (>=3.1) request to arguments with annotationsValidate handlers argumentsGenerate swagger specificationPosts:Meet the aiohugExamplesArguments from path and queryfromaiohttpimportwebfromaiohugimportRouteTableDefroutes=RouteTableDef()@routes.get("/hello/{name}/")asyncdefhello(name:fields.String(),greeting:fields.String()="Hello"):return{"msg":f"{greeting},{name}"}app=web.Application()app.add_routes(routes)if__name__=="__main__":web.run_app(app)There is norequestobject in handler signature anymore - only required arguments.Body with schemafromaiohttpimportwebfromaiohugimportRouteTableDefroutes=RouteTableDef()classPayloadSchema(Schema):count=fields.Int()@routes.get("/")asyncdefwith_body(body:PayloadSchema()):returnbodyapp=create_app()app.add_routes(routes)client=awaittest_client(app)resp=awaitclient.get("/",json={"count":"5","another":7})assertawaitresp.json()=={"count":5}Another [email protected]("/ping/")asyncdefping():return201,"pong"SwaggerUseaiohug_swaggerpackage.DecoratorsBecause of the wayaiohttprouting works all decorators to resource handlers must be appliedBEFOREaiohug’s routing decorator, i.e.defsome_decorator(func):@wraps(func)defwrapper(request,*args,**kwargs):# Some logic for decoratorreturnfunc(*args,**kwargs)[email protected]("/ping/")@some_decoratorasyncdefhello():return"pong"Moreover, make sure to decorate wrapper functions withwrapsdecorator fromfunctoolsmodule - otherwiseaiohugwon’t be able to access original handler’s arguments and annotations.Why aiohug?It’s justhugAPI implementation foraiohttpTODO:don’t pass default arguments
aiohug-swagger
aiohug_swaggerGoalProvide swagger annotation foraiohughandlers.
aiohutils
This library is not intended for direct public use. It is used as dependency of the following projects:https://github.com/5j9/tsetmchttps://github.com/5j9/fipiranhttps://github.com/5j9/iranetfhttps://github.com/5j9/aggregator
aiohwenergy
AIOHWENERGYAsyncio package to communicate with HomeWizard Energy devices This package is aimed at basic control of the device. Initial setup and configuration is assumed to done with the official HomeWizard Energy app.DisclaimerThis package is not developed, nor supported by HomeWizard.Installationpython3-mpipinstallaiohwenergyUsageInstantiate the HWEnergy class and access the API.For more details on the API see the official API documentation onhttps://homewizard-energy-api.readthedocs.ioExampleThe example below is available as a runnable script in the repository.fromaiohwenergyimportHomeWizardEnergy# Make contact with a energy devicedevice=HomeWizardEnergy(args.host)# Update device valueawaitdevice.update()# Use the dataprint(device.device.product_name)print(device.device.serial)print(device.data.wifi_ssid)# Close connectionawaitdevice.close()
aiohydroottawa
No description available on PyPI.
aiohypixel
aiohypixelA modern asynchronous Hypixel API wrapper with full API coverage written in Python.InstallationIt's very simple! Just usepip, like this:pip install aiohypixel.If you want to install the staging build, you can do so by runningpip install --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple aiohypixelinstead.How do you use this?If you like to read, you can check the documentationhere!If not, here's a crash course:TODOYou can also check theexamplesfolder for some more handsdown examples on how to use this library.TODORan into any issues?No problem! Just head out to theIssuesand see if there's any opened or closed issue regarding situation. If not, feel free to open one!You can also join the supportMatrixroom at#aiohypixel:matrix.org.⚠ This module is still under heavy development, and so there may occur major changes!Keep an eye on this page, as it will be updated when major progress is done :wink:
aiohypixel-py
No description available on PyPI.
aioice
What isaioice?aioiceis a library for Interactive Connectivity Establishment (RFC 5245) in Python. It is built on top ofasyncio, Python’s standard asynchronous I/O framework.Interactive Connectivity Establishment (ICE) is useful for applications that establish peer-to-peer UDP data streams, as it facilitates NAT traversal. Typical usecases include SIP and WebRTC.To learn more aboutaioicepleaseread the documentation.Example#!/usr/bin/env pythonimportasyncioimportaioiceasyncdefconnect_using_ice():connection=aioice.Connection(ice_controlling=True)# gather local candidatesawaitconnection.gather_candidates()# send your information to the remote party using your signaling methodsend_local_info(connection.local_candidates,connection.local_username,connection.local_password)# receive remote information using your signaling methodremote_candidates,remote_username,remote_password=get_remote_info()# perform ICE handshakeforcandidateinremote_candidates:awaitconnection.add_remote_candidate(candidate)awaitconnection.add_remote_candidate(None)connection.remote_username=remote_usernameconnection.remote_password=remote_passwordawaitconnection.connect()# send and receive dataawaitconnection.sendto(b'1234',1)data,component=awaitconnection.recvfrom()# close connectionawaitconnection.close()asyncio.get_event_loop().run_until_complete(connect_using_ice())Licenseaioiceis released under theBSD license.
aioice-no-netifaces
aioice-no-netifacesaioice-no-netifacesis a fork fromaioice, which does not require netifaces library.Why?Netifacesis no longer maintainedInstalling on Python3.10 requires Microsoft Visual C++ 14.0 or greater on Windows, as there are no pre built binariesThis fork gets the host IP address with pure Pythonworkaround, which does not require Microsoft Visual C++.Caveats:This library does not support ipv6 (which the originalaioicedoes support)Currently this library uses only the primary ipv4 address (aioicecan use all of the ip4 addresses)Licenseaioice-no-netifacesis released under the same BSD license as the originalaioicelibrary.DevelopmentInstall:pip install .[dev]Build:python setup.py bdist_wheelRelease:twine upload dist/*
aioicloud
aioicloudWork in progress...aioicloud:love_you_gesture:Please star this repository if you end up using the library. It will help me continue supporting this product.:pray:
aioidex
No description available on PyPI.
aioify
aioify (maintenance mode)Authors of aioify and module-wrapper decided to discontinue support of these libraries since the idea: "let's convert sync libraries to async ones" works only for some cases. Existing releases of libraries won't be removed, but don't expect any changes since today. Feel free to fork these libraries, however, we don't recommend using the automatic sync-to-async library conversion approach, as unreliable. Instead, it's better to run synchronous functions asynchronously usinghttps://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_in_executororhttps://anyio.readthedocs.io/en/stable/api.html#running-code-in-worker-threads.Old documentationMake every function async and await-able.Usagepip install aioifyFor example, makeos,shutiland user defined function await-able.#!/usr/bin/env python############ Warning ############# This code should be executed only on POSIX OS with at least 1 GiB free space in /tmp/ directory and RAM!fromaioifyimportaioifyimportosimportshutildefgenerate_big_file(filename,file_size):withopen(file=filename,mode='wb')asf:f.write(os.urandom(file_size))aiogenerate_big_file=aioify(obj=generate_big_file)aios=aioify(obj=os,name='aios')aioshutil=aioify(obj=shutil,name='aishutil')asyncdefmain():dir_path='/tmp/big-files/'awaitaios.makedirs(name=dir_path,exist_ok=True)filename=os.path.join(dir_path,'original')copy_filename=os.path.join(dir_path,'copy')file_size=1024*1024*1024awaitaiogenerate_big_file(filename=filename,file_size=file_size)awaitaioshutil.copy(src=filename,dst=copy_filename)awaitaioshutil.rmtree(path=dir_path)if__name__=='__main__':importasyncioasaioloop=aio.get_event_loop()loop.run_until_complete(main())
aioiliad
[![Build Status](https://travis-ci.org/eliseomartelli/AioIliad.svg?branch=master)](https://travis-ci.org/eliseomartelli/AioIliad)version number: 0.1.3 author: Eliseo MartelliOverviewA python package that can be installed with pip.Installation / UsageTo install use pip:$ pip install aioiliadOr clone the repo:$ git clonehttps://github.com/eliseomartelli/aioiliad.git$ python setup.py installFeel free to fork!
aioimap
aioimap: Asyncio IMAP clientReceive e-mails from an IMAP server asynchronously and trigger a callback with the message.Dependenciesaioimap requires:Python (>=3.7)aioimaplib (>=0.7.18)python-dotenvfastapi (>=0.61)uvicorn (>=0.12)UsageAssume a project structure as so:project | |--app.py |--.envapp.py:from aioimap import Message def callback(m: Message): print("Subject: {}".format(m.subject)) print("Sender: {}".format(m.sender)) # do some other fun stuffTerminal (without .env file):cd path/to/project python -m aioimap --host <EMAILSERVER> -u <EMAILID> -p <PWD> -a "app:callback"If you have a.envfile in the same directory:SERVER=<EMAILSERVER> EMAIL=<EMAILID> PASS=<PWD>ThenTerminal (with .env file):cd path/to/project python -m aioimap -a "app:callback"
aioimaplib
AboutThis library is inspired byimaplibandimaplib2from Piers Lauder, Nicolas Sebrecht, Sebastian Spaeth. Some utilities functions are taken from imaplib/imaplib2 thanks to them.The aim is to port the imaplib withasyncio, to benefit from the sleep or treat model.It runs with python 3.6, 3.7, 3.8, 3.9.Exampleimportasynciofromaioimaplibimportaioimaplibasyncdefcheck_mailbox(host,user,password):imap_client=aioimaplib.IMAP4_SSL(host=host)awaitimap_client.wait_hello_from_server()awaitimap_client.login(user,password)res,data=awaitimap_client.select()print('there is%smessages INBOX'%data[0])awaitimap_client.logout()if__name__=='__main__':loop=asyncio.get_event_loop()loop.run_until_complete(check_mailbox('my.imap.server','user','pass'))Bewarethat the IMAP4.close() function is an IMAP function that is closing the selected mailbox, thus passing from SELECTED state to AUTH state. Itdoes not closethe TCP connection. The way to close TCP connection properly is to logout.IDLE commandTheRFC2177is implemented, to be able to wait for new mail messages without using CPU. The responses are pushed in an async queue, and it is possible to read them in real time. To leave the IDLE mode, it is necessary to send a “DONE” command to the server.asyncdefwait_for_new_message(host,user,password):imap_client=aioimaplib.IMAP4_SSL(host=host)awaitimap_client.wait_hello_from_server()awaitimap_client.login(user,password)awaitimap_client.select()idle=awaitimap_client.idle_start(timeout=10)whileimap_client.has_pending_idle():msg=awaitimap_client.wait_server_push()print(msg)ifmsg==STOP_WAIT_SERVER_PUSH:imap_client.idle_done()awaitasyncio.wait_for(idle,1)awaitimap_client.logout()if__name__=='__main__':loop=asyncio.get_event_loop()loop.run_until_complete(wait_for_new_message('my.imap.server','user','pass'))Or in a more event based style (the IDLE command is closed at each message from server):asyncdefidle_loop(host,user,password):imap_client=aioimaplib.IMAP4_SSL(host=host,timeout=30)awaitimap_client.wait_hello_from_server()awaitimap_client.login(user,password)awaitimap_client.select()whileTrue:print((awaitimap_client.uid('fetch','1:*','FLAGS')))idle=awaitimap_client.idle_start(timeout=60)print((awaitimap_client.wait_server_push()))imap_client.idle_done()awaitasyncio.wait_for(idle,30)ThreadingThe IMAP4ClientProtocol class is not thread safe, it usesasyncio.Eventandasyncio.Conditionthat are not thread safe, and state change for pending commands is not locked.It is possible to use threads but each IMAP4ClientProtocol instance should run in the same thread:Each color rectangle is an IMAP4ClientProtocol instance piece of code executed by the thread asyncio loop until it reaches a yield, waiting on I/O.For example, it is possible to launch 4 mono-threaded mail-fetcher processes on a 4 cores server withsupervisor, and use a distribution function like len(email) % (process_num) or whatever to share equally a mail account list between the 4 processes.IMAP command concurrencyIMAP protocol allows to run some commands in parallel. Four rules are implemented to ensure responses consistency:if a sync command is running, the following requests (sync or async) must waitif an async command is running, same async commands (or with the same untagged response type) must waitasync commands can be executed in parallelsync command must wait pending async commands to finishLoggingAs said in the logginghowtothe logger is defined withlogger=logging.getLogger(__name__)Where name is ‘aioimaplib.aioimaplib’. You can set the logger parameters, either by python APIaioimaplib_logger=logging.getLogger('aioimaplib.aioimaplib')sh=logging.StreamHandler()sh.setLevel(logging.DEBUG)sh.setFormatter(logging.Formatter("%(asctime)s%(levelname)s[%(module)s:%(lineno)d]%(message)s"))aioimaplib_logger.addHandler(sh)Or loading config file (for example with logging.config.dictConfig(yaml.load(file))) with this piece of yaml fileloggers:...aioimaplib.aioimaplib:level:DEBUGhandlers:[syslog]propagate:no...Tested withdovecot 2.2.13 on debian Jessiegmail with imap and SSLoutlook with SSLyahoo with SSLfree.fr with SSLorange.fr with SSLmailden.net with SSLDevelopDevelopers are welcome! If you want to improve it, fix bugs, test it with other IMAP servers, give feedback, thank you for it.To develop, just runvirtualenv--python=python3.4venvsourcevenv/bin/activatepythonsetup.pydeveloppipinstall-rdev-requirements.txtnosetestsTo add an imaplib or imaplib2 command you can :add the function to the testing imapserver with a new imaplib or imaplib2 server test, i.e. test_imapserver_imaplib.py or test_imapserver_imaplib2.py respectively;then add the function to the aioimaplib doing almost the same test than above but the async way in test_aioimaplib.py.Not unit testedPREAUTHTODO23/25 IMAP4rev1 commands are implemented from the mainrfc3501. ‘STARTTLS’ and ‘AUTHENTICATE’ are still missing.‘COMPRESS’ fromrfc4978‘SETACL’ ‘DELETEACL’ ‘GETACL’ ‘MYRIGHTS’ ‘LISTRIGHTS’ from ACLrfc4314‘GETQUOTA’: ‘GETQUOTAROOT’: ‘SETQUOTA’ from quotarfc2087‘SORT’ and ‘THREAD’ from therfc5256‘ID’ from therfc2971‘NAMESPACE’ fromrfc2342‘CATENATE’ fromrfc4469tests with other serversIf it goes wrongSometimes you break things and you don’t understand what’s going on (I always do). For this library I have two related tools:ngrep on the imap test port:sudongrep-dloport12345activate debug logs changing INFO to DEBUG at the top of the mock server and the aioimaplibChangesV1.0.0After 5 years and 420 usages let’s switch to 1.0.0.[aiolib] adds python 3.10 (but python 3.10 is failing on downloading interpretor)[aiolib] adds getquotaroot commandV0.9.0Please note that this release changes the API : response lines are now all of bytes type (and not in string).[aiolib] compatible with python 3.9[aiolib] avoid having distinct types (str/bytes) in response linesV0.8.0[aiolib] adds type hints[aiolib] use async/await syntax (remove support for python 3.4)[aiolib] fixes issue #30 on idle race condition[aiolib] fixes the allowed versionV0.7.18[aiolib] fix the fix python 3.7 don’t use the 7.17V0.7.17[aiolib] fix loading issue when importing aioimaplib with python 3.7V0.7.16merge from darkrain42[aiolib] fix interaction between idle loop and server keepalive[aiolib] fix cert verification on debian buster[test] fix imapserver literal handling on Python 3.6.5+[test] tests: Replace calls to asyncio.async with asyncio.ensure_futureV0.7.15[aiolib] replace ‘async’ by is_async for python 3.7 cf #42[aiolib] Add ID command[aiolib] Add NAMESPACE commandV0.7.14[fix] when there is ::1 as localhost in /etc/hosts in a docker container[test] tests with SSL[aiolib] quote password properly in IMAP dialogV0.7.13[aiolib] adds a connection lost callback[test] imapserver : added APPENDUID response for APPEND cmd[test][fix] imapserver append should add to the connected user mb[test] imapserver : more accurate building of message headers (using python email module)V0.7.12[aiolib] fix issue #24[aiolib] fix issue #27V0.7.11[aiolib] adds rfc6851 moveV0.7.10[aiolib] adds IMAP4.has_capability functionV0.7.9[aiolib] adds uncomplete fetch command with uncomplete line[aiolib] adds uncomplete fetch command BODY without literal[aiolib] adds rfc4315 uidplus : expunge with uids[test] handles uidset better in imap server[test] refactor testing IMAP4ClientProtocol.data_received instead of _handle_responsesV0.7.8[aiolib] idle : added an idle_waiter for an event based idle loopV0.7.7[aiolib] do not filter exists line for examine command[aiolib] idle : wait for the end of data frame before pushing into the queue[test] imapserver enhancements : accepts sequence sets/returns UID when fetch by uidV0.7.6[aiolib] idle : added loop methodsV0.7.5[aiolib][fix] it’s up to the user to send idle DONEV0.7.4[aiolib] timeout for idle of 29 minutes + timeout of wait_server_push doesn’t raise TimeoutExceptionV0.7.3[aiolib] added timeout for wait_server_push of 29 minutes[aiolib] Remove imap’s Continuation from server when connection is idled. Provide imapserver.wait_state to wait for idle in tests[test][refactor] Replace WithIMapServer inheritance by mixin combinations between ClockTestCase/TestCase and WithIMapServer[test] Allow to send a html email[fix] handling untagged responses with noop async commandV0.7.2[fix] bug when incomplete literal occured before a tagged status line[tests] imapserver search with uid range[tests] better fetch request handling[log] Limit partials’ log to 100 characters[build] Add tests’ requires in setup.pyV0.7.1[refactor] adding incomplete line before calling _handle_responsesV0.7.0[fix] generalization of literal treatmentdo not filter exists line for ‘select’ command (breaks the API). To retrieve unread mails with select, useaioimaplib.extract_exists((yield from imap_client.select()) instead of ‘yield from imap_client.select()[0]’V0.6.2[fix] added ‘$’ and ‘;’ for fetch message with litteral regexpV0.6.1[fix] issue #17 “Error fetch uid param”V0.6.0moved timeout handling at the Command level and not IMAP4 client for fetch as proposed by @cyberlis inhttps://github.com/bamthomas/aioimaplib/pull/16V0.5.20fix : issue #15https://github.com/bamthomas/aioimaplib/issues/15This will break the API for FETCH with emails BODY : now the first line is the server FETCH server response line. The messages are between 1 and end of Response.lines list.V0.5.19tests : [revert] add_charset to much intrusive when running a test suiteV0.5.18tests : body text was not base64 encoded even if the header said soV0.5.17tests : mail_from parameter from Mail.create should handlemail@host, <mail@host>, Name <mail@host>V0.5.16tests : added better encoding handling and message building in Mail.createV0.5.15tests : added message_id as Mail.create parameter for testingV0.5.14tests : extract Mail.create_binary for convenienceV0.5.13fix : trailing whitespace bug causing “BAD Could not parse command” using gmail/IDLEfix : stop adding a space for the prefix ‘UID ‘ -> ‘UID’V0.5.12fix : issue #12 Not properly buffering newlines for incomplete linesfix : imapserver with status of an inexistant mailboxfix : remove offset problem with strip() modifying length of read datafix : remove ‘unknown data received’ logs if line is emptyV0.5.11remove hard coded logging configdoc : added logging settingsV0.5.10added rfc5032 ‘within’ function to server and tests for aiolib (it is only YOUNGER/OLDER arguments)V0.5.9pushing continuation in the queue when idledV0.5.8added a stop waiting server push function to interupt yield from queue.getV0.5.7server send still here every IDLE_STILL_HERE_PERIOD_SECONDS to client when idlefix when server was lauched with main, loop is already runningV0.5.6fix docfix imapserver main (needs a asyncio.loop.run_forever())V0.5.5fix issues with coroutines in uid commanddocumentationremove PARTIAL, PROXYAUTH, SETANNOTATION and GETANNOTATION commandsV0.5.4refactor: treating response as we read the imap server responses for a better readingdocremoving tests from packagepublish on pypiadded coverallV0.5.3fix aioimaplib bug when receiving chunked fetch datado not abort when receiving unsollicited data from serverV0.5.2build CI environmentlicense GPL v3.0V0.5.1added APPEND commandfix usernames can have ‘@’ for mockimapserverserver can handle SEARCH with CHARSET opt parameter (but ignores it)V0.5added 11 new imap commandsadded imap command synchronizingrefactordocumentationV0.1init project with mockimapserverproject files11 imap commands
aioimaplib-hakiergrzonzo
AboutThis library is inspired byimaplibandimaplib2from Piers Lauder, Nicolas Sebrecht, Sebastian Spaeth. Some utilities functions are taken from imaplib/imaplib2 thanks to them.The aim is to port the imaplib withasyncio, to benefit from the sleep or treat model.It runs with python 3.6, 3.7, 3.8, 3.9.Exampleimportasynciofromaioimaplibimportaioimaplibasyncdefcheck_mailbox(host,user,password):imap_client=aioimaplib.IMAP4_SSL(host=host)awaitimap_client.wait_hello_from_server()awaitimap_client.login(user,password)res,data=awaitimap_client.select()print('there is%smessages INBOX'%data[0])awaitimap_client.logout()if__name__=='__main__':loop=asyncio.get_event_loop()loop.run_until_complete(check_mailbox('my.imap.server','user','pass'))Bewarethat the IMAP4.close() function is an IMAP function that is closing the selected mailbox, thus passing from SELECTED state to AUTH state. Itdoes not closethe TCP connection. The way to close TCP connection properly is to logout.IDLE commandTheRFC2177is implemented, to be able to wait for new mail messages without using CPU. The responses are pushed in an async queue, and it is possible to read them in real time. To leave the IDLE mode, it is necessary to send a “DONE” command to the server.asyncdefwait_for_new_message(host,user,password):imap_client=aioimaplib.IMAP4_SSL(host=host)awaitimap_client.wait_hello_from_server()awaitimap_client.login(user,password)awaitimap_client.select()idle=awaitimap_client.idle_start(timeout=10)whileimap_client.has_pending_idle():msg=awaitimap_client.wait_server_push()print(msg)ifmsg==STOP_WAIT_SERVER_PUSH:imap_client.idle_done()awaitasyncio.wait_for(idle,1)awaitimap_client.logout()if__name__=='__main__':loop=asyncio.get_event_loop()loop.run_until_complete(wait_for_new_message('my.imap.server','user','pass'))Or in a more event based style (the IDLE command is closed at each message from server):asyncdefidle_loop(host,user,password):imap_client=aioimaplib.IMAP4_SSL(host=host,timeout=30)awaitimap_client.wait_hello_from_server()awaitimap_client.login(user,password)awaitimap_client.select()whileTrue:print((awaitimap_client.uid('fetch','1:*','FLAGS')))idle=awaitimap_client.idle_start(timeout=60)print((awaitimap_client.wait_server_push()))imap_client.idle_done()awaitasyncio.wait_for(idle,30)ThreadingThe IMAP4ClientProtocol class is not thread safe, it usesasyncio.Eventandasyncio.Conditionthat are not thread safe, and state change for pending commands is not locked.It is possible to use threads but each IMAP4ClientProtocol instance should run in the same thread:Each color rectangle is an IMAP4ClientProtocol instance piece of code executed by the thread asyncio loop until it reaches a yield, waiting on I/O.For example, it is possible to launch 4 mono-threaded mail-fetcher processes on a 4 cores server withsupervisor, and use a distribution function like len(email) % (process_num) or whatever to share equally a mail account list between the 4 processes.IMAP command concurrencyIMAP protocol allows to run some commands in parallel. Four rules are implemented to ensure responses consistency:if a sync command is running, the following requests (sync or async) must waitif an async command is running, same async commands (or with the same untagged response type) must waitasync commands can be executed in parallelsync command must wait pending async commands to finishLoggingAs said in the logginghowtothe logger is defined withlogger=logging.getLogger(__name__)Where name is ‘aioimaplib.aioimaplib’. You can set the logger parameters, either by python APIaioimaplib_logger=logging.getLogger('aioimaplib.aioimaplib')sh=logging.StreamHandler()sh.setLevel(logging.DEBUG)sh.setFormatter(logging.Formatter("%(asctime)s%(levelname)s[%(module)s:%(lineno)d]%(message)s"))aioimaplib_logger.addHandler(sh)Or loading config file (for example with logging.config.dictConfig(yaml.load(file))) with this piece of yaml fileloggers:...aioimaplib.aioimaplib:level:DEBUGhandlers:[syslog]propagate:no...Tested withdovecot 2.2.13 on debian Jessiegmail with imap and SSLoutlook with SSLyahoo with SSLfree.fr with SSLorange.fr with SSLmailden.net with SSLDevelopDevelopers are welcome! If you want to improve it, fix bugs, test it with other IMAP servers, give feedback, thank you for it.To develop, just runvirtualenv--python=python3.4venvsourcevenv/bin/activatepythonsetup.pydeveloppipinstall-rdev-requirements.txtnosetestsTo add an imaplib or imaplib2 command you can :add the function to the testing imapserver with a new imaplib or imaplib2 server test, i.e. test_imapserver_imaplib.py or test_imapserver_imaplib2.py respectively;then add the function to the aioimaplib doing almost the same test than above but the async way in test_aioimaplib.py.Not unit testedPREAUTHTODO23/25 IMAP4rev1 commands are implemented from the mainrfc3501. ‘STARTTLS’ and ‘AUTHENTICATE’ are still missing.‘COMPRESS’ fromrfc4978‘SETACL’ ‘DELETEACL’ ‘GETACL’ ‘MYRIGHTS’ ‘LISTRIGHTS’ from ACLrfc4314‘GETQUOTA’: ‘GETQUOTAROOT’: ‘SETQUOTA’ from quotarfc2087‘SORT’ and ‘THREAD’ from therfc5256‘ID’ from therfc2971‘NAMESPACE’ fromrfc2342‘CATENATE’ fromrfc4469tests with other serversIf it goes wrongSometimes you break things and you don’t understand what’s going on (I always do). For this library I have two related tools:ngrep on the imap test port:sudongrep-dloport12345activate debug logs changing INFO to DEBUG at the top of the mock server and the aioimaplibChangesV1.0.0After 5 years and 420 usages let’s switch to 1.0.0.[aiolib] adds python 3.10 (but python 3.10 is failing on downloading interpretor)[aiolib] adds getquotaroot commandV0.9.0Please note that this release changes the API : response lines are now all of bytes type (and not in string).[aiolib] compatible with python 3.9[aiolib] avoid having distinct types (str/bytes) in response linesV0.8.0[aiolib] adds type hints[aiolib] use async/await syntax (remove support for python 3.4)[aiolib] fixes issue #30 on idle race condition[aiolib] fixes the allowed versionV0.7.18[aiolib] fix the fix python 3.7 don’t use the 7.17V0.7.17[aiolib] fix loading issue when importing aioimaplib with python 3.7V0.7.16merge from darkrain42[aiolib] fix interaction between idle loop and server keepalive[aiolib] fix cert verification on debian buster[test] fix imapserver literal handling on Python 3.6.5+[test] tests: Replace calls to asyncio.async with asyncio.ensure_futureV0.7.15[aiolib] replace ‘async’ by is_async for python 3.7 cf #42[aiolib] Add ID command[aiolib] Add NAMESPACE commandV0.7.14[fix] when there is ::1 as localhost in /etc/hosts in a docker container[test] tests with SSL[aiolib] quote password properly in IMAP dialogV0.7.13[aiolib] adds a connection lost callback[test] imapserver : added APPENDUID response for APPEND cmd[test][fix] imapserver append should add to the connected user mb[test] imapserver : more accurate building of message headers (using python email module)V0.7.12[aiolib] fix issue #24[aiolib] fix issue #27V0.7.11[aiolib] adds rfc6851 moveV0.7.10[aiolib] adds IMAP4.has_capability functionV0.7.9[aiolib] adds uncomplete fetch command with uncomplete line[aiolib] adds uncomplete fetch command BODY without literal[aiolib] adds rfc4315 uidplus : expunge with uids[test] handles uidset better in imap server[test] refactor testing IMAP4ClientProtocol.data_received instead of _handle_responsesV0.7.8[aiolib] idle : added an idle_waiter for an event based idle loopV0.7.7[aiolib] do not filter exists line for examine command[aiolib] idle : wait for the end of data frame before pushing into the queue[test] imapserver enhancements : accepts sequence sets/returns UID when fetch by uidV0.7.6[aiolib] idle : added loop methodsV0.7.5[aiolib][fix] it’s up to the user to send idle DONEV0.7.4[aiolib] timeout for idle of 29 minutes + timeout of wait_server_push doesn’t raise TimeoutExceptionV0.7.3[aiolib] added timeout for wait_server_push of 29 minutes[aiolib] Remove imap’s Continuation from server when connection is idled. Provide imapserver.wait_state to wait for idle in tests[test][refactor] Replace WithIMapServer inheritance by mixin combinations between ClockTestCase/TestCase and WithIMapServer[test] Allow to send a html email[fix] handling untagged responses with noop async commandV0.7.2[fix] bug when incomplete literal occured before a tagged status line[tests] imapserver search with uid range[tests] better fetch request handling[log] Limit partials’ log to 100 characters[build] Add tests’ requires in setup.pyV0.7.1[refactor] adding incomplete line before calling _handle_responsesV0.7.0[fix] generalization of literal treatmentdo not filter exists line for ‘select’ command (breaks the API). To retrieve unread mails with select, useaioimaplib.extract_exists((yield from imap_client.select()) instead of ‘yield from imap_client.select()[0]’V0.6.2[fix] added ‘$’ and ‘;’ for fetch message with litteral regexpV0.6.1[fix] issue #17 “Error fetch uid param”V0.6.0moved timeout handling at the Command level and not IMAP4 client for fetch as proposed by @cyberlis inhttps://github.com/bamthomas/aioimaplib/pull/16V0.5.20fix : issue #15https://github.com/bamthomas/aioimaplib/issues/15This will break the API for FETCH with emails BODY : now the first line is the server FETCH server response line. The messages are between 1 and end of Response.lines list.V0.5.19tests : [revert] add_charset to much intrusive when running a test suiteV0.5.18tests : body text was not base64 encoded even if the header said soV0.5.17tests : mail_from parameter from Mail.create should handlemail@host, <mail@host>, Name <mail@host>V0.5.16tests : added better encoding handling and message building in Mail.createV0.5.15tests : added message_id as Mail.create parameter for testingV0.5.14tests : extract Mail.create_binary for convenienceV0.5.13fix : trailing whitespace bug causing “BAD Could not parse command” using gmail/IDLEfix : stop adding a space for the prefix ‘UID ‘ -> ‘UID’V0.5.12fix : issue #12 Not properly buffering newlines for incomplete linesfix : imapserver with status of an inexistant mailboxfix : remove offset problem with strip() modifying length of read datafix : remove ‘unknown data received’ logs if line is emptyV0.5.11remove hard coded logging configdoc : added logging settingsV0.5.10added rfc5032 ‘within’ function to server and tests for aiolib (it is only YOUNGER/OLDER arguments)V0.5.9pushing continuation in the queue when idledV0.5.8added a stop waiting server push function to interupt yield from queue.getV0.5.7server send still here every IDLE_STILL_HERE_PERIOD_SECONDS to client when idlefix when server was lauched with main, loop is already runningV0.5.6fix docfix imapserver main (needs a asyncio.loop.run_forever())V0.5.5fix issues with coroutines in uid commanddocumentationremove PARTIAL, PROXYAUTH, SETANNOTATION and GETANNOTATION commandsV0.5.4refactor: treating response as we read the imap server responses for a better readingdocremoving tests from packagepublish on pypiadded coverallV0.5.3fix aioimaplib bug when receiving chunked fetch datado not abort when receiving unsollicited data from serverV0.5.2build CI environmentlicense GPL v3.0V0.5.1added APPEND commandfix usernames can have ‘@’ for mockimapserverserver can handle SEARCH with CHARSET opt parameter (but ignores it)V0.5added 11 new imap commandsadded imap command synchronizingrefactordocumentationV0.1init project with mockimapserverproject files11 imap commands
aioimdb
aioimdb (IMDb + Python 3.6 + Asyncio)Python asyncio IMDb client using the IMDb JSON web service made available for their iOS app. This version requires Python 3.6 or later. It is based off of thesynchronous version by Richard O'Dwyer.API TerminologyTitlethis can be a movie, tv show, video, documentary etc.Namethis can be a credit, cast member, any person generally.InstallationTo install aioimdb, simply:pipinstallaioimdbHow To UseInitialise The ClientfromaioimdbimportImdbasyncwithImdb()asimdbresult=awaitimdb.<methodcall># <-- see Available Methods belowExample:fromaioimdbimportImdbasyncwithImdb()asimdbresult=awaitimdb.get_title('tt0111161')Available MethodsNOTE: For each client method, if the resource cannot be found they will raiseLookupError, if there is an API error thenImdbAPIErrorwill raise.ExampleDescriptionawait get_title('tt0111161')Returns a dict containing title informationawait search_for_title("The Dark Knight")Returns a dict of resultsawait search_for_name("Christian Bale)Returns a dict of resultsawait title_exits('tt0111161')Returns True if exists otherwise Falseawait get_title_genres('tt0303461')Returns a dict containing title genres informationawait get_title_credits('tt0303461')Returns a dict containing title credits informationawait get_title_quotes('tt0303461')Returns a dict containing title quotes informationawait get_title_ratings('tt0303461')Returns a dict containing title ratings informationawait get_title_connections('tt0303461')Returns a dict containing title connections informationawait get_title_similarities('tt0303461')Returns a dict containing title similarities informationawait get_title_videos('tt0303461')Returns a dict containing title videos informationawait get_title_news('tt0303461')Returns a dict containing newsawait get_title_trivia('tt0303461')Returns a dict containing triviaawait get_title_soundtracks('tt0303461')Returns a dict containing soundtracks informationawait get_title_goofs('tt0303461')Returns a dict containing "goofs" and teaser informationawait get_title_technical('tt0303461')Returns a dict containing technical informationawait get_title_companies('tt0303461')Returns a dict containing information about companies related to titleawait get_title_episodes('tt0303461')Returns a dict containing season and episodes informationawait get_title_episodes_detailed(imdb_id='tt0303461', season=1)Returns a dict containing detailed season episodes informationawait get_title_top_crew('tt0303461')Returns a dict containing detailed information about title's top crew (ie: directors, writters, etc.)await get_title_plot('tt0111161')Returns a dict containing title plot informationawait get_title_plot_synopsis('tt0111161')Returns a dict containing title plot synopsis informationawait get_title_awards('tt0111161')Returns a dict containing title plot informationawait get_title_releases('tt0111161')Returns a dict containing releases informationawait get_title_versions('tt0111161')Returns a dict containing versions information (meaning different versions of this title for different regions, or different versions for DVD vs Cinema)await get_title_user_reviews('tt0111161')Returns a dict containing user review informationawait get_title_metacritic_reviews('tt0111161')Returns a dict containing metacritic review informationawait get_title_images('tt0111161')Returns a dict containing title images informationawait get_name('nm0000151')Returns a dict containing person/name informationawait get_name_filmography('nm0000151')Returns a dict containing person/name filmography informationawait get_name_images('nm0000032')Returns a dict containing person/name images informationawait get_name_videos('nm0000032')Returns a dict containing person/name videos informationvalidate_imdb_id('tt0111161')RaisesValueErrorif not validawait get_popular_titles()Returns a dict containing popular titles informationawait get_popular_shows()Returns a dict containing popular tv showsawait get_popular_movies()Returns a dict containing popular moviesRequirements1. Python 3.6 or later 2. See requirements.txtRunning The Testspipinstall-rtest_requirements.txt py.testtests
aioimgbb
No description available on PyPI.
aioimgur
No description available on PyPI.
aioimport
aioimportAsynchronous module import for asyncioGetting StartedInstallingInstall fromPyPIusing:pip install aioimportThe problemSome naughty modules have long running operations during importNaive solutionFirst thing that comes to mind is make import local:asyncdefmy_work()->None:importnaughty# will block event loopIt reduces time your program takes to start (or library to import), but it is still blocking your event loop.Usageimportaioimportasyncdefmy_work()->None:awaitaioimport.import_module("naughty")# will asynchronously import moduleimportnaughty# will be instantaneous since `naughty` is already in `sys.modules`awaitaioimport.reload(naughty)# and you can asynchronously reload modules tooHow it worksModule import is done in asyncio default executor.Be aware of the fact that GIL still exists and technically import is done concurrently rather than in parallel with your code.LicenseThis project is licensed under the MIT License - see theLICENSEfile for details
aioinflux
Asynchronous Python client forInfluxDB. Built on top ofaiohttpandasyncio. Aioinflux is an alternative to the official InfluxDB Python client.Aioinflux supports interacting with InfluxDB in a non-blocking way by usingaiohttp. It also supports writing and querying ofPandasdataframes, among other handy functionality.Please refer to thedocumentationfor more details.InstallationPython 3.6+ is required. You also need to have access to a running instance of InfluxDB.pipinstallaioinfluxQuick startThis sums most of what you can do withaioinflux:importasynciofromaioinfluximportInfluxDBClientpoint={'time':'2009-11-10T23:00:00Z','measurement':'cpu_load_short','tags':{'host':'server01','region':'us-west'},'fields':{'value':0.64}}asyncdefmain():asyncwithInfluxDBClient(db='testdb')asclient:awaitclient.create_database(db='testdb')awaitclient.write(point)resp=awaitclient.query('SELECT value FROM cpu_load_short')print(resp)asyncio.get_event_loop().run_until_complete(main())See thedocumentationfor more detailed usage.
aioinflux3
aio-influxinfluxdb python client working with asyncioInstallpip install aioinflux3Initialize asynchronous clientfrom aioinflux3 import InfluxClient, Measurement, Query, Field async with InfluxClient(host=..., port=..., org=..., token=...) as client: # write code hereWrite dataasync with InfluxClient(host=..., port=..., org=..., token=...) as client: await client.write(Measurement.new('measurement', timestamp, tag=[Field(key=tag key, val=tag value), ], fields=[ Field(key=filed key, val=field value), ] ) )Make Queryasync with InfluxClient(host=..., port=..., org=..., token=...) as client: query = Query(bucket name, measurement=measurement name) .range(start='-4h', end='-1s') .filter('_field name', tag name= tag value) .window(every='5s', fn='func name') # func name in next list .do_yield(name='func name') # name if optional resp = await client.query(query) # return json table resp = await client.query(query, numpy=True) # return a numpy Structured Arrayfunc list:meanmedianmaxminsumderivativedistinctcountincreaseskewspreadstddevfirstlastuniquesortnonnegative derivative1NoticeThis project started for own useage. My goal is make it simple and easy to use, it's not full functional for InfluxDB v2 API. If you like it, Pls star, and tell me yourneeds in issuse, I will try my best to make it happen.
aioinfluxdb
aioinfluxdbThe Python client for InfluxDB v2 supports asyncio.This is early-stage projectWhy aioinfluxdb?The official clientdoes not supports asyncio that can get significant performance. andaioinfluxdoes not supports InfluxDB v2.Feature tableFeatureSub category✅ / ⚠ / 🚧QueryQuery Data✅QueryAnalyzer Flux Query🚧QueryGenerate AST from Query🚧QueryRetrieve query suggestions🚧QueryRetrieve query suggestionsfor a branching suggestion🚧Write✅Buckets⚠Dashboards🚧Tasks🚧Resources🚧Authorizations🚧Organizations⚠Users🚧Health🚧Ping✅Ready🚧Routes🚧Backup🚧Cells🚧Checks🚧DBRPs🚧Delete🚧Labels🚧NotificationEndpoints🚧NotificationRules🚧Restore🚧Rules🚧Scraper Targets🚧Secrets🚧Setup🚧Signin🚧Signout🚧Sources🚧Telegraf Plugins🚧Telegrafs🚧Templates🚧Variables🚧Views🚧This project borrows some de/serialization code frominfluxdb-client.
aioinject
Async-first dependency injection library based on python type hints, seedocumentationInstallationInstall using pippip install aioinject
aioinsta
aioINSTAStill in developmentAsynchronous wrapper of instagram PRIVATE APIimportasynciofromaioinstaimportClientsettings={"your_settings":"xxxx"}client=Client()asyncdefmain():awaitclient.login("username","password")data=awaitclient.media_info(client.media_pk_from_url("https://www.instagram.com/p/CrfF1nhslH4"))print(data)asyncio.run(main())
aioinstagrapi
Fast and effective asynchronous Instagram Private API wrapper (public+private requests and challenge resolver).Uses the most recent version of the API from Instagram.Async wrapper aroundhttps://githib.com/adw0rd/instagrapiFeatures:Performs Public API (web, anonymous) or Private API (mobile app, authorized) requests depending on the situation (to avoid Instagram limits)Challenge Resolver have Email (as well as recipes for automating receive a code from email) and SMS handlersSupport upload a Photo, Video, IGTV, Clips (Reels), Albums and StoriesSupport work with User, Media, Insights, Collections, Location (Place), Hashtag and Direct objectsLike, Follow, Edit account (Bio) and much more elseInsights by account, posts and storiesBuild stories with custom background, font animation, swipe up link and mention usersIn the next release, account registration and captcha passing will appear
aiointeractions
An async Discord HTTP Interactions wrapper fordiscord.pybuilt withaiohttp.Documentationhttps://aiointeractions.readthedocs.io/Installingaiointeractionsrequires Python 3.8 or newer.pip install aiointeractionsExampleimportasyncioimportdiscordimportaiointeractionsintents=discord.Intents.none()# intents are not required because there is no gateway connectionclient=discord.Client(intents=intents)tree=discord.app_commands.CommandTree(client)app=aiointeractions.InteractionsApp(client)discord.utils.setup_logging(root=True)@tree.command()asyncdefping(interaction:discord.Interaction)->None:awaitinteraction.response.send_message('Pong!')app.run('bot token')Fork SupportWhile some forks may be compatible, discord.py forks will not be supported.
aio-iotccsdk
Python SDK for AI Vision Developer KitThis library allows developer to control theQualcomm Visual Intelligence Platformfor hardware acceleration fo AI models to deliver superior inferencing performance.The library enables developers to easily combine the Vision AI DevKit withAzure IoT Edgeto deploy vision ML models and custom business logic from the cloud to the edge.UsageThe main class for controlling the camera is the CameraClient:fromiotccsdkimportCameraClientcamera_client=CameraClient.connect(username="admin",password="admin",ip_address=<cameraipaddress>)camera_client.configure_preview(resolution="1080P",encode="AVC/H.264",bitrate="1.5Mbps",display_out=1)camera_client.set_preview_state("on")rtsp_stream_address=camera_client.preview_urlFor more complete code examples see the samples folder in the project GitHub repositoryhttps://github.com/microsoft/vision-ai-developer-kit.Release History0.1.4 (2019-06-19)Update project metadata and readme0.1.0 (2019-06-19)Project creation
aioiotprov
aioiotprovA library/utility to provision IoT devicesThis is early day. Currently it can provision TP-Link smartplugs, Broadlink IR blasters, Sonoff switches running the Tasmota firmware, Shelly devices and E-Trix power monitors, Xiaomi Yeelights (Possibly other Xiaomi too)This uses nmcli or wpa_cli to control and configure WIFI access. This means this will work only with Linux, and then again not all. It is working on a RaspberryPi running Debian Stretch (No NetworkManager) and works on a laptop ruunning Ubuntu 18.10 to 20.04When using nmcli, it is possible to use a connected WiFi adapter, this has not yet been tested with wpa_cliInstallationWe are on PyPi sopip3 install aioiotprovRunningYou can just run it by doingpython3 -m aioiotprov "My SSID" "My Secret Key"If you want to set user, password and for sonoff, MQTT, do something likepython3 -m aioiotprov -u user -p password "My SSID" "My Secret Key" \ -o "sonoff::mqtt==on||user=mqttuser||password=mqttpass||host=somehost||port=1883||client=DVES_XXXXXX||topic=sonoff-XXXXXX||full topic=blabla/%prefix%/%topic%/"For Shellies,python3 -m aioiotprov -u user -p password "My SSID" "My Secret Key" \ -o "shelly::mqtt==on||user==mqttuser||password==mqttpass||host==somehost||port==1883"For Tasmota,python3 -m aioiotprov -d -u user -p passwd -o 'tasmota::mqtt==on||template=={"NAME":"Sonoff T1 3CH","GPIO":[17,255,255,255,23,22,18,19,21,56,0,0,0],"FLAG":0,"BASE":30}||host==somehost||user==mqttuser||password==mqttpasswd' -- SSID KEYSetting option will only works with plugins that can handle those. Use '::' after name of the plugin. Use '==' to set value and use '||' to separate optionsPluginsbroadlinkThis is a plugin to provisionBroadlinkdevices, like the A1 sensor or the RM4 Mini IR blaster.The device cannot be secured (no user/password setting) nor is any option available for this plugin.e-trixThis is a plugin to provisionE-Trixelectrix metering devices.The device cannot be secured (no user/password setting) nor is any option available for this plugin.shellyThis is a plugin to provisionShellydevices.If you set the user and the password, the device will be secured with those.The plugin supports the following options:mqtt: on or off Use MQTT or not host: mqtt host URI (with port if needed) (only if mqtt=='on' user: mqtt username password: mqtt passwordtasmotaThis is a plugin to provision devices running theTasmotasoftware.If you set the user and the password, the device will be secured with those.The plugin supports the following options:module: The index of the module to use (e.g. 29 is for Sonoff T1 2CH) template: A device template. See the Tasmota documentation for details. mqtt: on or off Use MQTT or not host: mqtt host (only if mqtt=='on' user: mqtt username password: mqtt password port: mqtt port client: see tasmota documentation for details topic: define the device unique id for MQTT full topic: : full topic e.g. mystuff/%prefix%/%topic% For 'client', 'topic' and 'full topic' the string '{mac}' in the value will be replaced by the last 6 hexadigits of the MAC address in lowercase format.tp-linkThis is a plugin to provisionTP-Linksmart plugs devices. It may work with other smart home devices, but this has not been tested. The device cannot be secured (no user/password setting) nor is any option available for this plugin.yeelightThis plugin is based on the protocol description and the code fromOpenMiHomeThis plugin provisionXiaomi Yeelight.Upon successful provisioning, the token, used to encrypt subsequent communications, is returned.By default, the key will be saved in the file ~/.aioyeelight. It can then be used withaioyeelight. If you do not wish to persist keys, use the nopersist option.Note: The plugin accepts the option 'owner' but this does not seem to have any effect.How it worksMostly each plugin knows what SSID to look for. If one of the needed SSID is found, aioiotprov will connect to the SSID and hand over provisioning duties to the plugin.
aioipapi
aioipapiAsynchronous asyncio/aiohttp based client forhttps://ip-api.comIP geolocation API.ip-api.comis a fast, accurate, reliable API service for IP geolocation, free for non-commercial use.aioipapipackage provides asynchronous API to use ip-api.com service in free and pro. The package features:Support JSON APIendpointSupport Batch JSON APIendpointAccess topro servicewith API keyFree API rate limits controlCustomizable retrying when networking problemsYou must not use aioipapi package for commercial purposes without API key.InstallingUse pip for installing:pip install -U aioipapiUsageAll examples are provided for Python 3.7 and above.Uselocationcoroutine to locate your own IP:importasynciofromaioipapiimportlocationprint(asyncio.run(location())){'status': 'success', 'country': 'United States', 'countryCode': 'US', 'region': 'CA', 'regionName': 'California', 'city': 'Santa Clara', 'zip': '95051', 'lat': 37.3417, 'lon': -121.9753, 'timezone': 'America/Los_Angeles', 'isp': 'DigitalOcean, LLC', 'org': 'Digital Ocean', 'as': 'AS14061 DigitalOcean, LLC', 'query': 'XXX.XX.XXX.XXX'}Uselocationcoroutine to locate a domain name:print(asyncio.run(location('github.com'))){'status': 'success', 'country': 'Netherlands', 'countryCode': 'NL', 'region': 'NH', 'regionName': 'North Holland', 'city': 'Amsterdam', 'zip': '1012', 'lat': 52.3667, 'lon': 4.89454, 'timezone': 'Europe/Amsterdam', 'isp': 'GitHub, Inc.', 'org': 'GitHub, Inc.', 'as': 'AS36459 GitHub, Inc.', 'query': '140.82.118.3'}A domain location is supported only in JSON endpoint. Currently, batch JSON endpoint does not support domain names as query. In other words, you cannot locate a list of domain names per time.Uselocationcoroutine to locate an IP with cusomized result fields and language:print(asyncio.run(location('8.8.8.8',fields=['continent','region','country'],lang='de'))){'status': 'success', 'continent': 'Nordamerika', 'country': 'Vereinigte Staaten', 'region': 'VA', 'query': '8.8.8.8'}Uselocationcoroutine to locate a list of IPs:print(asyncio.run(location(['1.0.0.1','1.1.1.1','8.8.4.4','8.8.8.8'],fields=['lat','lon','org'])))[ {'status': 'success', 'lat': -27.4766, 'lon': 153.0166, 'org': 'APNIC and Cloudflare DNS Resolver project', 'query': '1.0.0.1'}, {'status': 'success', 'lat': -27.4766, 'lon': 153.0166, 'org': 'APNIC and Cloudflare DNS Resolver project', 'query': '1.1.1.1'}, {'status': 'success', 'lat': 39.03, 'lon': -77.5, 'org': 'Google Public DNS', 'query': '8.8.4.4'}, {'status': 'success', 'lat': 39.03, 'lon': -77.5, 'org': 'Google Public DNS', 'query': '8.8.8.8'} ]You can customize the result fields and lang for each IP in the query list:ips=['77.88.55.66',{'query':'1.1.1.1','fields':['lat','lon','country'],'lang':'de'},{'query':'8.8.8.8','fields':['continent','country'],'lang':'ru'},]print(asyncio.run(location(ips,fields=['region','isp','org'])))[ {'status': 'success', 'region': 'MOW', 'isp': 'Yandex LLC', 'org': 'Yandex enterprise network', 'query': '77.88.55.66'}, {'status': 'success', 'country': 'Australien', 'lat': -27.4766, 'lon': 153.0166, 'query': '1.1.1.1'}, {'status': 'success', 'continent': 'Северная Америка', 'country': 'США', 'query': '8.8.8.8'} ]In these cases the package uses Batch JSON API endpoint.Uselocation_streamasync generator to locate IPs from an iterable or async iterable:importasynciofromaioipapiimportlocation_streamasyncdeflocate():asyncforresinlocation_stream(['1.0.0.1','1.1.1.1','8.8.4.4','8.8.8.8']):print(res)asyncio.run(locate())location_streamalso supportsfieldsandlangoptions.location_streamalways uses Batch JSON API endpoint.UseIpApiClientclass:importasynciofromaioipapiimportIpApiClientasyncdeflocate():asyncwithIpApiClient()asclient:print(awaitclient.location())asyncio.run(locate())IpApiClientprovideslocationandlocation_streammethods similar to the corresponding non-member coroutines.UseIpApiClientclass with existingaiohttp.ClientSessioninstead of client own session:importasyncioimportaiohttpfromaioipapiimportIpApiClientasyncdeflocate():asyncwithaiohttp.ClientSession()assession:asyncwithIpApiClient(session=session)asclient:print(awaitclient.location())asyncio.run(locate())Usage of existing session also supported inlocationandlocation_streamnon-member coroutines.If you want to use unlimited pro ip-api service you can use your API key inlocation,location_streamfunctions andIpApiClient:asyncwithIpApiClient(key='your-api-key')asclient:...When API key is set, the package always uses HTTPS for connection withpro.ip-api.com.Free API Rate Limit Controlip-api service has rate limits in free API (without key). Currently, there are 45 requests per minute for JSON endpoint and 15 requests per minute for Batch JSON endpoint.The package controls the rate limits usingX-RlandX-Ttlresponse headers. In other words, you are unlikely to get 429 HTTP error when using free API. When API key is being used, the rate limits are not being checked, because pro API is theoretically unlimited.Let's locate a lot of IPs for example:importasyncioimportsysimportlogginglogging.basicConfig(format='%(relativeCreated)d[%(levelname)s]%(message)s',level=logging.DEBUG,stream=sys.stderr,)fromaioipapiimportlocationasyncio.run(location(['8.8.8.8']*2000))798 [DEBUG] BATCH API rate limit: rl=14, ttl=60 900 [DEBUG] BATCH API rate limit: rl=13, ttl=59 1001 [DEBUG] BATCH API rate limit: rl=12, ttl=59 1103 [DEBUG] BATCH API rate limit: rl=11, ttl=59 1247 [DEBUG] BATCH API rate limit: rl=10, ttl=59 1391 [DEBUG] BATCH API rate limit: rl=9, ttl=59 1493 [DEBUG] BATCH API rate limit: rl=8, ttl=59 1595 [DEBUG] BATCH API rate limit: rl=7, ttl=59 1698 [DEBUG] BATCH API rate limit: rl=6, ttl=59 1809 [DEBUG] BATCH API rate limit: rl=5, ttl=58 1910 [DEBUG] BATCH API rate limit: rl=4, ttl=58 2015 [DEBUG] BATCH API rate limit: rl=3, ttl=58 2116 [DEBUG] BATCH API rate limit: rl=2, ttl=58 2216 [DEBUG] BATCH API rate limit: rl=1, ttl=58 2315 [DEBUG] BATCH API rate limit: rl=0, ttl=58 2367 [WARNING] API rate limit is reached. Waiting for 61 seconds by rate limit... 63464 [DEBUG] BATCH API rate limit: rl=14, ttl=60 63605 [DEBUG] BATCH API rate limit: rl=13, ttl=59 63695 [DEBUG] BATCH API rate limit: rl=12, ttl=59 63790 [DEBUG] BATCH API rate limit: rl=11, ttl=59 63894 [DEBUG] BATCH API rate limit: rl=10, ttl=59Retrying ConnectionThe client try to reconnect to the service when networking problems. By default 3 attempts and 1 second between attempts are used. You can change these parameters byretry_attemptsandretry_delayparameters:fromaioipapiimportlocation,location_stream,IpApiClient...result=location('8.8.8.8',retry_attempts=2,retry_delay=1.5)stream=location_stream(['8.8.8.8','1.1.1.1'],retry_attempts=2,retry_delay=1.5)...asyncwithIpApiClient(retry_attempts=2,retry_delay=1.5):...Also you can change these parameters in the global config:fromaioipapiimportconfig,IpApiClientconfig.retry_attempts=2config.retry_delay=1.5...asyncwithIpApiClient():...LicenseMIT
aio-ipfabric
Python Asyncio Client for IP FabricThis package contains a Python 3.8+ asyncio client for use wih the IP Fabric product.About IP Fabric:https://ipfabric.io/About IP Fabric API:https://docs.ipfabric.io/api/Installating aio-ipfabric and supported versionsaio-ipfabric is available onPyPI:pipinstallaio-ipfabricDirect installationpipinstallgit+https://github.com/jeremyschulman/aio-ipfabric@master#egg=aio-ipfabricRequests officially supports Python 3.8+.Quick StartfromaioipfabricimportIPFabricClientasyncdefdemo_1_devices_list():"""Example code that uses IPFabricClient without contextmanager"""# create a client using environment variables (see next section)ipf=IPFabricClient()# alternatively create instance with parameters# ipf = IPFabricClient(base_url='https://myipfserver.com', username='admin', password='admin12345')# ipf = IPFabricClient(base_url='https://myipfserver.com', token='TOKENFROMIPF')# login to IP Fabric systemawaitipf.login()# fetch the complete device inventorydevice_list=awaitipf.fetch_devices()# close asyncio connection, otherwise you will see a warning.awaitipf.logout()returndevice_listasyncdefdemo_2_devices_list():"""Example code that uses IPFabricClient as contextmanager"""# create a client using environment variables (see next section)asyncwithIPFabricClient()asipf:returnawaitipf.fetch_devices()Environment VariablesThe following environment variable can be used so that you do no need to provide them in your program:IPF_ADDR- IP Fabric server URL, for example "https://my-ipfabric-server.com/"IPF_USERNAME- Login usernameIPF_PASSWORD- Login passwordIPF_TOKEN- A persistent API tokenYou can use either the login credentials or the token to login.If you prefer not to use environment variables, the call toIPFabricClient()accepts parameters; refer to thehelp(IPFabricClient)for details.DocumentationSee thedocsdirectory.
aioipfs
info:AsynchronousIPFSclient libraryaioipfsis a python3 library providing an asynchronous API forIPFS. Supported python versions:3.6,3.7,3.8,3.9,3.10,3.11,3.12.This library supports theRPC API specificationsforkuboversion0.26.0. Unit tests are run against most major go-ipfs releases and allkuboreleases, see theCIsection below.Seethe documentation here.InstallationpipinstallaioipfsSupport for CAR (Content-Addressable Archives) decoding (with theipfs-car-decoder package) can be enabled with thecarextra:pipinstall'aioipfs[car]'By default thejsonmodule from the standard Python library is used to decode JSON messages, butorjsonwill be used if it is installed:pipinstall'aioipfs[orjson]'UsageClient instantiationThe recommended way to specify the kubo node’s RPC API address is to pass amultiaddr.client=aioipfs.AsyncIPFS(maddr='/ip4/127.0.0.1/tcp/5001')client=aioipfs.AsyncIPFS(maddr='/dns4/localhost/tcp/5001')You can also pass amultiaddr.Multiaddrinstance.frommultiaddrimportMultiaddrclient=aioipfs.AsyncIPFS(maddr=Multiaddr('/ip4/127.0.0.1/tcp/5001'))Otherwise just passhostandportseparately:client=aioipfs.AsyncIPFS(host='localhost',port=5001)client=aioipfs.AsyncIPFS(host='::1',port=5201)Get an IPFS resourceimportsysimportasyncioimportaioipfsasyncdefget(cid:str):client=aioipfs.AsyncIPFS()awaitclient.get(cid,dstdir='.')awaitclient.close()loop=asyncio.get_event_loop()loop.run_until_complete(get(sys.argv[1]))Add some filesThis example will import all files and directories specified on the command line. Note that theaddAPI function is an asynchronous generator and therefore should be used with theasync forsyntax.importsysimportasyncioimportaioipfsasyncdefadd_files(files:list):client=aioipfs.AsyncIPFS()asyncforadded_fileinclient.add(*files,recursive=True):print('Imported file{0}, CID:{1}'.format(added_file['Name'],added_file['Hash']))awaitclient.close()loop=asyncio.get_event_loop()loop.run_until_complete(add_files(sys.argv[1:]))You can also use the async list generator syntax:cids=[entry['Hash']asyncforentryinclient.add(dir_path)]Pubsub serviceasyncdefpubsub_serve(topic:str):asyncwithaioipfs.AsyncIPFS()ascli:asyncformessageincli.pubsub.sub(topic):print('Received message from',message['from'])awaitcli.pubsub.pub(topic,message['data'])Dialing a P2P serviceasyncwithaioipfs.AsyncIPFS()asclient:asyncwithclient.p2p.dial_service(peer_id,'/x/echo')asdial:print(f'Dial host:{dial.maddr_host}, port:{dial.maddr_port}')# Connect to the service now....CIThe Gitlab CI workflow runs unit tests against the following go-ipfs/kubo releases (go herefor the CI jobs overview).go-ipfs >=0.11.0,<=0.13.0kubo >=0.14.0,<=0.26.0FeaturesAsync file writing on get operationsTheaiofileslibrary is used to asynchronously write data retrieved from the IPFS daemon when using the/api/v0/getAPI call, to avoid blocking the event loop. TAR extraction is done in asyncio’s threadpool.RequirementsPython >= 3.6, <= 3.11aiohttpaiofilespy-multibaseyarlLicenseaioipfsis offered under the GNU Lesser GPL3 (LGPL3) license.
aioipfs-2
# AioKITRoutines for asynchronous programming
aioipfs-api
Async IPFS API ClientDocumentation can be found ataioipfs-api.readthedocs.org.Installationpip install aioipfs-apiUsageThis assumes you have a working familiarity withasyncio.importasynciofromaioipfs_api.clientimportClientasyncdefmain():asyncwithClient()asclient:# print the readmeasyncwithclient.cat("QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG/readme")asf:print(awaitf.text())# add a directoryprint(awaitclient.add('/some/dir/path'))loop=asyncio.get_event_loop()loop.run_until_complete(main())LoggingThis library uses the standardPython logging library. To see debut output printed to STDOUT, for instance, use:importlogginglog=logging.getLogger('aioipfs_api')log.setLevel(logging.DEBUG)log.addHandler(logging.StreamHandler())Running TestsTo run tests:pip install -r dev-requirements.txt python -m unittest
aioipinfo
aioipinfoA simple, asyncipinfo.ioclient.Exposes anIPInfoClientthat implements one querying method,ipinfo, and includes a CLI client that can be run withpython3 -m aioipinfo. See thefull docsfor more details.
aioirc
AsyncIO IRC Library for >= Python 3.3In Pre-Alpha now.
aioircd
aioircdA minimalist python asynchronous IRC server built on top ofTrio.Installation and UsageDownload and install the latest stable version using pip. Windows users might replacepython3bypy.python3 -m pip install aioircdThen run the server:HOST=0.0.0.0 LOGLEVEL=INFO python3 -m aioircdThe configuration is done via environment variables, see--help:optional arguments: -h, --help show this help message and exit -V, --version show program's version number and exit environment variables: HOST public domain name (default: julien-UX410UAR) ADDR ip address to bind (default: 127.0.1.1) PORT port to bind (default: 6667) PASS server password (default: ) TIMEOUT kick inactive users after x seconds (default: 60) PING_TIMEOUT PING inactive users x seconds before timeout (default: 5) LOGLEVEL logging verbosity (default: WARNING)ScopeWe try to both keep only implement the most important commands and to make sure all modern IRC clients are working. If you are having troubles using aioircd with your client feel free to open an issue.Stuff we don't plan to support: server connections, user modes, channel modes.
aioiregul
aioiregulAsynchronous library to get data from Iregul systemsThis library is under developmentRequires Python 3 and uses asyncio, aiohttp and BeautifulSoup4.importaioiregulimportaiohttpimportasyncioasyncdefmain():opt=aioiregul.ConnectionOptions(username='User',password='Pass')dev=aioiregul.Device(opt)res=awaitdev.collect()print(res)loop=asyncio.get_event_loop()loop.run_until_complete(main())
aioisotp
This package implementsISO-TPover CAN as anasynciotransport layer, enabling simultaneous receiving and transmitting messages with any number of connections.Raw CAN communication usespython-canwhich offers compatibility for many different CAN interfaces and operating systems.If SocketCANISO-TP moduleis loaded and Python 3.7+ is used, the transport is delegated to the kernel if possible for better timing performance. Use the ‘socketcan’ interface. If unsuccessful, raw CAN will be used as fallback.The isotpserver fromcan-utilscan also be used to bridge a SocketCAN ISO-TP connection over TCP/IP. Use the ‘isotpserver’ interface and ‘host:port’ as channel.Why asynchronous?Asynchronous programming simplifies some possible use-cases:Full duplex receiving and transmitting on a single connection.Communicate on multiple connections simultaneously.Functional addressing where one request is sent out and all nodes respond, then processing the responses as they arrive.Implementing or simulating multiple servers.No threads need to be handled with all the locking mechanisms required by it.InstallationInstall from PyPI:$ pip install aioisotp==0.1.1DocumentationA basic documentation can be built using Sphinx:$ python setup.py build_sphinxQuick startHere is an example of an echo server implemented using a callback based protocol and a client implemented as sequencial reader and writer streams.importasyncioimportaioisotpclassEchoServer(asyncio.Protocol):defconnection_made(self,transport):self.transport=transportdefdata_received(self,data):# Echo back the same dataself.transport.write(data)asyncdefmain():network=aioisotp.ISOTPNetwork('vcan0',interface='virtual',receive_own_messages=True)withnetwork.open():# A server that uses a protocoltransport,protocol=awaitnetwork.create_connection(EchoServer,0x1CDADCF9,0x1CDAF9DC)# A client that uses streamsreader,writer=awaitnetwork.open_connection(0x1CDAF9DC,0x1CDADCF9)writer.write(b'Hello world!')response=awaitreader.read(4095)assertresponse==b'Hello world!'loop=asyncio.get_event_loop()loop.run_until_complete(main())UDSThis package is meant to enable the use of other protocols that require ISO-TP. One of the most common is UDS. A third party library likeudsoncanorpyvitcan be used to encode and decode payloads.importaioisotpimportudsoncan...reader,writer=awaitnetwork.open_connection(0x1CDAF9DC,0x1CDADCF9)# Construct and send requestrequest=udsoncan.Request(udsoncan.services.ReadDataByIdentifier,data=b'\xF1\x90')writer.write(request.get_payload())# Wait for response and decode the payloadpayload=awaitreader.read(4095)response=udsoncan.Response.from_payload(payload)print(response)print(response.data)
aioitertools
aioitertoolsImplementation of itertools, builtins, and more for AsyncIO and mixed-type iterables.Installaioitertools requires Python 3.6 or newer. You can install it from PyPI:$ pip install aioitertoolsUsageaioitertools shadows the standard library whenever possible to provide asynchronous version of the modules and functions you already know. It's fully compatible with standard iterators and async iterators alike, giving you one unified, familiar interface for interacting with iterable objects:fromaioitertoolsimportiter,next,map,zipsomething=iter(...)first_item=awaitnext(something)asyncforiteminiter(something):...asyncdeffetch(url):response=awaitaiohttp.request(...)returnresponse.jsonasyncforvalueinmap(fetch,MANY_URLS):...asyncfora,binzip(something,something_else):...aioitertools emulates the entireitertoolsmodule, offering the same function signatures, but as async generators. All functions support standard iterables and async iterables alike, and can take functions or coroutines:fromaioitertoolsimportchain,isliceasyncdefgenerator1(...):yield...asyncdefgenerator2(...):yield...asyncforvalueinchain(generator1(),generator2()):...asyncforvalueinislice(generator1(),2,None,2):...Seebuiltins.py,itertools.py, andmore_itertools.pyfor full documentation of functions and abilities.Licenseaioitertools is copyrightAmethyst Reese, and licensed under the MIT license. I am providing code in this repository to you under an open source license. This is my personal repository; the license you receive to my code is from me and not from my employer. See theLICENSEfile for details.
aioja
aiojaAsync version of Jinja2.This library contains a modification of the Jinja2 library. In addition to Jinja's built-inrender_async, i've added:asyncFileSystemLoader(viaaiofiles)async bytecode cache (aioredisandaiocachesupported)async version of theEnvironment.compile_templatesmethodInstallpip install aiojaQuick Startfromaioja.environmentimportEnvironmentfromaioja.loadersimportFileSystemLoaderfromaioja.bccache.aiocacheimportAioCacheBytecodeCacheenv=Environment(loader=FileSystemLoader('templates'),# ...# bytecode_cache=AioCacheBytecodeCache()# ...)template=awaitenv.get_template('index.html')content=awaittemplate.render_async({'page_id':123})
aiojaeger
aiojaegerRequirementsPython3.7+aiohttppydancticthriftpy2CHANGES0.1.0 (2020-04-16)Init releaseAdd support for zipkin and jeager systemTests and linters
aiojarm
aiojarmAsync version ofJARM.InstallationpipinstallaiojarmUsageimportasyncioimportaiojarmloop=asyncio.get_event_loop()fingerprints=loop.run_until_complete(asyncio.gather(aiojarm.scan("www.salesforce.com"),aiojarm.scan("www.google.com"),aiojarm.scan("www.facebook.com"),aiojarm.scan("github.com"),))print(fingerprints)# [# (# "www.salesforce.com",# 443,# "23.42.156.194",# "2ad2ad0002ad2ad00042d42d00000069d641f34fe76acdc05c40262f8815e5",# ),# (# "www.google.com",# 443,# "172.217.25.228",# "27d40d40d29d40d1dc42d43d00041d4689ee210389f4f6b4b5b1b93f92252d",# ),# (# "www.facebook.com",# 443,# "31.13.82.36",# "27d27d27d29d27d1dc41d43d00041d741011a7be03d7498e0df05581db08a9",# ),# (# "github.com",# 443,# "52.192.72.89",# "29d29d00029d29d00041d41d0000008aec5bb03750a1d7eddfa29fb2d1deea",# ),# ]CLI usage$aiojarm--help Usage:aiojarm[OPTIONS]HOSTNAMES... Arguments:HOSTNAMES...IPs/domainsorafilewhichcontainsalistofIPs/domainsperline[required]Options:--portINTEGER[default:443]--max-at-onceINTEGER[default:8]--install-completionInstallcompletionforthecurrentshell.--show-completionShowcompletionforthecurrentshell,tocopyitorcustomizetheinstallation.--helpShowthismessageandexit. $aiojarm1.1.1.11.1.1.1,443,1.1.1.1,27d3ed3ed0003ed1dc42d43d00041d6183ff1bfae51ebd88d70384363d525c $aiojarmgoogle.com.uagoogle.gr google.com.ua,443,172.217.25.195,27d40d40d29d40d1dc42d43d00041d4689ee210389f4f6b4b5b1b93f92252d google.gr,443,216.58.220.131,27d40d40d29d40d1dc42d43d00041d4689ee210389f4f6b4b5b1b93f92252d# or you can input hostnames via a file$aiojarmlist.txtLicenseJARM is created by Salesforce's JARM team and it is licensed with 3-Clause "New" or "Revised" License.https://github.com/salesforce/jarm/blob/master/LICENSE.txt
aiojenkins
Asynchronous python package of Jenkins API endpoints based on aiohttp.Also pay attention to brand new package with same API set but with sync and async interfaces:https://github.com/pbelskiy/ujenkinsInstallationpip3installaiojenkinsUsageStart new build:importasyncioimportaiojenkinsjenkins=aiojenkins.Jenkins('http://your_server/jenkins','user','password')asyncdefexample():awaitjenkins.builds.start('job_name',dict(parameter='test'))loop=asyncio.get_event_loop()try:loop.run_until_complete(example())finally:loop.run_until_complete(jenkins.close())loop.close()Please look at tests directory for more examples.DocumentationRead the DocsTestingCurrently tests aren’t using any mocking. I am testing locally with dockerized LTS Jenkins ver. 2.222.3Prerequisites:docker, toxdocker run -d --name jenkins --restart always -p 8080:8080 jenkins/jenkins:lts docker exec jenkins cat /var/jenkins_home/secrets/initialAdminPassword chromium http://localhost:8080 # create admin:admin toxOr Jenkins 1.554docker run -d --name jenkins-1.554 --restart always -p 8081:8080 jenkins:1.554ContributingFeel free to PR
aiojikan
AioJikanAn asynchronous api wrapper for theJikan API.FeaturesSimple and Easy to use100% API CoverageFully typehinted models (I tried my best at least)Usage of datetime objects where applicable for easy conversionsExamplesAll projects should create a single instance of AioJikan, provide it with an aiohttp.ClientSession if you want to, and you're good to go.importasyncioimportaiojikanasyncdefmain():client=aiojikan.AioJikan()love_is_war=awaitclient.get_anime(37999)print(f"Love is war has{love_is_war.favorites}favorites!")awaitclient.close()loop=asyncio.get_event_loop()loop.run_until_complete(main())LicenseThis library is licensed under the MIT license, please review ithere
aiojlrpy
aiojlrpyPython 3 Async library for interacting with the JLR Remote car rest and websocket APIs.InstallationEither check out this repository directly or install through pip (for Python3).pip install aiojlrpyUsageNOTE: This is an async library, therefore must be run in a running event loop.To get started, instantiate aConnectionobject and pass along the email address and password associated with your Jaguar InControl account.There are two ways to authenticate to InControl. Using the user name and password or with a valid refresh token.The JLR API requires a device ID to be registered (UUID4 formatted). If you do not specify one when instantiating theConnectionobject it will generate a new one for your automatically. However, it is highly recommended to provide a consistant device ID for your connection, especially if using the websocket function.InControl provides 2 different APIs.REST API The main api to get vehicle data and perform actions on your account/vehicleWebsocket API A push api that provides messages when things happen on your vehicle for service calls and things which update status attributes and alerts. A status message is formatted from the library into a strucutred StatusMessage class object.fromaiojlrpyimportConnection,Vehicle,StatusMessage# Authenticate just the rest api using the username, password.c=Connection(EMAIL,PWD,device_id=DEVICEID,)awaitc.connect()v=c.vehicles[0]# Authenticate and enable the websocket connection (highly recommended to provide a fixed device id here).# on_message is a callback function in your code to receive websocket messagesc=Connection(EMAIL,PWD,device_id=DEVICE_ID,ws_message_callback=on_message,)awaitc.connect()asyncdefon_message(message:StatusMessage):print(message)# Authenticate using a refresh token (username must still be specified)c=Connection(email='[email protected]',refresh_token='124c3f21-42ds-2e4d-86f8-221v32392a1d')awaitc.connect()Connection.vehicleswill list all vehicles associated with your account.# Get user informationawaitc.get_user_info()# Update user information.p=awaitc.get_user_info()p['contact']['userPreferences']['unitsOfMeasurement']="Km Litre Celsius VolPerDist Wh DistPerkWh"awaitc.update_user_info(p)# Refresh access tokenawaitc.refresh_tokens()# Get attributes associated with vehicleawaitv.get_attributes()# Get current status of vehicleawaitv.get_status()# Get current active servicesawaitv.get_services()# Optionally, you can also specify a status value keyawaitv.get_status("EV_STATE_OF_CHARGE")# Get subscription packesawaitv.get_subscription_packages()# Get trip data (last 1000 trips).awaitv.get_trips()# Get data for a single trip (specified with trip id)awaitv.get_trip(121655021)# Get vehicle health statusawaitv.request_health_status()# Get departure timersawaitv.get_departure_timers()# Get configured wakeup timeawaitv.get_wakeup_time()# Honk horn and blink lightsawaitv.honk_blink()# Get current position of vehicleawaitv.get_position()# Start preconditioning at 21.0Cawaitv.preconditioning_start("210")# Stop preconditioningawaitv.precenditioning_stop()# Set vehicle nickname and registration numberawaitv.set_attributes("Name","reg-number")# Lock vehicleawaitv.lock(pin)# pin being the personal master pin# Unlock vehicleawaitv.unlock(pin)# Reset alarmawaitv.reset_alarm(pin)# Start chargingawaitv.charging_start()# Stop chargingawaitv.charging_stop()# Set max soc at 80% (Requires upcoming OTA update)awaitv.set_max_soc(80)# Set max soc for current charging session to 90% (Requires upcoming OTA update)awaitv.set_one_off_max_soc(90)# Add single departure timer (index, year, month, day, hour, minute)awaitv.add_departure_timer(10,2019,1,30,20,30)# Delete a single departure timer index.awaitv.delete_departure_timer(10)# Schedule repeated departure timer.schedule={"friday":False,"monday":True,"saturday":False,"sunday":False,"thursday":False,"tuesday":True,"wednesday":True}awaitv.add_repeated_departure_timer(10,20,30,schedule)# Set wakeup timer (epoch millis)awaitv.set_wakeup_time(1547845200000)# Cancel wakeup timerawaitv.delete_wakeup_time()# Enable service mode (requires personal PIN)awaitv.enable_service_mode("1234",1547551847000)# Enable transport mode (requires personal PIN)awaitv.enable_transport_mode("1234",1547551847000)# Enable privacy modeawaitv.enable_privacy_mode("1234")# Disable privacy modeawaitv.disable_privacy_mode("1234")# Add charging period with specified index identifier value.awaitv.add_charging_period(1,schedule,0,30,8,45)# Reverse geocodeawaitc.reverse_geocode(59.915475,10.733054)ExamplesThe examples directory contains example scripts that put aiojlrpy to good use. #TODOCreditsHuge shout out to @ardedv for his tremendous work in jlypy which this library uses as a base.
aiojobs
Job scheduler for managing background tasks (asyncio)The library gives a controlled way for scheduling background tasks for asyncio applications.Installation$pip3installaiojobsUsage exampleimportasyncioimportaiojobsasyncdefcoro(timeout):awaitasyncio.sleep(timeout)asyncdefmain():scheduler=aiojobs.Scheduler()foriinrange(100):# spawn jobsawaitscheduler.spawn(coro(i/10))awaitasyncio.sleep(5.0)# not all scheduled jobs are finished at the moment# gracefully close spawned jobsawaitscheduler.close()asyncio.get_event_loop().run_until_complete(main())Integration with aiohttp.webfromaiohttpimportwebfromaiojobs.aiohttpimportsetup,spawnasyncdefhandler(request):awaitspawn(request,coro())returnweb.Response()app=web.Application()app.router.add_get('/',handler)setup(app)or justfromaiojobs.aiohttpimportatomic@atomicasyncdefhandler(request):returnweb.Response()For more information read documentation:https://aiojobs.readthedocs.ioCommunication channelsaio-libsgoogle group:https://groups.google.com/forum/#!forum/aio-libsFeel free to post your questions and ideas here.Gitter Chathttps://gitter.im/aio-libs/LobbyWe supportStack Overflow. Please addpython-asynciooraiohttptag to your question there.Author and LicenseTheaiojobspackage is written by Andrew Svetlov.It’sApache 2licensed and freely available.
aiojobs-fork
ImportantThis is a manintained fork of an abandoned package. The originalaiojobspackage is written by Andrew Svetlov. The purpose of this fork is to merge open pull requests that were open for a very long time without any feedback from the maintainer side.aiojobsJobs scheduler for managing background task (asyncio)The library gives controlled way for scheduling background tasks for asyncio applications.Installation$pip3installaiojobsUsage exampleimportasyncioimportaiojobsasyncdefcoro(timeout):awaitasyncio.sleep(timeout)asyncdefmain():scheduler=awaitaiojobs.create_scheduler()foriinrange(100):# spawn jobsawaitscheduler.spawn(coro(i/10))awaitasyncio.sleep(5.0)# not all scheduled jobs are finished at the moment# gracefully close spawned jobsawaitscheduler.close()asyncio.get_event_loop().run_until_complete(main())Integration with aiohttp.webfromaiohttpimportwebfromaiojobs.aiohttpimportsetup,spawnasyncdefhandler(request):awaitspawn(request,coro())returnweb.Response()app=web.Application()app.router.add_get('/',handler)setup(app)or justfromaiojobs.aiohttpimportatomic@atomicasyncdefhandler(request):returnweb.Response()For more information read documentation:https://aiojobs.readthedocs.ioCommunication channelsaio-libsgoogle group:https://groups.google.com/forum/#!forum/aio-libsFeel free to post your questions and ideas here.Gitter Chathttps://gitter.im/aio-libs/LobbyWe supportStack Overflow. Please addpython-asynciooraiohttptag to your question there.Author and LicenseTheaiojobspackage is written by Andrew Svetlov.It’sApache 2licensed and freely available.
aiojobs-stubs
AboutThis repository contains external type annotations (seePEP 484) for theaiojobslibrary.InstallationTo use these stubs with mypy, you have to install the aiojobs-stubs package.pipinstallaiojobs-stubs
aiojson
Simple json template verifier foraiohttpUsageSimple example:fromaiohttpimportJsonTemplate@JsonTemplate({"messages":[{"id":int,"text":str}])asyncdefreceived_message(request,validated_data):pass
aiojsonapi
No description available on PyPI.
aiojsonBox
No description available on PyPI.
aiojsonflow
Write scripts in JSON format and run it. Easy to extend it by writting simple python functions. It’s a way to let user run custom scripts in a flow.
aiojsonrpc
aiojsonrpc2
``aiojsonrpc2`` is a Python3 JSONRPC module built using ``asyncio``.Supports Python 3.5+ only (usesasync/awaitsyntax)Plain socket transport (not JSONRPC over HTTP)Supports secure TLS (ie. SSL) socketsThis is a new, fast, and modern JSONRPC module originally built to support`aiostratum_proxy<https://github.com/wetblanketcc/aiostratum_proxy>`__ (a next-gen, extensible cryptocurrency mining proxy). However, releasing it as it’s own independent Python package made the most sense.InstallationThere are currently no external dependencies required foraiojsonrpc2, and installation is simple:pip install aiojsonrpc2UsageTo useaiojsonrpc2and depending on your needs, you need to implement either a client or server ‘protocol’. BothClientProtocolandServerProtocollet you handle bi-directional JSONRPC communication.All incoming JSONRPC requests infer a protocol instance method from the JSONRPCmethodparameter. For example, if themethodcontainsclient.show_message, then the protocol class implementation must have an instance method calledhandle_client_show_message:from aiojsonrpc2 import ClientProtocol, ServerProtocol class MyClientProtocol(ClientProtocol): # NOTE: the opposing connection (perhaps a server) would # have sent the `client.show_message` request; # bidirectional communication! def handle_client_show_message(self, connection, params, **kwargs): # assuming the message to show is `params[0]` print(params[0])Note how all.(ie. full stops/periods) from the JSONRPCmethodparameter are replaced by_(ie. underscore).Future ConsiderationsCommunity involvement is appreciated.Code review,pull requests for bug fixes & improvements,reporting issues, spreading the word - all appreciated.TODO:teststravis integrationhandlehaproxy ``PROXY`protocol <http://www.haproxy.org/download/1.8/doc/proxy-protocol.txt>`__
aio-jsonrpc-2.0
aio-jsonrpc-2.0Descriptionjson rpc 2.0 protocol implementation for asyncio, without transport.specification:http://www.jsonrpc.org/Usage:Example to resolve request:importasyncioimportjsonfromaio_jsonrpc_20importRequestResolverasyncdeffoo(msg):awaitasyncio.sleep(0.1)return'foobar '+str(msg)router={'foo':foo}resolver=RequestResolver(router)json_request=json.dumps({"jsonrpc":"2.0","method":"foo","params":["toto"],"id":1})asyncdefmain():json_response=awaitresolver.handle(json_request)print(json_response)loop=asyncio.get_event_loop()loop.run_until_complete(main())Result:{"jsonrpc":"2.0","result":"foobar toto","id":1}Example to build request:fromaio_jsonrpc_20importRequestBuilderbuilder=RequestBuilder()json_request=builder.call(method="foo",params={"name":"bar"})print(json_request)json_request=builder.call(method="foo",params={"name":"bar2"})print(json_request)json_request=builder.notify(method="log",params=["hello"])print(json_request)Result:{"jsonrpc":"2.0","method":"foo","params":{"name":"bar"},"id":1}{"jsonrpc":"2.0","method":"foo","params":{"name":"bar2"},"id":2}{"jsonrpc":"2.0","method":"log","params":["hello"]}Example to build batch request:fromaio_jsonrpc_20importBatchRequestBuilderbatch_builder=BatchRequestBuilder()id1=batch_builder.call(method="foo",params={"name":"bar"})id2=batch_builder.call(method="foo2",params={"name":"bar"})print(id1,id2)batch_builder.notify(method="foo3",params={"name":"bar"})json_request=batch_builder.get_request()print(json_request)Result:12[{"jsonrpc":"2.0","method":"foo","params":{"name":"bar"},"id":1},{"jsonrpc":"2.0","method":"foo2","params":{"name":"bar"},"id":2},{"jsonrpc":"2.0","method":"foo3","params":{"name":"bar"}}]TODO:Fix definitely interface for buildersMore TestDocumentationOptimisation...Testing:py.test --cov=aio_jsonrpc_20 --cov-report term-missing tests/0.1.2fix(README): Fixed encoding error0.1.0Initial release.
aiok
No description available on PyPI.
aiok8s
aiok8sThis a client library meant for building asynchronous Kubernetes controllers using Python. It currently integrates withkubernetes_asyncio.Most of the code is directly translated from and attributed toclient-goandcontroller-runtime. This approach is taken to help ensure that the logic is battle-tested and reduce overhead in maintaining the library. It's meant to replicate only some of the most desirable APIs of the Go libraries, not all of them.This is in early development. APIs may be adjusted or even removed.
aioka
aioka
aiokafka
asyncio client for KafkaAIOKafkaProducerAIOKafkaProducer is a high-level, asynchronous message producer.Example of AIOKafkaProducer usage:fromaiokafkaimportAIOKafkaProducerimportasyncioasyncdefsend_one():producer=AIOKafkaProducer(bootstrap_servers='localhost:9092')# Get cluster layout and initial topic/partition leadership informationawaitproducer.start()try:# Produce messageawaitproducer.send_and_wait("my_topic",b"Super message")finally:# Wait for all pending messages to be delivered or expire.awaitproducer.stop()asyncio.run(send_one())AIOKafkaConsumerAIOKafkaConsumer is a high-level, asynchronous message consumer. It interacts with the assigned Kafka Group Coordinator node to allow multiple consumers to load balance consumption of topics (requires kafka >= 0.9.0.0).Example of AIOKafkaConsumer usage:fromaiokafkaimportAIOKafkaConsumerimportasyncioasyncdefconsume():consumer=AIOKafkaConsumer('my_topic','my_other_topic',bootstrap_servers='localhost:9092',group_id="my-group")# Get cluster layout and join group `my-group`awaitconsumer.start()try:# Consume messagesasyncformsginconsumer:print("consumed: ",msg.topic,msg.partition,msg.offset,msg.key,msg.value,msg.timestamp)finally:# Will leave consumer group; perform autocommit if enabled.awaitconsumer.stop()asyncio.run(consume())Running testsDocker is required to run tests. Seehttps://docs.docker.com/engine/installationfor installation notes. Also note, thatlz4compression libraries for python will requirepython-devpackage, or python source header files for compilation on Linux. NOTE: You will also need a valid java installation. It’s required for thekeytoolutility, used to generate ssh keys for some tests.Setting up tests requirements (assuming you’re within virtualenv on ubuntu 14.04+):sudo apt-get install -y libsnappy-dev libzstd-dev libkrb5-dev krb5-user make setupRunning tests with coverage:make covTo run tests with a specific version of Kafka (default one is 1.0.2) use KAFKA_VERSION variable:make cov KAFKA_VERSION=0.10.2.1Test running cheatsheat:make testFLAGS="-l-x--ff"- run until 1 failure, rerun failed tests first. Great for cleaning up a lot of errors, say after a big refactor.make testFLAGS="-kconsumer"- run only the consumer tests.make testFLAGS="-m'not ssl'"- run tests excluding ssl.make testFLAGS="--no-pull"- do not try to pull new docker image before test run.