Saravanan666/pypi-org huggingface dataset:
Package: aiohttp-clean-jwt
aiohttp-clean-jwtПростая аутентификация по JWT-токену для aiohttpИсточник вдохновения -aiohttp-jwtК сожалению, оригинальная библиотека плохо документирована, перегружена малопонятным функционалом и уже несколько лет выглядит заброшенной.Установка:pip install aiohttp_clean_jwtПример использования:fromaiohttpimportwebfromaiohttp.webimportApplication,Request,Responsefromaiohttp_clean_jwtimportget_token,json_response,middleware_factoryJWT_SECRET='top_secret_word'JWT_ALGORITHM='HS256'JWT_EXP_DELTA_SECONDS=360JWT_AUTH_SCHEME='Bearer'asyncdefget_user_id(login:str,password:str)->int:""" Проверка ID пользователя. В реальном приложении должна сходить в базу."""iflogin=='vasya'andpassword=='qwerty':return12345asyncdefsign_in(request:Request)->Response:""" Ручка авторизации """try:login=request.rel_url.query['login']password=request.rel_url.query['password']exceptKeyError:raiseweb.HTTPUnauthorized(reason='Missing credentials')user_id=awaitget_user_id(login=login,password=password)ifuser_idisnotNone:jwt_token=get_token({'user_id':str(user_id)},expiration_s=JWT_EXP_DELTA_SECONDS,algorithm=JWT_ALGORITHM,secret=JWT_SECRET)returnjson_response({'token':jwt_token})else:raiseweb.HTTPUnauthorized(reason='Wrong credentials')# Все ручки по умолчанию считаются приватными.# Чтобы сделать ручку публичной, ее нужно явным образом перечислить в whitelist.# Для доступа к приватным ручкам необходимо передавать полученный в /login токен через# HTTP HEADER "Authorization: Bearer"asyncdefstub1(request:Request)->Response:""" Приватная ручка 1"""user_id=request.rel_url.query['user_id']result={'user_id':user_id,'handler':'stub1'}returnjson_response(result)asyncdefstub2(request:Request)->Response:""" Приватная ручка 2"""user_id=request.rel_url.query['user_id']result={'user_id':user_id,'handler':'stub2'}returnjson_response(result)asyncdefpublic(request:Request)->Response:""" Публичная ручка"""result={'user_id':'anonymous','handler':'public'}returnjson_response(result)if__name__=='__main__':app=Application(middlewares=middleware_factory(whitelist=['/login','/public'],secret=JWT_SECRET,algorithm=JWT_ALGORITHM,auth_scheme=JWT_AUTH_SCHEME,))app.add_routes([web.get('/login',sign_in),web.get('/public',public),web.get('/stub1',stub1),web.get('/stub2',stub2)])web.run_app(app=app)
Package: aiohttp-client-cache
aiohttp-client-cacheaiohttp-client-cacheis an async persistent cache foraiohttpclient requests, based onrequests-cache.FeaturesEase of use:Use as adrop-in replacementforaiohttp.ClientSessionCustomization:Works out of the box with little to no config, but with plenty of options
available for customizing cacheexpirationand otherbehaviorPersistence:Includes severalstorage backends:
SQLite, DynamoDB, MongoDB, DragonflyDB and Redis.QuickstartFirst, install with pip (python 3.8+ required):pipinstallaiohttp-client-cache[all]Note:Adding[all]will install optional dependencies for all supported backends. When adding this
library to your application, you can include only the dependencies you actually need; see individual
backend docs andpyproject.tomlfor details.Basic UsageNext, useaiohttp_client_cache.CachedSessionin place ofaiohttp.ClientSession.
To briefly demonstrate how to use it:Replace this:fromaiohttpimportClientSessionasyncwithClientSession()assession:awaitsession.get('http://httpbin.org/delay/1')With this:fromaiohttp_client_cacheimportCachedSession,SQLiteBackendasyncwithCachedSession(cache=SQLiteBackend('demo_cache'))assession:awaitsession.get('http://httpbin.org/delay/1')The URL in this example adds a delay of 1 second, simulating a slow or rate-limited website.
With caching, the response will be fetched once, saved todemo_cache.sqlite, and subsequent
requests will return the cached response near-instantly.ConfigurationSeveral options are available to customize caching behavior. This example demonstrates a few of them:# fmt: offfromaiohttp_client_cacheimportSQLiteBackendcache=SQLiteBackend(cache_name='~/.cache/aiohttp-requests.db',# For SQLite, this will be used as the filenameexpire_after=60*60,# By default, cached responses expire in an hoururls_expire_after={'*.fillmurray.com':-1},# Requests for any subdomain on this site will never expireallowed_codes=(200,418),# Cache responses with these status codesallowed_methods=['GET','POST'],# Cache requests with these HTTP methodsinclude_headers=True,# Cache requests with different headers separatelyignored_params=['auth_token'],# Keep using the cached response even if this param changestimeout=2.5,# Connection timeout for SQLite backend)More InfoTo learn more, see:User GuideCache BackendsAPI ReferenceExamplesFeedbackIf there is a feature you want, if you've discovered a bug, or if you have other general feedback, pleasecreate an issuefor it!
Package: aiohttp-client-manager
A module to automatically manageaiohttp.ClientSessionobjects for you
to improve performance.The package manages a global cache ofaiohttp.ClientSessionobjects based
on the host a particular request is connecting to so connections can be
reused between requests.It also simplifies the API.UsageThe usage is similar to the pythonrequestslibrary:import aiohttp_client
async with aiohttp_client.get('http://www.google.com') as resp:
    # do something hereConfigurationUses env variables to configure max number of reqeusts/sessions to manage:AIOHTTP_SESSION_SIZE: max number of sessions to keep in cache(default 200)AIOHTTP_SESSION_DNS_CACHE: number of seconds to keep dns lookup in cache(default 20)AIOHTTP_SESSION_LIMIT: number of simultaneous connections to have per session(default 500)1.1.2 (2022-10-20)Change to bsd license1.1.1 (2020-04-15)better session connector defaults1.1.0 (2019-06-06)update max requests and sessionsUpdated setup.py to point to aihttp_client.py1.0.0 (2018-04-09)initial release
