Saravanan666/pypi-org huggingface dataset:
Package: aiohttp-google-auth-backend
aiohttp_google_auth_backendThe Google Authentication Library for python,google-auth,
providesverify_token(and verify_oauth2_token) methods, which can be used by
backend servers to verify the token provided by the
web/mobile application and return decoded profile fields. However, python google-auth does
not yet provide the support for asyncio.Theaiohttp_google_auth_backendlibrary provides async
wrapper for these methods.How to use itaiohttp_google_auth_backend package provides JSAioGoogleTokenVerifier class to asynchronously handle the token verification.The library uses the asynchronous task to fetch and cache the
GOOGLE OAUTH2 Certificates in the background using aiohttp Client API.Create an instance of JSAioGoogleTokenVerifier, along with the aiohttp web application instance, during the startup.Registeron_startupmethod of the instance with on_startup of web application to fetch the certificates for first rime and then start the background thread to re-fetch the certificates.Registeron_cleanupmethod of the instance with on_cleanup of web application to cancel the background thread when the process is being stopped.Constructor for the JSAioGoogleTokenVerifier class provides following parameters to customize re-fetching of certificates.By default, library uses the "Expires" header to identify when the certificates need to be re-fetched.Theok_renew_intervalparameter can be used to specify interval to re-fetch certificates (e.g. every hour).If the library fails to fetch the certificates, it will repeatedly try to re-fetch certificates until successful.Library starts with initial delay ofmin_error_renew_interval(default: 1 second) and
exponentially backoff the interval for each sub-sequent fetch till the delay reachesmax_error_renew_interval.Token fields to be returned are identified by parameterprofile_fields(default: email)Following code sample assume that token to be verified is passed as parameter idtoken.fromaiohttpimportwebfromaiohttp_google_auth_backendimportJSAioGoogleTokenVerifierSAMPLE_GOOGLE_CLIENT_ID="YOUR GOOGLE APPID"asyncdefhandleLogin(request):data=awaitrequest.json()status,res=awaitrequest.app['verifyGoogleToken'].verify_token(data["idtoken"],SAMPLE_GOOGLE_CLIENT_ID)ifstatus==200:returnweb.json_response(res,status=status)else:returnweb.json_response(dict(error=str(res['error'])),status=status)asyncdefapp_startup(app):app['JSAioGoogleTokenVerifier']=JSAioGoogleTokenVerifier()awaitapp['JSAioGoogleTokenVerifier'].on_startup()asyncdefapp_cleanup(app):awaitapp['JSAioGoogleTokenVerifier'].on_cleanup()defapp_run():app=web.Application()app.on_startup.append(app_startup)app.on_cleanup.append(app_cleanup)app.add_routes([web.post('/login',handleLogin)])web.run_app(app)if__name__=='__main__':app_run()
Package: aiohttphelper
aiohttphelperContextRequirementsInstallation / DependenciesUsageError HandlingReferencesContextThe purpose of this package is to make a simple wrapper for aiohttp/calls in order to use it in my personnal / professional projects.It will make one or several calls using the same session and coroutines.RequirementsPython >= 3.6Installation / DependenciespipinstallaiohttphelperThe following dependencies will also be installedaiohttp[speedups]==3.6.2UsageFirst import the module:import aiohttphelperYou have 4 functions available to you:aiohttphelper.get(calls,headers,**kwargs)aiohttphelper.put(calls,headers,**kwargs)daiohttphelper.post(calls,headers,**kwargs)aiohttphelper.delete(calls,headers,**kwargs)Callsis a list of the urls to request. In case of put/post you need to provide a tuple (url, data):aiohttphelper.put((url,data),headers,**kwargs)They all return the same thing, a list of SimpleNamespace objects with the following attributes:object.urlobject.statusobject.textAs it's build in top of aiohttp **kwargs is used to pass parameters to the request.
Look at thedocumentationfor more details.:warning: !Be carefull the default timeout for the session is 5 minutes, but you can override it:aiohttphelper.get('dummy_url',headers='dummy_headers',timeout="10000")Error HandlingBy default all the calls that does not succed will raise an error:aiohttp.client_exceptions.ClientResponseErrorIf you want to carry on with the calls even if one fails you need to passraise_for_status=Falseas an argument.
If you do so the result will contain the response text and response status in any successfull request.Referencesaiohttp documentationaiohttp LicenceCopyright 2013-2020 aiohttp maintainers
Package: aiohttp-hijacks
aiohttp-hijacksHijack aiohttp session to re-route the requests.fromaiohttp_hijacksimportFakeServer,FakeSession,routeclassServer(FakeServer):""" Application that will respond to the client. """@route('/')asyncdefget_abc(self,request):self.calls+=1returnself.json_response({"status":"ok"})# Reroute google.com → 127.0.0.1asyncwithServer()asserver:# instantiate Server handling '127.0.0.1:{server.port}/abc'asyncwithFakeSession(reroute={'google.com':server.port})assession:# redirecting calls to http(s)://google.com to 127.0.0.1:{server.port}resp=awaitsession.get("https://google.com")data=awaitresp.json()assertdata=={"status":"ok"}
Package: aiohttp-index
aiohttp.webmiddleware to
serve index files (e.g. index.html) when static directories are requested.Usagefromaiohttpimportwebfromaiohttp_indeximportIndexMiddlewareapp=web.Application(middlewares=[IndexMiddleware()])app.router.add_static('/','static')appwill now servestatic/index.htmlwhen/is requested.DependenciesPython 3.5+aiohttp(tested on
0.21.4)
Package: aiohttp-ip-rotator
aiohttp-ip-rotatorAn asynchronous alternative to the requests-ip-rotator  (https://github.com/Ge0rg3/requests-ip-rotator) library based on aiohttp, completely copying its functionalityExamplefromasyncioimportget_event_loopfromaiohttp_ip_rotatorimportRotatingClientSessionasyncdefmain():session=RotatingClientSession("https://api.ipify.org","aws access key id","aws access key secret")awaitsession.start()foriinrange(5):response=awaitsession.get("https://api.ipify.org")print(f"Your ip:{awaitresponse.text()}")awaitsession.close()if__name__=="__main__":get_event_loop().run_until_complete(main())Example 2fromasyncioimportget_event_loopfromaiohttp_ip_rotatorimportRotatingClientSessionasyncdefmain():asyncwithRotatingClientSession("https://api.ipify.org","aws access key id","aws access key secret")assession:foriinrange(5):response=awaitsession.get("https://api.ipify.org")print(f"Your ip:{awaitresponse.text()}")if__name__=="__main__":get_event_loop().run_until_complete(main())
Package: aiohttp-jrpc
aiohttp_jrpcjsonrpcprotocol implementation foraiohttp.web.Example serverimportasynciofromaiohttpimportwebfromaiohttp_jrpcimportService,JError,jrpc_errorhandler_middlewareSCH={"type":"object","properties":{"data":{"type":"string"},},}@asyncio.coroutinedefcustom_errorhandler_middleware(app,handler):@asyncio.coroutinedefmiddleware(request):try:return(yield fromhandler(request))exceptException:""" Custom errors: -32000 to -32099 """returnJError().custom(-32000,"Example error")returnmiddlewareclassMyJRPC(Service):@Service.valid(SCH)defhello(self,ctx,data):ifdata["data"]=="hello":return{"status":"hi"}return{"status":data}deferror(self,ctx,data):raiseException("Error which will catch middleware")defno_valid(self,ctx,data):""" Method without validation incommig data """return{"status":"ok"}@asyncio.coroutinedefinit(loop):app=web.Application(loop=loop,middlewares=[jrpc_errorhandler_middleware])#app = web.Application(loop=loop, middlewares=[custom_errorhandler_middleware])app.router.add_route('POST',"/api",MyJRPC)srv=yield fromloop.create_server(app.make_handler(),"127.0.0.1",8080)print("Server started at http://127.0.0.1:8080")returnsrvloop=asyncio.get_event_loop()loop.run_until_complete(init(loop))try:loop.run_forever()exceptKeyboardInterrupt:passExample clientimportasyncioimportaiohttpfromaiohttp_jrpcimportClient,InvalidResponseRemote=Client('http://localhost:8080/api')@asyncio.coroutinedefrpc_call():try:rsp=yield fromRemote.request('hello',{'data':'hello'})returnrspexceptInvalidResponseaserr:returnerrexceptExceptionaserr:returnerrreturnFalseloop=asyncio.get_event_loop()content=loop.run_until_complete(rpc_call())print(content.result)loop.close()Licenseaiohttp_jrpcBSD license.CHANGES0.1.0 (2016-02-20)Added client and testsChanged BSD v3 to BSD v2 license0.0.3 (2015-10-27)Fix messages of protocol errorsFix tests and add tests for custom errorsFix example bugsAdded custom middleware to example for handle errors0.0.2 (2015-10-22)Added middleware to catch exceptionsTesting internal error0.0.1 (2015-10-18)Init releaseCreditsaiohttp_jrpcis written byVeniamin Gvozdikov.Contributorslatyas(懒)Please add yourself here alphabetically when you submit your first pull request.
Package: aiohttp-jsonrpc
JSON-RPC server and client implementation based on aiohttp.Server examplefromaiohttpimportwebfromaiohttp_jsonrpcimporthandlerclassJSONRPCExample(handler.JSONRPCView):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)defrpc_exception(self):raiseException("YEEEEEE!!!")defrpc_test_notification(self):print("Notification received")app=web.Application()app.router.add_route('*','/',JSONRPCExample)if__name__=="__main__":importlogginglogging.basicConfig(level=logging.INFO)web.run_app(app,print=logging.info)Client exampleimportasynciofromaiohttp_jsonrpc.clientimportServerProxyloop=asyncio.get_event_loop()client=ServerProxy("http://127.0.0.1:8080/",loop=loop)asyncdefmain():print(awaitclient.test())# Or via __getitem__method=client['args']notification=client.create_notification("test_notification")print(awaitmethod(1,2,3))awaitnotification()results=awaitclient.batch(client['test'],client['test'].prepare(),client['args'].prepare(1,2,3),client['not_found'].prepare(1,2,3),# notify with paramsnotification.prepare(),# notification without paramsnotification,)print(results)client.close()if__name__=="__main__":loop.run_until_complete(main())
Package: aiohttp-jwt
aiohttp-jwtThe library providesaiohttpmiddleware and helper utils for working with JSON web tokens.Works on Python3.5+MIT LicenseLatest docsTBDContributions are highly welcome!RequirementsAiohttp >= 2.3.5PyJWTInstall$pipinstallaiohttp_jwtSimple Usageserver.pyimportjwtfromaiohttpimportwebfromaiohttp_jwtimportJWTMiddlewaresharable_secret='secret'asyncdefprotected_handler(request):returnweb.json_response({'user':request['payload']})app=web.Application(middlewares=[JWTMiddleware(sharable_secret),])app.router.add_get('/protected',protected_handler)if__name__=='__main__':web.run_app(app)client.pyimportasyncioimportaiohttpimportasync_timeoutasyncdeffetch(session,url,headers=None):asyncwithasync_timeout.timeout(10):asyncwithsession.get(url,headers=headers)asresponse:returnawaitresponse.json()asyncdefmain():asyncwithaiohttp.ClientSession()assession:response=awaitfetch(session,'http://localhost:8080/protected',headers={'Authorization':'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InRlc3QifQ.pyNsXX_vNsUvdt6xu13F1Gs1zGELT4Va8a38eG5svBA'})print(response)loop=asyncio.get_event_loop()loop.run_until_complete(main())ExamplesBasic ExamplePermissions controlCreditsThis module inspired by officialauth0/express-jwtmiddleware andexpress-jwt-permissionsextension.Related packagesFor advanced security facilities checkaio-libs/aiohttp_securityLicenseMIT License
Package: aiohttp-limit
Anaiohttpmiddleware for limiting connections.
Python 3.5+ is required for usage, 3.7+ is required for tests.UsageJust addLimitMiddlewareas a middleware:fromaiohttpimportwebfromaiohttp_limitimportLimitMiddlewareapp=web.Application(middlewares=[LimitMiddleware(requests=10)])This sample usage will restrict requests to 10 per worker.
Package: aiohttp-login
Registration and authorization (including social) for aiohttp appsWith just a few settings you’ll give for youraiohttpsite:registration with email confirmationauthorization by email or social account (facebook, google and
vkontakte for now)reset password by emailchange email with confirmationedit current passwordYou can see all of this staff alivehereDatabasesYou can use this lib with different database backends:postgres withasyncpgmongodb withmotorthe db you need -it’s very easy to add a new backendUI themesThe library designed to easily change UI themes. Currentlybootstrap-3andbootstrap-4themes are available. But it’s very
easy to add new themes, actually theme - is just a folder with jinja2
templates.Installation and configurationJust install the library from pypi:pip install aiohttp-loginChoice and configure one of database storages.For postgres withasyncpg:importasyncpgfromaiohttp_login.asyncpg_storageimportAsyncpgStoragepool=awaitasyncpg.create_pool(dsn='postgres:///your_db')storage=AsyncpgStorage(pool)For mongodb withmotor:frommotor.motor_asyncioimportAsyncIOMotorClientfromaiohttp_login.motor_storageimportMotorStoragedb=AsyncIOMotorClient(io_loop=loop)['your_db']storage=MotorStorage(db)Now configure the library with a few settings:app=web.Application(loop=loop)app.middlewares.append(aiohttp_login.flash.middleware)aiohttp_jinja2.setup(app,loader=jinja_app_loader.Loader(),context_processors=[aiohttp_login.flash.context_processor],)aiohttp_login.setup(app,storage,{'CSRF_SECRET':'secret','VKONTAKTE_ID':'your-id','VKONTAKTE_SECRET':'your-secret','GOOGLE_ID':'your-id','GOOGLE_SECRET':'your-secret','FACEBOOK_ID':'your-id','FACEBOOK_SECRET':'your-secret','SMTP_SENDER':'Your Name <your@gmail.com>','SMTP_HOST':'smtp.gmail.com','SMTP_PORT':465,'SMTP_USERNAME':'your@gmail.com','SMTP_PASSWORD':'password'})That’s all. Look at thelive
exampleand its code in theexamplefolder. Full list of available settings you can find inaiohttp_login/cfg.pyfile.Run the exampleCreate a virtual environment and install the dependencies:cd example
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txtCreate postgres database and tables:createdb aiohttp_login
psql -d aiohttp_login -f ../aiohttp_login/pg_tables.sqlRenamesettings.py.templatetosettings.pyand populate it with
real data.Run the server:python app.pyRun testspip install -r requirements-dev.txt
py.test
Package: aiohttp-login-jwt
This fork of imbolc/aiohttp-login is developed for the based onJWTtokens registration and login procedures.Moreover, the following options are added into thecfg.pyfor the
contained in JWT roles: -"ROLES_API_BLACK_LIST": {}- for the
configuration of forbiden endpoints for certain roles; -"ROLES_API_LIMITS": {}- for the configuration of API calls
limits for certain roles; -"CACHE"- Redis or KeyDB object for
calls counting (cache storage) (defaultNonethat means no
restrictions); -"API_CALL_LIMIT_EXPIRATION_TIME"- time interval
in minutes within which number calls should be restricted (default60).aiohttp-loginRegistration and authorization (including social) for aiohttp appsWith just a few settings you’ll give for youraiohttpsite:registration with email confirmationauthorization by email or social account (facebook, google and
vkontakte for now)reset password by emailchange email with confirmationedit current passwordYou can see all of this staff alivehereDatabasesYou can use this lib with different database backends:postgres withasyncpgmongodb withmotorthe db you need -it’s very easy to add a new backendUI themesThe library designed to easily change UI themes. Currentlybootstrap-3andbootstrap-4themes are available. But it’s very
easy to add new themes, actually theme - is just a folder with jinja2
templates.Installation and configurationJust install the library from pypi:pip install aiohttp-loginChoice and configure one of database storages.For postgres withasyncpg:importasyncpgfromaiohttp_login.asyncpg_storageimportAsyncpgStoragepool=awaitasyncpg.create_pool(dsn='postgres:///your_db')storage=AsyncpgStorage(pool)For mongodb withmotor:frommotor.motor_asyncioimportAsyncIOMotorClientfromaiohttp_login.motor_storageimportMotorStoragedb=AsyncIOMotorClient(io_loop=loop)['your_db']storage=MotorStorage(db)Now configure the library with a few settings:app=web.Application(loop=loop)app.middlewares.append(aiohttp_login.flash.middleware)aiohttp_jinja2.setup(app,loader=jinja_app_loader.Loader(),context_processors=[aiohttp_login.flash.context_processor],)aiohttp_login.setup(app,storage,{'CSRF_SECRET':'secret','VKONTAKTE_ID':'your-id','VKONTAKTE_SECRET':'your-secret','GOOGLE_ID':'your-id','GOOGLE_SECRET':'your-secret','FACEBOOK_ID':'your-id','FACEBOOK_SECRET':'your-secret','SMTP_SENDER':'Your Name <your@gmail.com>','SMTP_HOST':'smtp.gmail.com','SMTP_PORT':465,'SMTP_USERNAME':'your@gmail.com','SMTP_PASSWORD':'password'})That’s all. Look at the code in theexamplefolder. Full list of available settings you can find inaiohttp_login/cfg.pyfile.Run the exampleCreate a virtual environment and install the dependencies:cd example
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txtCreate postgres database and tables:createdb aiohttp_login
psql -d aiohttp_login -f ../aiohttp_login/pg_tables.sqlRenamesettings.py.templatetosettings.pyand populate it with
real data.Run the server:python app.pyRun testspip install -r requirements-dev.txt
py.test
Package: aiohttp-middlewares
Collection of useful middlewares foraiohttp.webapplications.Works onPython3.7+Works withaiohttp.web3.8.1+BSD licensedLatest documentationon Read The DocsSource, issues, and pull requestson GitHubQuick StartBy defaultaiohttp.webdoes not providemany built-in middlewaresfor
standart web-development needs such as: handling errors, shielding view
handlers, or providing CORS headers.aiohttp-middlewarestries to fix this by providing several middlewares that
aims to cover most common web-development needs.For example, to enable CORS headers forhttp://localhost:8081origin and
handle errors foraiohttp.webapplication you need to,fromaiohttpimportwebfromaiohttp_middlewaresimport(cors_middleware,error_middleware,)app=web.Application(middlewares=(cors_middleware(origins=("http://localhost:8081",)),error_middleware(),))Checkdocumentationfor
all available middlewares and available initialization options.
Package: aiohttp-msal
aiohttp_msal Python libraryAuthorization Code Flow Helper. Learn more about auth-code-flow athttps://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flowAsync based OAuth using the Microsoft Authentication Library (MSAL) for Python.Blocking MSAL functions are executed in the executor thread.
Should be useful until such time as MSAL Python gets a true async version.Tested with MSAL Python 1.21.0 onward -MSAL Python docsAsycMSAL classThe AsyncMSAL class wraps the behavior in the following example apphttps://github.com/Azure-Samples/ms-identity-python-webapp/blob/master/app.py#L76It is responsible to manage tokens & token refreshes and as a client to retrieve data using these tokens.Acquire the tokenFirstly you should get the tokens via OAuthinitiate_auth_code_flowreferernceThe caller is expected to:somehow store this content, typically inside the current session of the server,guide the end user (i.e. resource owner) to visit that auth_uri, typically with a redirectand then relay this dict and subsequent auth response to
acquire_token_by_auth_code_flow().Step 1and part ofStep 3is stored by this class in the aiohttp_sessionacquire_token_by_auth_code_flowreferernceUse the tokenNow you are free to make requests (typically from an aiohttp server)session=awaitget_session(request)aiomsal=AsyncMSAL(session)asyncwithaiomsal.get("https://graph.microsoft.com/v1.0/me")asres:res=awaitres.json()Example web serverComplete routes can be found inroutes.pyStart the login process@ROUTES.get("/user/login")asyncdefuser_login(request:web.Request)->web.Response:"""Redirect to MS login page."""session=awaitnew_session(request)redir=AsyncMSAL(session).build_auth_code_flow(redirect_uri=get_route(request,URI_USER_AUTHORIZED))returnweb.HTTPFound(redir)Acquire the token after being redirected back to the server@ROUTES.post(URI_USER_AUTHORIZED)asyncdefuser_authorized(request:web.Request)->web.Response:"""Complete the auth code flow."""session=awaitget_session(request)auth_response=dict(awaitrequest.post())aiomsal=AsyncMSAL(session)awaitaiomsal.async_acquire_token_by_auth_code_flow(auth_response)Helper methods@ROUTES.get("/user/photo")Serve the user's photo from their Microsoft profileget_user_infoGet the user's email and display name from MS Graphget_manager_infoGet the user's manager info from MS GraphRedis tools to retrieve session tokensfromaiohttp_msalimportENV,AsyncMSALfromaiohttp_msal.redis_toolsimportget_sessiondefmain()# Uses the redis.asyncio driver to retrieve the current token# Will update the token_cache if a RefreshToken was usedases=asyncio.run(get_session(MYEMAIL))client=GraphClient(ases.get_token)# ...# use the Graphclient
Package: aiohttp-oauth2
aiohttp-oauth2A provider agnostic oauth2 client library for aiohttp, implemented as a self-composed nested application.No opinions about auth mechanisms are enforced on the application, anon_loginandon_errorcoroutine can, and should, be provided to implement your own login mechanisms (token, session, etc).Usage$pipinstall-Uaiohttp_oauth2Simplefromaiohttpimportwebfromaiohttp_oauth2importoauth2_appasyncdefapp_factory():app=web.Application()app.add_subapp("/github/",# any arbitrary prefixoauth2_app(client_id=123,client_secret=456,authorize_url="https://github.com/login/oauth/authorize",token_url="https://github.com/login/oauth/access_token",# add scopes if you want to customize themscopes=["foo","bar","baz"],# optionally add an on_login coroutine to handle the post-login logic# it should expect the request and the oauth2 access code responseon_login=set_session_and_redirect,on_error=show_error_page,),)returnappThe necessary oauth2 routes are added as/authand/callback. Now logging in a user is as simple as redirecting them to:/github/auth.ComplexSince theoauth2_appfunction is simply a factory that generates sub-apps, you can use this to add any number of oauth2 providers to log in against:fromaiohttpimportwebfromaiohttp_oauth2importoauth2_appasyncdefapp_factory()->web.Application:app=web.Application()app.add_subapp("/github/",oauth2_app(...,authorize_url="https://github.com/login/oauth/authorize",token_url="https://github.com/login/oauth/access_token",))app.add_subapp("/google/",oauth2_app(...,authorize_url="https://accounts.google.com/o/oauth2/v2/auth",token_url="https://www.googleapis.com/oauth2/v4/token",))app.add_subapp("/twitter/",oauth2_app(...,authorize_url="https://api.twitter.com/oauth/authorize",token_url="https://api.twitter.com/oauth2/token",))...returnappYou can now redirect users to/twitter/auth,/google/auth, and/github/auth.As a nice shortcut to the boilerplate of the authorize/token URLs, see theaiohttp_oauth2/client/contrib.pyhelpers to avoid needing to set the urls explicity.importosfromaiohttpimportwebfromaiohttp_oauth2.client.contribimportgithubasyncdefapp_factory()->web.Application:app=web.Application()app.add_subapp("/login/github",github(os.getenv("CLIENT_ID"),os.getenv("CLIENT_SECRET"),),)# and/or `google`, `slack`, `twitter` instead of `github`returnappExamplesCheck the "examples" directory for working examples:$ cd examples
$ pip install -r requirements.txt

# this just makes the library available for import, don't typically do it :D
$ PYTHONPATH=".." python github.pyTipsIncorrect URL scheme (missinghttps)Foraiohttp's URL resolution feature to work with SSL, be sure to useaiohttp-remotes. This will ensure that if you are serving your aiohttp application behind any termination point for TLS that aiohttp is still aware via the various forwarding headers that traefik/nginx/etc should set.