Saravanan666/pypi-org huggingface dataset:
Package: 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:UUID@routes.post('/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 parameter.@routes.post('/{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)
Package: 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>
Package: 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

...
Package: 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.
Package: 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())
Package: 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())
Package: 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.
Package: 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.
Package: 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.
Package: 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)
Package: 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 shortcuts@routes.post("/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)returnwrapper@routes.get("/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
Package: 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()
Package: 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:
Package: 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.
Package: 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/*
Package: 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())
Package: 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!
Package: 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"