Package: aiohttp-client-rate-limiter
aiohttp_client_rate_limiterThis is a mini tool that overwrites ClientSession class from aiohttp (https://pypi.org/project/aiohttp/). This subclass introduces rate limter functionality while leaving all the other parent behaviors untouched.Example:importasynciofromaiohttp_client_rate_limiter.ClientSessionimportRateLimitedClientSessionrl_session=RateLimitedClientSession(max_concur=5,reqs_per_period=10,period_in_secs=60)tasks=[asyncio.create_task(rl_session.get(f"https://www.google.com/?q={i}",ssl=False))foriinrange(10)]awaitasyncio.gather(*tasks)awaitrl_session.close()Or, we could simply do this, using the native context manager as provided by aiohttp:importasynciofromaiohttp_client_rate_limiter.ClientSessionimportRateLimitedClientSessionasyncwithRateLimitedClientSession(max_concur=60,reqs_per_period=5,period_in_secs=10)asrl_session:tasks=[asyncio.create_task(rl_session.get(f"https://www.google.com/?q={i}",ssl=False))foriinrange(10)]awaitasyncio.gather(*tasks)The above example could provide a steady rate of 10 requests/60 seconds at the maximum concurrency of 5.
Package: aiohttp-compress
aiohttp-compressThis module is the simplest way to enable compression support foraiohttpserver applications globally.Installationpipinstallaiohttp-compressExamplefromaiohttpimportwebfromaiohttp_compressimportcompress_middlewareasyncdefhandle(request):name=request.match_info.get('name',"Anonymous")text="Hello, "+namereturnweb.Response(text=text)app=web.Application()app.middlewares.append(compress_middleware)app.add_routes([web.get('/',handle),web.get('/{name}',handle)])if__name__=='__main__':web.run_app(app)
Package: aiohttp-datadog
Anaiohttpmiddleware for reporting metrics toDatadog. Python 3.5+ is required.Usagefromaiohttpimportwebfromaiohttp_datadogimportDatadogMiddlewareapp=web.Application(middlewares=(DatadogMiddleware("my_app",{"host":"localhost","port":8126},),),)If you’re using a custom DogStatsd class,
you can supply it via a keyword argument:app=web.Application(middlewares=(DatadogMiddleware("my_app",{"host":"localhost","port":8126},dogstatsd_class=CatStatsd,),),)Or if you’re even more of a control freak,
you can instantiate it yourself:app=web.Application(middlewares=(DatadogMiddleware("my_app",dogstatsd_instance=CatStatsd(meow=False),),),)
Package: aiohttp-debugmode
aiohttp-debugmodeThis package helps you easily start a aiohttp develpment server in subprocess ,everytime dependencies/statics are modified ,daemon process will automatically reload server thus helps you automation your workflow. Aiohttp-debugtoolbar included.Based on watchdog.Works on Python3.7+aiohttp-debugtoolbarincluded ,thus you can get a full report of traceback if exception raised.(* Screenshot fromaio-libs/aiohttp-debugtoolbar*)Installpip install aiohttp-debugmodeUsagequick_start.py# here's a demo script from aiohttp.doc\quickstartfromaiohttpimportwebroutes=web.RouteTableDef()@routes.get('/')asyncdefhello(request):returnweb.Response(text="Hello, world")app=web.Application()app.add_routes(routes)web.run_app(app)Simply modify severl lines like this# Add importfromaiohttp_debugmodeimportDebugmode# Let Debugmode take over control of run_appDebugmode.run_app(app)By default ,templates&staticfloder is added to observing list of watchdog. You can manually set observe file/floder using append_observe.Debugmode.append_observe(['other/login.html','assets'])If you need some kind of process when a aiohttp server starts up:defstup():...# do somethingDebugmode.on_startup(stup)# accepts callable.Examplesaiohttp-debugmode with VueAssume that you are usiung vue-cli and have a directory structure like this:...
├── Project
│   ├── static
│   ├── templates
│   ├── app.py               # aiohttp app entry
│   └── frontend             # vue frontend folder
│       ├── dist             # webpack output directory
│       │   ├── css
│       │   ├── js
│       │   └── index.html
│       ├── node_modules
│       │   └── ...
│       ├── src              # vue source
│       │   └── ...
│       └── vue.config.js
│   └── ...Assume that webpack outputs built file into/Project/frontend/distfloder while your aiohttp app collects templates & statics from/Project/templates&/Project/staticfolder.Here's a sample code:fromaiohttpimportwebfromaiohttp_debugmodeimportDebugmodeimportaiohttp_jinja2# Pretended doing some tempate rander stuff.# @aiohttp_jinja2.template('index.html')asyncdefhello(request):returnweb.Response(text="Randered.")# Debugtoolbar included thus you can get# a full report of traceback.asyncdeferror(request):raiseException('Testing.')app=web.Application()app.router.add_route('GET','/',hello)app.router.add_route('GET','/err',error)app.add_routes([web.static('/','static')])definitialize():importshutil,os,glob# You may use os.path.abspath to get absolute path in some situation.ifos.path.exists('frontend\dist\index.html'):shutil.move('frontend\dist\index.html','templates')try:shutil.rmtree(filepath)os.mkdir(filepath)forfilepathinglob.glob('frontend\dist\*'):shutil.move(filepath,'static')exceptExceptionase:raiseeDebugmode.append_observe(['frontend\dist'])# backslashes on windows.Debugmode.on_startup(initialize)# Debugmode takes over run_app instead of web.run_appDebugmode.run_app(app,host='127.0.0.1',port=8080)Thus every time you runnpm run build,debugmode will catch file modified event ,init file directory and restart aiohttp server with new generated html/js/css file.
Package: aiohttp-doh
DNS over HTTPS reslover for aiohttpInstallation$pipinstallaiohttp-dohManual UsageIf you want use manualy, you must importClientSessioninaiohttp.clientmodule andTCPConnectorinaiohttp.connectormodule andDNSOverHTTPSResolverinaiohttp_dohpackage.fromaiohttp.clientimportClientSessionfromaiohttp.connectorimportTCPConnectorfromaiohttp_dohimportDNSOverHTTPSResolverdefmy_client_session(*args,**kwargs):resolver=DNSOverHTTPSResolver(endpoints=['https://cloudflare-dns.com/dns-query',])connector=TCPConnector(resolver=resolver)returnClientSession(*args,**kwargs,connector=connector)asyncdefmain():asyncwithmy_client_session()assession:asyncwithsession.get('http://example.com')asresp:data=awaitresp.text()print(data)ShortcutManual usage is too board. So I make shortcut to use easily.
You just replaceaiohttp.ClientSessiontoaiohttp_doh.ClientSession.fromaiohttp_dohimportClientSessionasyncdefmain():asyncwithClientSession()assession:asyncwithsession.get('http://example.com')asresp:data=awaitresp.text()print(data)OptionsYou can pass below parameter for configuration.endpointsList of str. DNS over HTTPS endpoints.
Shortcut use‘https://dns.google.com/resolve’and‘https://cloudflare-dns.com/dns-query’both in default.
You can also use others instead.json_loadsFunction for loads json. default is Python builtin json module’s one.
You can use third-party json library like simplejson or ujson.resolver_classInternal DNS resolver class. Using for connect to endpoint.
default is aiohttp default.LicenseMIT
Package: aiohttp-etag
The library provides Etag support foraiohttp.web.Most of the source code is ported fromTornado.InstallationInstall from PyPI:pip install aiohttp-etagDevelopingInstall requirement and launch tests:pip install -r dev-requirements.txt
pytest testsUsageA trivial usage example:importasyncioimporttimeimportaiohttp_etagfromaiohttpimportwebasyncdefhome(request):last_visit=time.time()text='Last visited:{}'.format(last_visit)returnweb.Response(text=text)asyncdefresource(request):last_visit=time.time()returnweb.json_response({'last_visit':last_visit,})asyncdefmake_app():app=web.Application()aiohttp_etag.setup(app)app.router.add_get('/',home)app.router.add_get('/resource',resource)returnappweb.run_app(make_app())
Package: aiohttp_exc_handlers
Usageimportasynciofromaiohttpimportwebfromaiohttp_exc_handlersimport(exc_handlers_middleware,bind_exc_handler,)classCustomException(Exception):passasyncdefcustom_exception_handler(request,exc):returnweb.Response(text="Hello,{!s}!".format(exc))asyncdefhello(request):raiseCustomException('world')# add middlewareapp=web.Application(middlewares=[exc_handlers_middleware])# bind handler to exceptionbind_exc_handler(app,CustomException,custom_exception_handler)app.router.add_route('GET','/',hello)loop=asyncio.get_event_loop()handler=app.make_handler()f=loop.create_server(handler,'0.0.0.0',8080)srv=loop.run_until_complete(f)try:loop.run_forever()exceptKeyboardInterrupt:passfinally:loop.run_until_complete(handler.finish_connections(1.0))srv.close()loop.run_until_complete(srv.wait_closed())loop.run_until_complete(app.finish())loop.close()Tests$pipinstallpytest$py.testtests.py
Package: aiohttp-ext.auth
# Расширение aiohttp для управления процессом авторизации пользователей в системе## Краткое описание функционала расширенияДанное расширение представляет из себя специализированный middleware производящий
проверку заголовков запроса и производящий по результатам авторизацию (а в некоторых случаях
и аутентификацию тоже) пользователяУспешная аутентификация заканчиваются установкой ключа ‘user’ экземпляра запроса (request).
Значением ключа ‘user’, в этом случае, выступает экземпляра класса ORM Gino соответствующий
профилю авторизованного пользователя.В случае провальной авторизации ключ ‘user’ приобретает значение None### Кастомный профиль пользователя
Расширение определеяет порофиль пользователя самостоятельно, но способно работать и с кастомным профилем
определенным на уровне приложения. Для этого следует указать класс профиля (это обязательно должен быть
класс ORM Gino) в настройках, в ключе ‘user_model’ (см. демо-приложение, находящееся в под-каталоге demo/ )### Бакэенды аутентификации
Расширение реализует различные способы авторизации пользователя путем подключения т. н. бакэндов
авторизации, каждый из которых представляет из себя класс, наследующий от абстрактного
класса AuthorizationBackendРасширение несет в себе два такаих бакэенда: бакэнд базовой аутентификации и бакэенд аутентификации
Bearer (терехногая аутентифкация с использованием JWT-токена)Расширение не накладывает ограничений на количество подключенных бакэендов аутентифкации: любое их
количество может быть включено в список ключа auth_backends настроек приложения. Расширение будет пытаться
авторизовать пользователя в порядке перечисленных бакэендов и прекращает попытки при первом успешном
результате### ДекораторыРасширение несет с собой два декоратора. Первый из них - authorization_required применяется в общем случае,
для декорирования обработчика ответа сервера, для гарантии что обработчик будет работать только с
авторизованным запросом. Второй декоратор, - bearer_authorization_required - устроен сложнее.Так же как и декоратор authorization_required, декоратор bearer_authorization_required применяется
в случае необходимости получения гарантии того, что обработчик запроса к серверу будет работать
с авторизованным запросом, но кроме этого этот декоратор способен обрабатывать ошибки декодирования и
проверки токена и отдавать их в качестве причины отказа в авторизации на ресурсе. Кроме того, в заголовок
ответа данный декоратор добавляет ключ www-authenticate, в котором указывает realm, service и scope
необходимые клиенту для получения Bearer-токена в доверенном центре авторизации. Реалм центра
авторизации является обязательным параметром, два других - опциональны.## УстановкаУстановка расширения производится с помощью менеджера pip`bash pip install aiohttp_ext.auth `## Использованиесм. демо-приложение, находящееся в под-каталоге demo/
Package: aiohttp-extracts
aiohttp-extractsThis library allows you to extract variable number of request parameters to a handler's arguments.
It uses type hints to determine where each value must be extracted from.For exampleWith aiohttp-extracts:fromaiohttpimportwebfromaiohttp_extractsimportwith_extractionfromaiohttp_extractsimportRequestAttr,MatchInfo,QueryAttrroutes=web.RouteTableDef()@routes.get(r'/chats/{chat_id:(\d+)}/')@with_extractionasyncdefhandler(user:RequestAttr[int],# by default it uses argument namechat:MatchInfo['chat_id',int],# but you can specify name what you wantoffset:QueryAttr[int]=0,# and you can simply set a default valuecount:QueryAttr[int]=100)->web.Response:...Without aiohttp-extracts:fromaiohttpimportwebfromaiohttp_extractsimportwith_extractionroutes=web.RouteTableDef()@routes.get(r'/chats/{chat_id:(\d+)}/')asyncdefhandler(request:web.Request):user=request.get('user')chat=request.match_info.get('chat_id')offset=request.query.get('offset',0)count=request.query.get('count',100))->web.Response:...InstallationInstallation process as simple as:$ pip install aiohttp-extractsUsageFirst we need to set a middleware to app.fromaiohttpimportwebfromaioservertimingimportserver_timing_mwareapp=web.Applicalion(middlewares=[server_timing_mware])Usual handlerfromaiohttpimportwebfromaiohttp_extractsimportwith_extractionfromaiohttp_extractsimportRequestAttr,MatchInfo,QueryAttr@with_extractionasyncdefhandler(user:RequestAttr[int],chat:MatchInfo['chat_id',int],offset:QueryAttr[int]=0,count:QueryAttr[int]=100)->web.Response:...ClassviewWith decoratorfromaiohttpimportwebfromaiohttp_extractsimportwith_extractionfromaiohttp_extractsimportRequestAttr,MatchInfo,QueryAttr@extract_classviewclassChatView(web.View):asyncdefget(user:RequestAttr[int],chat:MatchInfo['chat_id',int],offset:QueryAttr[int]=0,count:QueryAttr[int]=100)->web.Response:...With metaclassfromaiohttpimportwebfromaiohttp_extractsimportExtractionMetafromaiohttp_extractsimportRequestAttr,MatchInfo,QueryAttrclassChatView(web.View,metaclass=ExtractionMeta):asyncdefget(user:RequestAttr[int],chat:MatchInfo['chat_id',int],offset:QueryAttr[int]=0,count:QueryAttr[int]=100)->web.Response:...Types that can be used in handlers argsType nameWhat it replacesAdditional infoaiohttp.web.RequestrequestUsually request objectaiohttp_extracts.RequestAttrrequest.get(...)Any request attributeaiohttp_extracts.MatchInforequest.match_info.get(...)aiohttp_extracts.QueryAttrrequest.query.get(...)aiohttp_extracts.Headerrequest.headers.get(...)aiohttp_extracts.Cookierequest.cookies.get(...)aiohttp_extracts.JSONBodyawait request.json()LinksThis library onPyPI
Package: aiohttp-fast-url-dispatcher
aiohttp-fast-url-dispatcherDocumentation:https://aiohttp-fast-url-dispatcher.readthedocs.ioSource Code:https://github.com/bdraco/aiohttp-fast-url-dispatcherA faster URL dispatcher for aiohttpThe defaultUrlDispatcherimplementation does a linear search every which can have a significantTimeComplexitywhen dispatching urls when there are a lot of routes.FastUrlDispatcherkeeps an index of the urls which allows for fast dispatch.This library will become obsolete with aiohttp 3.10 as the changes
are expected to merge upstream viahttps://github.com/aio-libs/aiohttp/pull/7829InstallationInstall this via pip (or your favourite package manager):pip install aiohttp-fast-url-dispatcherUsageAttach to aweb.Applicationbefore any resources are registered.dispatcher=FastUrlDispatcher()app=web.Application()attach_fast_url_dispatcher(app,dispatcher)Create with a newweb.Applicationdispatcher=FastUrlDispatcher()app=web.Application(router=dispatcher)CaveatsIf you have multiple handlers that resolve to the same URL, this module will always prefer the static name over a dynamic name. For example:app.router.add_get(r"/second/{user}/info",handler)app.router.add_get("/second/bob/info",handler)"/second/bob/info"will always be matched beforer"/second/{user}/info"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: aiohttp-flashbag
The library provides flashbag foraiohttp.web.UsageThe library allows us to share some data between requests inside session.Basic usage example:importaiohttp_flashbagfromaiohttpimportwebfromaiohttp_sessionimportsetupassetup_sessionfromaiohttp_sessionimportSimpleCookieStorageasyncdefhandler_get(request):validation_error=aiohttp_flashbag.flashbag_get(request,'error')error_html=''ifvalidation_errorisnotNone:error_html='<span>{validation_error}</span>'.format(validation_error=validation_error,)body='''
        <html>
            <head><title>aiohttp_flashbag demo</title></head>
            <body>
                <form method="POST" action="/">
                    <input type="text" name="name" />{error_html}<input type="submit" value="Say hello">
                </form>
            </body>
        </html>
    '''body=body.format(error_html=error_html)returnweb.Response(body=body.encode('utf-8'),content_type='text/html')asyncdefhandler_post(request):post=awaitrequest.post()iflen(post['name'])==0:aiohttp_flashbag.flashbag_set(request,'error','Name is required')returnweb.HTTPSeeOther('/')body='Hello,{name}'.format(name=post['name'])returnweb.Response(body=body.encode('utf-8'),content_type='text/html')defmake_app():session_storage=SimpleCookieStorage()app=web.Application()setup_session(app,session_storage)app.middlewares.append(aiohttp_flashbag.flashbag_middleware)app.router.add_route('GET','/',handler_get,)app.router.add_route('POST','/',handler_post,)returnappweb.run_app(make_app())First of all, you have to registeraiohttp_flashbag.flashbag_middlewareinaiohttp.web.Application.You can get some data from the previous request withaiohttp_flashbag.flashbag_getmethod. Parameters:request. Instance ofaiohttp.web_request.Request.key. Name of “variable” that you want to getdefault. The default value that should be returned, if the key doesn’t exist in session flashbag.To set one “variable” in flashbag you should useaiohttp_flashbag.flashbag_set. Parameters:request. Instance ofaiohttp.web_request.Request.key. Name of “variable” that you want to specify.value. Data that you want to specify.If you need to replace all “variables” in flashbag you should useaiohttp_flashbag.flashbag_replace_all. Parameters:request. Instance ofaiohttp.web_request.Request.value. Dict with values that you want to add into flashbag.