package
stringlengths
1
122
pacakge-description
stringlengths
0
1.3M
aiohttp-devtools
Dev tools foraiohttp.aiohttp-devtoolsprovides a number of tools useful when developing applications with aiohttp and associated libraries.Installationpipinstallaiohttp-devtoolsUsageTheaiohttp-devtoolsCLI (and it’s shorter aliasadev) consist of two sub-commands:runserverandserve.runserverProvides a simple local server for running your application while you’re developing.Usage is simplyadevrunserver<app-path>Note:adev runserver<app-path>will import the whole file, hence it doesn’t work withweb.run_app(app). You can however useif __name__ == '__main__': web.run_app(app).app-pathcan be a path to either a directory containing a recognized default file (app.pyormain.py) or to a specific file. The--app-factoryoption can be used to define which method is called from the app path file, if not supplied some default method names are tried (namelyapp,app_factory,get_appandcreate_app, which can be variables, functions, or coroutines).Allrunserverarguments can be set via environment variables.runserverhas a few useful features:livereloadwill reload resources in the browser as your code changes without having to hit refresh, seelivereloadfor more details.static filesare served separately from your main app (generally on8001while your app is on8000) so you don’t have to contaminate your application to serve static files you only need locally.For more options seeadev runserver--help.serveSimilar torunserverexcept just serves static files.Usage is simplyadevserve<path-to-directory-to-serve>Likerunserveryou get nice live reloading and access logs. For more options seeadev serve--help.TutorialTo demonstrate what adev can do when combined with create-aio-app, let’s walk through creating a new application:First let’s create a clean python environment to work in and install aiohttp-devtools and create-aio-app.(it is assumed you’ve already gotpython,pipandvirtualenvinstalled)mkdirmy_new_app&&cdmy_new_appvirtualenv-p`whichpython3`env.env/bin/activatepipinstallaiohttp-devtoolscreate-aio-appWe’re now ready to build our new application withcreate-aio-appand we’ll name the projectmy_new_appafter the current directory.We’re going to explicitly choose no database here to make this tutorial easier, but you can remove that option and choose to use a proper database if you like.You can just hit return to choose the default for all the options.create-aio-appmy_new_app--without-postgresThat’s it, your app is now created. You might want to have a look through the local directory’s file tree.Before you can run your app you’ll need to install the other requirements, luckily they’ve already been listed inrequirements/development.txtbycreate-aio-app, to install simply runpipinstall-rrequirements/development.txtYou can then run your app with just:adevrunserverWith that:your app should be being served atlocalhost:8000(you can go and play with it in a browser).Your static files are being served atlocalhost:8001, adev has configured your app to know that so it should be rendering properly.any changes to your app’s code (.pyfiles) should cause the server to reload, changes to any files (.pyas well as.jinja,.js,.cssetc.) will cause livereload to prompt your browser to reload the required pages.That’s it, go develop.
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
aiohttp-dynamic
No description available on PyPI.
aiohttp-edit
Async http client/server frameworkKey FeaturesSupports both client and server side of HTTP protocol.Supports both client and server Web-Sockets out-of-the-box and avoids Callback Hell.Provides Web-server with middlewares and plugable routing.Getting startedClientTo get something from the web:importaiohttpimportasyncioasyncdefmain():asyncwithaiohttp.ClientSession()assession:asyncwithsession.get('http://python.org')asresponse:print("Status:",response.status)print("Content-type:",response.headers['content-type'])html=awaitresponse.text()print("Body:",html[:15],"...")loop=asyncio.get_event_loop()loop.run_until_complete(main())This prints:Status: 200 Content-type: text/html; charset=utf-8 Body: <!doctype html> ...Coming fromrequests? Readwhy we need so many lines.ServerAn example using a simple server:# examples/server_simple.pyfromaiohttpimportwebasyncdefhandle(request):name=request.match_info.get('name',"Anonymous")text="Hello, "+namereturnweb.Response(text=text)asyncdefwshandle(request):ws=web.WebSocketResponse()awaitws.prepare(request)asyncformsginws:ifmsg.type==web.WSMsgType.text:awaitws.send_str("Hello,{}".format(msg.data))elifmsg.type==web.WSMsgType.binary:awaitws.send_bytes(msg.data)elifmsg.type==web.WSMsgType.close:breakreturnwsapp=web.Application()app.add_routes([web.get('/',handle),web.get('/echo',wshandle),web.get('/{name}',handle)])if__name__=='__main__':web.run_app(app)Documentationhttps://aiohttp.readthedocs.io/Demoshttps://github.com/aio-libs/aiohttp-demosExternal linksThird party librariesBuilt with aiohttpPowered by aiohttpFeel free to make a Pull Request for adding your link to these pages!Communication channelsaio-libs discourse group:https://aio-libs.discourse.groupgitter chathttps://gitter.im/aio-libs/LobbyWe supportStack Overflow. Please addaiohttptag to your question there.RequirementsPython >= 3.6async-timeoutattrschardetmultidictyarlOptionally you may install thecChardetandaiodnslibraries (highly recommended for sake of speed).Licenseaiohttpis offered under the Apache 2 license.KeepsafeThe aiohttp community would like to thank Keepsafe (https://www.getkeepsafe.com) for its support in the early days of the project.Source codeThe latest developer version is available in a GitHub repository:https://github.com/aio-libs/aiohttpBenchmarksIf you are interested in efficiency, the AsyncIO community maintains a list of benchmarks on the official wiki:https://github.com/python/asyncio/wiki/BenchmarksChangelog3.7.4.post0 (2021-03-06)MiscBumped upper bound of thechardetruntime dependency to allow their v4.0 version stream.#53663.7.4 (2021-02-25)Bugfixes(SECURITY BUG)Started preventing open redirects in theaiohttp.web.normalize_path_middlewaremiddleware. For more details, seehttps://github.com/aio-libs/aiohttp/security/advisories/GHSA-v6wp-4m6f-gcjg.Thanks toBeast Glatisantfor finding the first instance of this issue andJelmer Vernooijfor reporting and tracking it down in aiohttp.#5497Fix interpretation difference of the pure-Python and the Cython-based HTTP parsers construct ayarl.URLobject for HTTP request-target.Before this fix, the Python parser would turn the URI’s absolute-path for//some-pathinto/while the Cython code preserved it as//some-path. Now, both do the latter.#54983.7.3 (2020-11-18)FeaturesUse Brotli instead of brotlipy#3803Made exceptions pickleable. Also changed the repr of some exceptions.#4077BugfixesRaise a ClientResponseError instead of an AssertionError for a blank HTTP Reason Phrase.#3532Fixweb_middlewares.normalize_path_middlewarebehavior for patch without slash.#3669Fix overshadowing of overlapped sub-applications prefixes.#3701MakeBaseConnector.close()a coroutine and wait until the client closes all connections. Drop deprecated “with Connector():” syntax.#3736Reset thesock_readtimeout each time data is received for aaiohttp.clientresponse.#3808Fixed type annotation for add_view method of UrlDispatcher to accept any subclass of View#3880Fixed querying the address families from DNS that the current host supports.#5156Change return type of MultipartReader.__aiter__() and BodyPartReader.__aiter__() to AsyncIterator.#5163Provide x86 Windows wheels.#5230Improved DocumentationAdd documentation foraiohttp.web.FileResponse.#3958Removed deprecation warning in tracing example docs#3964Fixed wrong “Usage” docstring ofaiohttp.client.request.#4603Add aiohttp-pydantic to third party libraries#5228Misc#41023.7.2 (2020-10-27)BugfixesFixed static files handling for loops without.sendfile()support#51493.7.1 (2020-10-25)BugfixesFixed a type error caused by the conditional import ofProtocol.#5111Server doesn’t send Content-Length for 1xx or 204#4901Fix run_app typing#4957Always requiretyping_extensionslibrary.#5107Fix a variable-shadowing bug causingThreadedResolver.resolveto return the resolved IP as thehostnamein each record, which prevented validation of HTTPS connections.#5110Added annotations to all public attributes.#5115Fix flaky test_when_timeout_smaller_second#5116Ensure sending a zero byte file does not throw an exception#5124Fix a bug inweb.run_app()about Python version checking on Windows#51273.7.0 (2020-10-24)FeaturesResponse headers are now prepared prior to runningon_response_preparehooks, directly before headers are sent to the client.#1958Add aquote_cookieoption toCookieJar, a way to skip quotation wrapping of cookies containing special characters.#2571CallAccessLogger.logwith the current exception available fromsys.exc_info().#3557web.UrlDispatcher.add_routesandweb.Application.add_routesreturn a list of registeredAbstractRouteinstances.AbstractRouteDef.register(and all subclasses) return a list of registered resources registered resource.#3866Added properties of default ClientSession params to ClientSession class so it is available for introspection#3882Don’t cancel web handler on peer disconnection, raiseOSErroron reading/writing instead.#4080Implement BaseRequest.get_extra_info() to access a protocol transports’ extra info.#4189AddedClientSession.timeoutproperty.#4191allow use of SameSite in cookies.#4224Useloop.sendfile()instead of custom implementation if available.#4269Apply SO_REUSEADDR to test server’s socket.#4393Use .raw_host instead of slower .host in client API#4402Allow configuring the buffer size of input stream by passingread_bufsizeargument.#4453Pass tests on Python 3.8 for Windows.#4513Addmethodandurlattributes toTraceRequestChunkSentParamsandTraceResponseChunkReceivedParams.#4674Add ClientResponse.ok property for checking status code under 400.#4711Don’t ceil timeouts that are smaller than 5 seconds.#4850TCPSite now listens by default on all interfaces instead of just IPv4 whenNoneis passed in as the host.#4894Bumphttp_parserto 2.9.4#5070BugfixesFix keepalive connections not being closed in time#3296Fix failed websocket handshake leaving connection hanging.#3380Fix tasks cancellation order on exit. The run_app task needs to be cancelled first for cleanup hooks to run with all tasks intact.#3805Don’t start heartbeat until _writer is set#4062Fix handling of multipart file uploads without a content type.#4089Preserve view handler function attributes across middlewares#4174Fix the string representation ofServerDisconnectedError.#4175Raising RuntimeError when trying to get encoding from not read body#4214Remove warning messages from noop.#4282Raise ClientPayloadError if FormData re-processed.#4345Fix a warning about unfinished task inweb_protocol.py#4408Fixed ‘deflate’ compression. According to RFC 2616 now.#4506Fixed OverflowError on platforms with 32-bit time_t#4515Fixed request.body_exists returns wrong value for methods without body.#4528Fix connecting to link-local IPv6 addresses.#4554Fix a problem with connection waiters that are never awaited.#4562Always make sure transport is not closing before reuse a connection.Reuse a protocol based on keepalive in headers is unreliable. For example, uWSGI will not support keepalive even it serves a HTTP 1.1 request, except explicitly configure uWSGI with a--http-keepaliveoption.Servers designed like uWSGI could cause aiohttp intermittently raise a ConnectionResetException when the protocol poll runs out and some protocol is reused.#4587Handle the last CRLF correctly even if it is received via separate TCP segment.#4630Fix the register_resource function to validate route name before splitting it so that route name can include python keywords.#4691Improve typing annotations forweb.Request,aiohttp.ClientResponseandmultipartmodule.#4736Fix resolver task is not awaited when connector is cancelled#4795Fix a bug “Aiohttp doesn’t return any error on invalid request methods”#4798Fix HEAD requests for static content.#4809Fix incorrect size calculation for memoryview#4890Add HTTPMove to _all__.#4897Fixed the type annotations in thetracingmodule.#4912Fix typing for multipart__aiter__.#4931Fix for race condition on connections in BaseConnector that leads to exceeding the connection limit.#4936Add forced UTF-8 encoding forapplication/rdap+jsonresponses.#4938Fix inconsistency between Python and C http request parsers in parsing pct-encoded URL.#4972Fix connection closing issue in HEAD request.#5012Fix type hint on BaseRunner.addresses (fromList[str]toList[Any])#5086Makeweb.run_app()more responsive to Ctrl+C on Windows for Python < 3.8. It slightly increases CPU load as a side effect.#5098Improved DocumentationFix example code in client quick-start#3376Updated the docs so there is no contradiction inttl_dns_cachedefault value#3512Add ‘Deploy with SSL’ to docs.#4201Change typing of the secure argument on StreamResponse.set_cookie fromOptional[str]toOptional[bool]#4204Changesttl_dns_cachetype from int to Optional[int].#4270Simplify README hello word example and add a documentation page for people coming from requests.#4272Improve some code examples in the documentation involving websockets and starting a simple HTTP site with an AppRunner.#4285Fix typo in code example in Multipart docs#4312Fix code example in Multipart section.#4314Update contributing guide so new contributors read the most recent version of that guide. Update command used to create test coverage reporting.#4810Spelling: Change “canonize” to “canonicalize”.#4986Addaiohttp-sse-clientlibrary to third party usage list.#5084Misc#2856,#4218,#42503.6.3 (2020-10-12)BugfixesPin yarl to<1.6.0to avoid buggy behavior that will be fixed by the next aiohttp release.3.6.2 (2019-10-09)FeaturesMade exceptions pickleable. Also changed the repr of some exceptions.#4077UseIterabletype hint instead ofSequenceforApplicationmiddlewareparameter.#4125BugfixesReset thesock_readtimeout each time data is received for aaiohttp.ClientResponse.#3808Fix handling of expired cookies so they are not stored in CookieJar.#4063Fix misleading message in the string representation ofClientConnectorError;self.ssl == Nonemeans default SSL context, not SSL disabled#4097Don’t clobber HTTP status when using FileResponse.#4106Improved DocumentationAdded minimal required logging configuration to logging documentation.#2469Update docs to reflect proxy support.#4100Fix typo in code example in testing docs.#4108Misc#41023.6.1 (2019-09-19)FeaturesCompatibility with Python 3.8.#4056Bugfixescorrect some exception string format#4068Emit a warning whenssl.OP_NO_COMPRESSIONis unavailable because the runtime is built against an outdated OpenSSL.#4052Update multidict requirement to >= 4.5#4057Improved DocumentationProvide pytest-aiohttp namespace for pytest fixtures in docs.#37233.6.0 (2019-09-06)FeaturesAdd support for Named Pipes (Site and Connector) under Windows. This feature requires Proactor event loop to work.#3629RemovedTransfer-Encoding:chunkedheader from websocket responses to be compatible with more http proxy servers.#3798Accept non-GET request for starting websocket handshake on server side.#3980BugfixesRaise a ClientResponseError instead of an AssertionError for a blank HTTP Reason Phrase.#3532Fix an issue where cookies would sometimes not be set during a redirect.#3576Change normalize_path_middleware to use 308 redirect instead of 301.This behavior should prevent clients from being unable to use PUT/POST methods on endpoints that are redirected because of a trailing slash.#3579Drop the processed task fromall_tasks()list early. It prevents logging about a task with unhandled exception when the server is used in conjunction withasyncio.run().#3587Signaltype annotation changed fromSignal[Callable[['TraceConfig'],Awaitable[None]]]toSignal[Callable[ClientSession, SimpleNamespace,...].#3595Use sanitized URL as Location header in redirects#3614Improve typing annotations for multipart.py along with changes required by mypy in files that references multipart.py.#3621Close session created insideaiohttp.requestwhen unhandled exception occurs#3628Cleanup per-chunk data in generic data read. Memory leak fixed.#3631Use correct type for add_view and family#3633Fix _keepalive field in __slots__ ofRequestHandler.#3644Properly handle ConnectionResetError, to silence the “Cannot write to closing transport” exception when clients disconnect uncleanly.#3648Suppress pytest warnings due totest_utilsclasses#3660Fix overshadowing of overlapped sub-application prefixes.#3701Fixed return type annotation for WSMessage.json()#3720Properly expose TooManyRedirects publicly as documented.#3818Fix missing brackets for IPv6 in proxy CONNECT request#3841Make the signature ofaiohttp.test_utils.TestClient.requestmatchasyncio.ClientSession.requestaccording to the docs#3852Use correct style for re-exported imports, makes mypy--strictmode happy.#3868Fixed type annotation for add_view method of UrlDispatcher to accept any subclass of View#3880Made cython HTTP parser set Reason-Phrase of the response to an empty string if it is missing.#3906Add URL to the string representation of ClientResponseError.#3959Acceptistrkeys inLooseHeaderstype hints.#3976Fixed race conditions in _resolve_host caching and throttling when tracing is enabled.#4013For URLs like “unix://localhost/…” set Host HTTP header to “localhost” instead of “localhost:None”.#4039Improved DocumentationModify documentation for Background Tasks to remove deprecated usage of event loop.#3526useif __name__ == '__main__':in server examples.#3775Update documentation reference to the default access logger.#3783Improve documentation forweb.BaseRequest.pathandweb.BaseRequest.raw_path.#3791Removed deprecation warning in tracing example docs#39643.5.4 (2019-01-12)BugfixesFix stream.read()/.readany()/.iter_any()which used to return a partial content only in case of compressed content#35253.5.3 (2019-01-10)BugfixesFix type stubs foraiohttp.web.run_app(access_log=True)and fix edge case ofaccess_log=Trueand the event loop being in debug mode.#3504Fixaiohttp.ClientTimeouttype annotations to acceptNonefor fields#3511Send custom per-request cookies even if session jar is empty#3515Restore Linux binary wheels publishing on PyPI3.5.2 (2019-01-08)FeaturesFileResponsefromweb_fileresponse.pyuses aThreadPoolExecutorto work with files asynchronously. I/O based payloads frompayload.pyuses aThreadPoolExecutorto work with I/O objects asynchronously.#3313Internal Server Errors in plain text if the browser does not support HTML.#3483BugfixesPreserve MultipartWriter parts headers on write. Refactor the way howPayload.headersare handled. Payload instances now always have headers and Content-Type defined. Fix Payload Content-Disposition header reset after initial creation.#3035Log suppressed exceptions inGunicornWebWorker.#3464Remove wildcard imports.#3468Use the same task for app initialization and web server handling in gunicorn workers. It allows to use Python3.7 context vars smoothly.#3471Fix handling of chunked+gzipped response when first chunk does not give uncompressed data#3477Replacecollections.MutableMappingwithcollections.abc.MutableMappingto avoid a deprecation warning.#3480Payload.sizetype annotation changed fromOptional[float]toOptional[int].#3484Ignore done tasks when cancels pending activities onweb.run_appfinalization.#3497Improved DocumentationAdd documentation foraiohttp.web.HTTPException.#3490Misc#34873.5.1 (2018-12-24)Fix a regression aboutClientSession._requote_redirect_urlmodification in debug mode.3.5.0 (2018-12-22)FeaturesThe library type annotations are checked in strict mode now.Add support for setting cookies for individual request (#2387)Application.add_domain implementation (#2809)The defaultappin the request returned bytest_utils.make_mocked_requestcan now have objects assigned to it and retrieved using the[]operator. (#3174)Makerequest.urlaccessible when transport is closed. (#3177)Addzlib_executor_sizeargument toResponseconstructor to allow compression to run in a background executor to avoid blocking the main thread and potentially triggering health check failures. (#3205)Enable users to setClientTimeoutinaiohttp.request(#3213)Don’t raise a warning ifNETRCenvironment variable is not set and~/.netrcfile doesn’t exist. (#3267)Add default logging handler to web.run_app If theApplication.debug`flag is set and the default loggeraiohttp.accessis used, access logs will now be output using astderrStreamHandlerif no handlers are attached. Furthermore, if the default logger has no log level set, the log level will be set toDEBUG. (#3324)Add method argument tosession.ws_connect(). Sometimes server API requires a different HTTP method for WebSocket connection establishment. For example,Docker execneeds POST. (#3378)Create a task per request handling. (#3406)BugfixesEnable passingaccess_log_classviahandler_args(#3158)Return empty bytes with end-of-chunk marker in empty stream reader. (#3186)AcceptCIMultiDictProxyinstances forheadersargument inweb.Responseconstructor. (#3207)Don’t uppercase HTTP method in parser (#3233)Make method match regexp RFC-7230 compliant (#3235)Addapp.pre_frozenstate to properly handle startup signals in sub-applications. (#3237)Enhanced parsing and validation of helpers.BasicAuth.decode. (#3239)Change imports from collections module in preparation for 3.8. (#3258)Ensure Host header is added first to ClientRequest to better replicate browser (#3265)Fix forward compatibility with Python 3.8: importing ABCs directly from the collections module will not be supported anymore. (#3273)Keep the query string bynormalize_path_middleware. (#3278)Fix missing parameterraise_for_statusfor aiohttp.request() (#3290)Bracket IPv6 addresses in the HOST header (#3304)Fix default message for server ping and pong frames. (#3308)Fix tests/test_connector.py typo and tests/autobahn/server.py duplicate loop def. (#3337)Fix false-negative indicator end_of_HTTP_chunk in StreamReader.readchunk function (#3361)Release HTTP response before raising status exception (#3364)Fix task cancellation whensendfile()syscall is used by static file handling. (#3383)Fix stack trace forasyncio.TimeoutErrorwhich was not logged, when it is caught in the handler. (#3414)Improved DocumentationImprove documentation ofApplication.make_handlerparameters. (#3152)Fix BaseRequest.raw_headers doc. (#3215)Fix typo in TypeError exception reason inweb.Application._handle(#3229)Make server access log format placeholder %b documentation reflect behavior and docstring. (#3307)Deprecations and RemovalsDeprecate modification ofsession.requote_redirect_url(#2278)Deprecatestream.unread_data()(#3260)Deprecated use of boolean inresp.enable_compression()(#3318)Encourage creation of aiohttp public objects inside a coroutine (#3331)Drop deadConnection.detach()andConnection.writer. Both methods were broken for more than 2 years. (#3358)Deprecateapp.loop,request.loop,client.loopandconnector.loopproperties. (#3374)Deprecate explicit debug argument. Use asyncio debug mode instead. (#3381)Deprecate body parameter in HTTPException (and derived classes) constructor. (#3385)Deprecate bare connector close, useasync with connector:andawait connector.close()instead. (#3417)Deprecate obsoleteread_timeoutandconn_timeoutinClientSessionconstructor. (#3438)Misc#3341, #3351
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())
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
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/
aiohttp-ext-handlers
No description available on PyPI.
aiohttp-ext-nester
No description available on PyPI.
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
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.
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.
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()
aiohttp-graphql
aiohttp-graphqlAddsGraphQLsupport to youraiohttpapplication.Based onflask-graphqlbySyrus Akbaryandsanic-graphqlbySergey Porivaev.UsageJust use theGraphQLViewview fromaiohttp_graphqlfromaiohttp_graphqlimportGraphQLViewGraphQLView.attach(app,schema=Schema,graphiql=True)# Optional, for adding batch query support (used in Apollo-Client)GraphQLView.attach(app,schema=Schema,batch=True)This will add a/graphqlendpoint to your app (customizable by passingroute_path='/mypath'toGraphQLView.attach).Note:GraphQLView.attachis just a convenience function, and the same functionality can be achieved withgql_view=GraphQLView(schema=Schema,**kwargs)app.router.add_route('*',gql_view,name='graphql')It's worth noting that the the "view function" ofGraphQLViewis contained inGraphQLView.__call__. So, when you create an instance, that instance is callable with the request object as the sole positional argument. To illustrate:gql_view=GraphQLView(schema=Schema,**kwargs)gql_view(request)# <-- the instance is callable and expects a `aiohttp.web.Request` object.Supported optionsschema: TheGraphQLSchemaobject that you want the view to execute when it gets a valid request.executor: TheExecutorthat you want to use to execute queries. If anAsyncioExecutorinstance is provided, performs queries asynchronously within executor’s loop.root_value: Theroot_valueyou want to provide toexecutor.execute.context: A value to pass as thecontextto thegraphql()function. By default is set todictwith request object at keyrequest.pretty: Whether or not you want the response to be pretty printed JSON.graphiql: IfTrue, may presentGraphiQLwhen loaded directly from a browser (a useful tool for debugging and exploration).graphiql_version: The version of the providedgraphiqlpackage.graphiql_template: Inject a Jinja template string to customize GraphiQL.middleware: Custom middleware forgraphql-python.batch: Set the GraphQL view as batch (for using inApollo-Clientor [ReactRelayNetworkLayer])jinja_env: Sets jinja environment to be used to process GraphiQL template. If Jinja’s async mode is enabled (byenable_async=True), usesTemplate.render_asyncinstead ofTemplate.render. If environment is not set, fallbacks to simple regex-based renderer.max_age: sets the response headerAccess-Control-Max-Agefor preflight requestsencoder: the encoder to use for responses (sensibly defaults tographql_server.json_encode)error_formatter: the error formatter to use for responses (sensibly defaults tographql_server.default_format_error)enable_async: whetherasyncmode will be enabled.subscriptions: TheGraphiQLsocket endpoint for using subscriptions ingraphql-ws.TestingTesting is done withpytest.gitclonehttps://github.com/graphql-python/aiohttp-graphqlcdaiohttp-graphql# Create a virtualenvpython3.6-mvenvenv&&sourceenv/bin/activate# for examplepipinstall-e.[test]pytestThe tests, while modeled after sanic-graphql's tests, have been entirely refactored to take advantage ofpytest-asyncio, conform with PEP-8, and increase readability with pytest fixtures. For usage tests, please check them out.LicenseCopyright for portions of projectaiohttp-graphqlare held bySyrus Akbaryas part of projectflask-graphqlandsanic-graphqlas part of projectSergey Porivaev. All other claims to this projectaiohttp-graphqlare held byDevin Fee.This project is licensed under the MIT License.
aiohttp_healthcheck
UNKNOWN
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
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"}
aiohttp-i18n
No description available on PyPI.
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)
aiohttp-init
No description available on PyPI.
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())
aiohttp-jinja2
aiohttp_jinja2jinja2template renderer foraiohttp.web.InstallationInstall from PyPI:pip install aiohttp-jinja2DevelopingInstall requirement and launch tests:pip install -r requirements-dev.txt pytest testsUsageBefore template rendering you have to setupjinja2 environmentfirst:app=web.Application()aiohttp_jinja2.setup(app,loader=jinja2.FileSystemLoader('/path/to/templates/folder'))Import:importaiohttp_jinja2importjinja2After 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_jinja2.template('tmpl.jinja2')defhandler(request):return{'name':'Andrew','surname':'Svetlov'}Or forClass Based Views <https://aiohttp.readthedocs.io/en/stable/web_quickstart.html#class-based-views>:classHandler(web.View):@aiohttp_jinja2.template('tmpl.jinja2')asyncdefget(self):return{'name':'Andrew','surname':'Svetlov'}On handler call theaiohttp_jinja2.templatedecorator will pass returned dictionary{'name': 'Andrew', 'surname': 'Svetlov'}into template namedtmpl.jinja2for getting resulting HTML text.If you need more complex processing (set response headers for example) you may callrender_templatefunction.Using a function based web handler:asyncdefhandler(request):context={'name':'Andrew','surname':'Svetlov'}response=aiohttp_jinja2.render_template('tmpl.jinja2',request,context)response.headers['Content-Language']='ru'returnresponseOr, again, a class based view:classHandler(web.View):asyncdefget(self):context={'name':'Andrew','surname':'Svetlov'}response=aiohttp_jinja2.render_template('tmpl.jinja2',self.request,context)response.headers['Content-Language']='ru'returnresponseLicenseaiohttp_jinja2is offered under the Apache 2 license.CHANGES1.6 (2023-11-18)Switch toaiohttp.web.AppKey, and deprecate the old ‘static_root_url’ key.Drop Python 3.7, add Python 3.12.1.5.1 (2023-02-01)Add support for Python 3.11.Drop support for decorating non-async functions with @template (deprecated since 0.16).1.5 (2021-08-21)Drop support for jinaj2 <3. Add support for 3+.Don’t requiretyping_extensionson Python 3.8+.1.4.2 (2020-11-23)Add CHANGES.rst to MANIFEST.in and sdist #4021.4.1 (2020-11-22)Document async rendering functions #3961.4.0 (2020-11-12)Fix type annotation forcontext_processorsargument #354Bump the minimal supportedaiohttpversion to 3.6.3 to avoid problems with uncompatibility betweenaiohttpandyarlAdd async rendering support #3931.3.0 (2020-10-30)Remove Any from template annotations #343Fix type annotation for filters inaiohttp_jinja2.setup#330Drop Python 3.5, support Python 3.91.2.0 (2019-10-21)Add type hints #2851.1.1 (2019-04-25)Bump minimal supportedjinja2version to 2.10.1 to avoid security vulnerability problem.1.1.0 (2018-09-05)Bump minimal supportedaiohttpversion to 3.2Userequest.config_dictfor accessingjinja2environment. It allows to reuse jinja rendering engine from parent application.1.0.0 (2018-03-12)Allow context_processors to compose from parent apps #1950.17.0 (2018-03-12)Auto-castintvalues inurl()jinja function tostr#1910.16.0 (2018-02-12)Pin to aiohttp 3.0+Deprecate non-async handlers support0.15.0 (2018-01-30)Upgrade middleware to new style from aiohttp 2.3+ #182Autoescape all templates by default #1790.13.0 (2016-12-14)Avoid subtle errors by copying context processor data #510.12.0 (2016-12-02)Add autodeploy script #460.11.0 (2016-11-24)Add jinja2 filters support #410.10.0 (2016-10-20)Rename package to aiohttp-jinja2 #310.9.0 (2016-09-26)Fix reason parameter in HTTPInternalServerError when template is not found #330.8.0 (2016-07-12)Add ability to render template without context #280.7.0 (2015-12-30)Add ability to decorate class based views (available in aiohttp 0.20) #18Upgrade aiohttp requirement to version 0.20.0+0.6.2 (2015-11-22)Make app_key parameter from render_string coroutine optional0.6.0 (2015-10-29)Fix a bug in middleware (missed coroutine decorator) #16Drop Python 3.3 support (switched to aiohttp version v0.18.0)Simplify context processors initialization by adding parameter tosetup()0.5.0 (2015-07-09)Introduce context processors #14Bypass StreamResponse #150.4.3 (2015-06-01)Fix distribution building: add manifest file0.4.2 (2015-05-21)Make HTTPInternalServerError exceptions more verbose on console output0.4.1 (2015-04-05)Documentation update0.4.0 (2015-04-02)Addrender_stringmethod0.3.1 (2015-04-01)Don’t allow non-mapping contextFix tiny documentation issuesChange the library logo0.3.0 (2015-03-15)Documentation release0.2.1 (2015-02-15)Fixrender_templatefunction0.2.0 (2015-02-05)Migrate to aiohttp 0.14Addstatusparameter to template decoratorDrop optionalresponseparameter0.1.0 (2015-01-08)Initial release
aiohttp-jinja2-haggle
No description available on PyPI.
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.
aiohttp-json-api
JSON APIimplementation foraiohttpIntroductionThis project heavily inspired bypy-jsonapi(author isBenedikt Schmitt). Some parts of this project is improved and refactoreddev-schemabranch ofpy-jsonapi. At beginning ofaiohttp-json-apithis branch was a great, but not finished implementation of JSON API withschema controllers. Also,py-jsonapiis not asynchronous and use inside self-implemented Request/Response classes.Some of base entities ofpy-jsonapiwas replaced withaiohttpserver’s objects, some of it was divided into new separate entities (e.g.JSONAPIContextorRegistry).Free software: MIT licenseDocumentation:https://aiohttp-json-api.readthedocs.ioRequirementsPython 3.6or neweraiohttpinflectionmultidictjsonpointerdateutiltrafaretpython-mimeparseTodoTutorialsImprove documentationTestsFeatures descriptionCustomizable payload keys inflection (default isdasherize<->underscore)Support for JSON API extensions (bulk creation etc.)Polymorphic relationshipsCreditsThis package was created withCookiecutterand thecookiecutter-pypackageproject template.History0.37.0 (2018-03-03)Drop Python 3.5 supportUpdate documentation0.36.1 (2018-03-03)Fix bug with content negotiationAdd cherry-picked and improved helpers frompython-mimeparse0.36.0 (2018-03-02)Improve content negotiation (fix #185) with python-mimeparseUpdate requirements0.35.2 (2017-12-13)Fix bug with wrong query parameters of links in compound documents0.35.1 (2017-12-12)Fixtrafaretrequirement to 1.0.2 (includedrfc3339.Date)0.35.0 (2017-12-11)BREAKING CHANGES!Schema is separated into Schema (marshaller) and ControllerRequest context instantiated in handlers and was renamed toJSONAPIContextChange signature of setup JSON API method in application (now we should pass a mapping between schemas and controllers)New abstract base class for ControllerSchema and Controller must be initialized with only one parameter —JSONAPIContextPassing a context to almost each method of Schema no more required (context is accessible from Schema or Controller instance directly)Remove decorator for JSON API handlers (content negotiation moved to middleware)Refactored fields and schema modulesImproved fetching of compound documentsExamples are updated to conform with all changes in this release0.33.1 (2017-12-06)Fix bug with no Accept header in request0.33.0 (2017-12-06)Improve content type negotiationImprove documentationAdd field for DateAdd example based onfantasy databaseIntroduce JSON API integration test suite (not done yet!)Improve collections helpersNo more links normalization by defaultMove meta object at top level of result document0.32.0 (2017-11-21)Constants, enums and structs refactoring(backward incompatible)Add useful typingsDocumentation fixesExtend development requirements0.31.0 (2017-11-14)Improve performance of URL resolving again. At this time with usage of standard Python urllibUpgrade requirements0.30.0 (2017-11-13)Improve performance of URL resolving in Link field (withcachetools)Upgrade requirements0.29.2 (2017-11-02)Documentation improvements0.29.1 (2017-11-02)Update READMEUpgrade requirements0.29.0 (2017-11-02)Simple example of usage is addedFix bug in handler of relationship query0.28.3 (2017-11-02)Fix bug with wrong read-only field errorDon’t require setup ID field in Schema to update a resource0.28.2 (2017-11-01)Addmultidictto requirements and to README0.28.1 (2017-10-31)Fix small bug with wrong empty sorting in RequestContext0.28.0 (2017-10-31)Add support for customizable inflection of fields from query string.Convert static methods of RequestContext to class methodsUpdate docs of RequestContext methods0.27.1 (2017-10-31)Fix packaging of ABCs and compats0.27.0 (2017-10-31)Abstract base classes refactoring (separate Field and Schema ABCs)Fix bug with compound documents in case models has no property “resource_id”Remove buggy helper to check subclass of any instanceDecompose setup application method to increase readabilityProperly error raised in jsonapi_handler decoratorUse one field instead of two to check what type of relation have the field0.26.0 (2017-10-30)Properly use abstract base classes. Inherit SchemaABC from ABC.Rename resource validation methods(backward incompatible)0.25.0 (2017-10-18)Add Tuple fieldFix bug with List field items enumerationFix wrong conversion of Decimal field to string on deserializationAddyarl(>=0.13) to requirements0.24.1 (2017-10-12)Add support for length range specifying for List field0.24.0 (2017-10-04)Convert document render utility to async coroutine(backward incompatible)Rename Error class property “json” to “as_dict” to clarify0.23.0 (2017-10-03)Use MultiDict for request context filters and FilterRule tuple(backward incompatible)Debug info on request context creation0.22.2 (2017-09-27)Add support for nullable List field0.22.1 (2017-09-25)Fix bug with wrong exit from compound documents fetch utility (“return” instead of “break”)0.22.0 (2017-09-22)Remove recursive fetching of compound documents. Replace it with simple loop.0.21.2 (2017-09-22)Fix bug with fetching compound documents when query parameter “include” contains the same relation twice and more.0.21.1 (2017-09-19)Fix bug with non-underscored relation name in relationship handlers0.21.0 (2017-09-19)Add support for field names conversion passed to “include” request contextUpdate development requirements0.20.2 (2017-08-30)Avoid assertion in Registry ensure identifier methodMake Schema getter of object id staticAvoid to filter out empty fields of rendered documents (less memory and faster)Get id field of schema more safely in URI resource ID validator0.20.1 (2017-08-15)Add support for load only fields (like a Marshmallow)0.20.0 (2017-08-14)Asynchronous validators supportRoutes namespace can be customizedRelative links support0.19.1 (2017-08-10)Improve serialization result default keys creation0.19.0 (2017-08-10)Refactor schema serializer to fix bug with no resource link in resultClean-up validation of expected ID in pre-validaiton of resourceUse status property of ErrorList in error middleware to return HTTP statusRemove default getter from Link field, because it doesn’t used anymore0.18.1 (2017-08-09)Migrate to trafaret >= 0.11.0Fix requirement of trafaret to version greater than 0.11.00.18.0 (2017-08-09)Properly handle missing values in deserialization and validation0.17.1 (2017-07-31)Add support for validation of Relationships ID field0.17.0 (2017-07-28)Normalize resource_id parameter usage in all mutation methods.Add fetch_resource schema coroutine to receive resource instance by ID.Add separate method for mapping deserialized data to schema.Context is required parameter for deserialization schema method.Move docs to ABC schema.Properly handle allow_none parameter for UUID field0.16.2 (2017-07-24)Fix arguments passed to validators0.16.1 (2017-07-24)Pass context to value setter in update methods0.16.0 (2017-07-22)Strict member names and type checking to conform JSON API requirements (routes and schema level). See also:http://jsonapi.org/format/#document-member-namesStrict check for overrides of handlersImprove debug logging0.15.2 (2017-07-21)Initialize default relationships links in meta-class, to avoid bug with empty names of relationships fields0.15.1 (2017-07-19)Rename resource ID parameter of query_resource schema’ method.0.15.0 (2017-07-18)Pagination is initialized from request by default. Remove separate class method of BasePagination to initialize pagination instanceImprove value validation error for absent fieldsImprove validation error of string field with choices0.14.0 (2017-07-13)Customisable JSON API handlers supportDRY in handlersMove context builder from middleware to jsonapi_handler decoratorRequest context receive optional resource_type now0.13.0 (2017-07-12)Revert back to asynchronous setters, because it’s used in update relationships and it might want to query DB, for example0.12.0 (2017-07-12)Base Registry class from UserDict, so Registry is a dict with ensure_identifier method.More strict typing checks on setup.0.11.1 (2017-07-11)Fix bug with mutation not cloned resource in method for delete relationshipRequire JSON API content type on delete relationships0.11.0 (2017-07-11)Method for update return original and updated resource as result. Updated resource is created via deepcopy. It will be useful to determine returned HTTP statusFix bug with enumeration (choices) in String fieldFix bug with context event setup for OPTIONS, HEAD and another request methods not used in JSON API0.10.0 (2017-07-10)Mass refactoring of schema, fields, validation and decoratorsGeneric approach to setup Schema decorators is used (inspired by Marshmallow)Fields are used only for encode/decode now (with pre/post validation). Additional validators for fields must be created on schema levelCustom JSON encoder with support JSONPointer serializationRemove boltons from requirementsNo more remap input data dictionary with key names to underscores conversion.Add helpers “first” and “make_sentinel” (cherry-picked from boltons)Fix enumeration (choices) support in String field0.9.3 (2017-07-06)Setup content-type validation on mutation API methods (application/vnd.api+json is required)Properly get and encode relationships fieldsUpdate docs and typing for ensure_identifier Registry’s method0.9.2 (2017-07-06)Fix bugs related to Python 3.5Generation of documentation on RTD is fixed0.9.1 (2017-07-06)Python 3.5 compatibility changes0.9.0 (2017-07-06)Handle aiohttp-json-api exceptions and errors in middleware. If exceptions is not related to JSON API errors, then exception is reraisedHuge refactoring of RequestContextNo more use of boltons cachedproperties, instead use parsing static methods related to each request context’ entityUpdate docs for RequestContext methodsAdd typings to RequestContext0.8.2 (2017-07-05)Properly handle error with wrong relation name (raise HTTP 400)0.8.1 (2017-07-05)Fix bdist_wheel python tag to support Python 3.50.8.0 (2017-07-05)Python 3.5 support (avoid usage of Python 3.6 format strings)Registry is plain object nowCustom Registry support (registry_classparameter inaiohttp_json_api.setup_jsonapimethod)Log debugging information at start about registered resources, methods and routesUse OrderedDict inside SchemaMeta0.7.2 (2017-07-04)Fix bug with JSONPointer when part passed via __truediv__ is integerValidate relationship object before adding relationship in ToMany field0.7.1 (2017-07-04)Fix bugs with validation of resource identifier in relationships fieldsAdd typings for base fields0.7.0 (2017-07-03)Setup of JSON API must be imported from package directlyFix bugs with decode fields and allow None values0.6.2 (2017-06-29)Update HISTORY0.6.1 (2017-06-29)Fix bug with Enum choices of String field0.6.0 (2017-06-29)Return resource in update method of Schema class. This will be helpful in inherit classes of Schemas.0.5.5 (2017-06-15)Setup auto-deploy to PyPI in Travis CI0.5.4 (2017-06-15)Initial release on PyPI0.5.3 (2017-06-14)Improve documentation0.5.0 (2017-06-14)Don’t useattrspackage anymoreRefactor requirements (move it intosetup.py)0.4.0 (2017-06-13)Schema imports refactoring (e.g. don’t useaiohttp_json_api.schema.schema.Schemaanymore)0.3.0 (2017-06-13)Upgrade requirements0.2.0 (2017-05-26)Fix setup.pyAdd test for Decimal trafaret field0.1.1 (2017-05-26)Dirty initial version
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())
aiohttp-json-rpc
aiohttp-json-rpcImplementsJSON-RPC 2.0 SpecificationusingaiohttpProtocolSupportWebsocketsince v0.1POSTTODOGETTODOInstallationpipinstallaiohttp-json-rpcUsageRPC methods can be added by usingrpc.add_method().All RPC methods are getting passed aaiohttp_json_rpc.communicaton.JsonRpcRequest.ServerThe following code implements a simple RPC server that serves the methodpingonlocalhost:8080.fromaiohttp.webimportApplication,run_appfromaiohttp_json_rpcimportJsonRpcimportasyncioasyncdefping(request):return'pong'if__name__=='__main__':loop=asyncio.get_event_loop()rpc=JsonRpc()rpc.add_methods(('',ping),)app=Application(loop=loop)app.router.add_route('*','/',rpc.handle_request)run_app(app,host='0.0.0.0',port=8080)Client (JS)The following code implements a simple RPC client that connects to the server above and prints all incoming messages to the console.<scriptsrc="//code.jquery.com/jquery-2.2.1.js"></script><script>varws=newWebSocket("ws://localhost:8080");varmessage_id=0;ws.onmessage=function(event){console.log(JSON.parse(event.data));}functionws_call_method(method,params){varrequest={jsonrpc:"2.0",id:message_id,method:method,params:params}ws.send(JSON.stringify(request));message_id++;}</script>These are example responses the server would give if you callws_call_method.--> ws_call_method("get_methods")<--{"jsonrpc":"2.0","result":["get_methods","ping"],"id":1}-->ws_call_method("ping")<--{"jsonrpc":"2.0","method":"ping","params":"pong","id":2}Client (Python)There’s also Python client, which can be used as follows:fromaiohttp_json_rpcimportJsonRpcClientasyncdefping_json_rpc():"""Connect to ws://localhost:8080/, call ping() and disconnect."""rpc_client=JsonRpcClient()try:awaitrpc_client.connect('localhost',8080)call_result=awaitrpc_client.call('ping')print(call_result)# prints 'pong' (if that's return val of ping)finally:awaitrpc_client.disconnect()asyncio.get_event_loop().run_until_complete(ping_json_rpc())Or use asynchronous context manager interface:fromaiohttp_json_rpcimportJsonRpcClientContextasyncdefjrpc_coro():asyncwithJsonRpcClientContext('ws://localhost:8000/rpc')asjrpc:# `some_other_method` will get request.params filled with `args` and# `kwargs` keys:method_res=awaitjrpc.some_other_method('arg1',key='arg2')returnmethod_resasyncio.get_event_loop().run_until_complete(jrpc_coro())FeaturesError HandlingAll errors specified in theerror specificationbut the InvalidParamsError are handled internally.If your coroutine got called with wrong params you can raise anaiohttp_json_rpc.RpcInvalidParamsErrorinstead of sending an error by yourself.The JSONRPC protocol defines a range for server defined errors.aiohttp_json_rpc.RpcGenericServerDefinedErrorimplements this feature.fromaiohttp_json_rpcimportRpcInvalidParamsErrorasyncdefadd(request):try:a=params.get('a')b=params.get('b')returna+bexceptKeyError:raiseRpcInvalidParamsErrorasyncdefadd(request):raiseRpcGenericServerDefinedError(error_code=-32050,message='Computer says no.',)Error LoggingEvery traceback caused by an RPC method will be caught and logged.The RPC will send an RPC ServerError and proceed as if nothing happened.asyncdefdivide(request):return1/0# will raise a ZeroDivisionErrorERROR:JsonRpc: Traceback (most recent call last): ERROR:JsonRpc: File "aiohttp_json_rpc/base.py", line 289, in handle_websocket_request ERROR:JsonRpc: rsp = yield from methods[msg['method']](ws, msg) ERROR:JsonRpc: File "./example.py", line 12, in divide ERROR:JsonRpc: return 1 / 0 ERROR:JsonRpc: ZeroDivisionError: division by zeroPublish SubscribeAny client of an RPC object can subscribe to a topic using the built-in RPC methodsubscribe().Topics can be added usingrpc.add_topics.AuthenticationThe auth system works like in Django with decorators. For details see the corresponding Django documentation.DecoratorDjango Equivalentaiohttp_json_rpc.django.auth.login_requireddjango.contrib.auth.decorators.login_requiredaiohttp_json_rpc.django.auth.permission_requireddjango.contrib.auth.decorators.permission_requiredaiohttp_json_rpc.django.auth.user_passes_testdjango.contrib.auth.decorators.user_passes_testfromaiohttp_json_rpc.authimport(permission_required,user_passes_test,login_required,)fromaiohttp_json_rpc.auth.djangoimportDjangoAuthBackendfromaiohttp_json_rpcimportJsonRpc@login_required@permission_required('ping')@user_passes_test(lambdauser:user.is_superuser)asyncdefping(request):return'pong'if__name__=='__main__':rpc=JsonRpc(auth_backend=DjangoAuthBackend())rpc.add_methods(('',ping),)rpc.add_topics(('foo',[login_required,permission_required('foo')]))Using SSL ConnectionsIf you need to setup a secure RPC server (use own certification files for example) you can create a ssl.SSLContext instance and pass it into the aiohttp web application.The following code implements a simple secure RPC server that serves the methodpingonlocalhost:8080fromaiohttp.webimportApplication,run_appfromaiohttp_json_rpcimportJsonRpcimportasyncioimportsslasyncdefping(request):return'pong'if__name__=='__main__':loop=asyncio.get_event_loop()rpc=JsonRpc()rpc.add_methods(('',ping),)app=Application(loop=loop)app.router.add_route('*','/',rpc.handle_request)ssl_context=ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)ssl_context.load_cert_chain('path/to/server.crt','path/to/server.key')run_app(app,host='0.0.0.0',port=8080,ssl_context=ssl_context)The following code implements a secure RPC client using theJsonRpcClientPython client.fromaiohttp_json_rpcimportJsonRpcClientimportsslasyncdefping_json_rpc():"""Connect to wss://localhost:8080/, call ping() and disconnect."""rpc_client=JsonRpcClient()ssl_context=ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)ssl_context.load_cert_chain('path/to/server.crt','path/to/server.key')try:awaitrpc_client.connect('localhost',8080,ssl=ssl_context)call_result=awaitrpc_client.call('ping')print(call_result)# prints 'pong' (if that's return val of ping)finally:awaitrpc_client.disconnect()asyncio.get_event_loop().run_until_complete(ping_json_rpc())Seeaiohttp documentationfor more details on SSL control for TCP sockets.Class Referencesclass aiohttp_json_rpc.JsonRpc(object)Methodsdef add_methods(self, *args,prefix='')Args have to be tuple containing a prefix as string (may be empty) and a module, object, coroutine or import string.If second arg is module or object all coroutines in it are getting added.async def get_methods()Returns list of all available RPC methods.def filter(self, topics)Returns generator over all clients that have subscribed for given topic.Topics can be string or a list of strings.async def notify(self, topic, data)Send RPC notification to all connected clients subscribed to given topic.Data has to be JSON serializable.Usesfilter().async def subscribe(topics)Subscribe to a topic.Topics can be string or a list of strings.async def unsubscribe(topics)Unsubscribe from a topic.Topics can be string or a list of strings.async def get_topics()Get subscribable topics as list of strings.
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
aiohttp-jwtplus
aiohttp-jwtplusAiohttp middleware and helper utils for working with JSON web token(signature). Added a post router for improving security level of SPAs & auto refresh secrets.Secret auto refresh.Totally separated content.Works on Python3.7+RequirementsAiohttp >= 2.3.5PyJWTInstallpip install aiohttp-jwtplusUsageYou need to create a SecretManager object ,which manages informations(secret \ scheme \ algorithm \ exp_interval \ auto_refresh_interval etc.) about jwt first.Then you need to create a JWTHelper ,in whose slots you can definite your business logic ,such as where you get token from ,what you do in identify process etc. If you dont pass them in ,JWTHelper will provides you a basic version of token_getter & identifier ,which simplely gets token from headers['Authorization'] value and then check out if decoded dictionary has key value 'username'.Finally you can create aiohttp.web.Application and pass middlewares in . It's a necessary condition to passin pre_jwt_identifier() and post_jwt_router() in order if you would like to activate post router. It's no need to register middleware via decorator first.Behaviors of routing under different authorizationpathremarksauthorized destinationunauthorized destination/index.htmlEntry of main functional SPA/index.html/login.html/login.htmlEntry of login page. Independent SPA/index.html/login.html/login_apiLogin api , one in jwt whitelist./login_api/login_api/setattr_apiOne of protected apis./setattr_api403 or 401/404Undefined page/index.html/login.html/* Status code 404 would be handled in SPA */Exampleserver_basic.py# here's a basic aiohttp hello-world server with four kinds of routing requirement respectively.fromaiohttpimportwebroutes=web.RouteTableDef()@routes.get('/index.html')asyncdefmain_spa_page(request):returnweb.Response(text="this is index.html")@routes.get('/login.html')asyncdeflogin_spa_page(request):returnweb.Response(text="this is login.html")@routes.get('/authentication')asyncdefloginapi(request):returnweb.Response(text="loginapi called")@routes.get('/setattr')asyncdefsetattr(request):returnweb.Response(text='this is a procted api')app=web.Application(middlewares=[])app.add_routes(routes)web._run_app(app)server.py# Add several lines to easily start a server with jwtplus-plugin.importasynciofromaiohttpimportwebfromaiohttp_jwtplusimport(SecretManager,JWTHelper,basic_identifier,basic_token_getter,show_request_info)routes=web.RouteTableDef()@routes.get('/index.html')asyncdefmain_spa_page(request):show_request_info(request)returnweb.Response(text="this is index.html")@routes.get('/login.html')asyncdeflogin_spa_page(request):show_request_info(request)returnweb.Response(text="this is login.html")@routes.get('/authentication')asyncdefloginapi(request):show_request_info(request)returnweb.Response(text="loginapi called")@routes.get('/setattr')asyncdefsetattr(request):show_request_info(request)returnweb.Response(text='this is a procted api')secret_manager=SecretManager(secret='testsecret',# default empty, will generate a random string.refresh_interval='30d',# default 0 ,represents secret auto refresh disabled. Accept string or intscheme="Bearer",# default.algorithm='HS256',# default.exptime='30d',# default.)jwt=JWTHelper(unauthorized_return_route='/login.html',# this's an exception which means if you've alreadly logined ,you cannot access to this page.unauthorized_return_route_handler=login_spa_page,authorized_return_page_handler=main_spa_page,secret_manager=secret_manager,token_getter=basic_token_getter,# defaultidentifier=basic_identifier,# defaultwhitelist=('/authentication',),# must be a tuple ,accepts regular expresion.protected_apis=['/setattr',])app=web.Application(middlewares=[jwt.pre_jwt_identifier(),jwt.post_jwt_router(),])app.add_routes(routes)loop=asyncio.get_event_loop()loop.create_task(secret_manager.auto_refresh())# Explicit trigger eventloop since we starts a secret-auto-refresh thread.loop.run_until_complete(web._run_app(app))client.py# For a quick test with python pretended frontend.importasynciofromaiohttpimportClientSessionfromaiohttp_jwtplusimport(SecretManager,JWTHelper,basic_identifier,# it's a coroutinebasic_token_getter,# it's a coroutineshow_request_info# print function)secret_manager=SecretManager(secret='testsecret',# default empty, will generate a random string.refresh_interval=0,# default 0 , no auto refresh.algorithm='HS256',# default.exptime='30d',# default.)url_pattern='http://localhost:8080{}'url_exts=['/index.html','/login.html','/authentication','/setattr','/404',]# Simulate you've alreadly got token feedback from server.# If you would like to generate token(without scheme) ,it accepts a dictionary# and items in which would be updated to jwt source payload.jwt=secret_manager.encode({'username':'jacky'})headers={'Authorization':"Bearer "+jwt.decode()}asyncdefmain():asyncwithClientSession()assession:print(f'{"#"*22}\nWith authentication')forurlextinurl_exts:asyncwithsession.get(url_pattern.format(urlext),headers=headers)asresponse:text=awaitresponse.text()print(f"called{urlext},\n\tget statuscode{response.status},\n\treturn text\"{text}\"")print(f'{"#"*22}\nWithout authentication')forurlextinurl_exts:asyncwithsession.get(url_pattern.format(urlext),headers={'Authorization':'None'})asresponse:text=awaitresponse.text()print(f"called{urlext},\n\tget statuscode{response.status},\n\treturn text\"{text}\"")asyncio.run(main())modify_identifier.py# Self-modified identifier & token_getter.fromaiohttpimportwebfromaiohttp_jwtplusimport(SecretManager,JWTHelper)asyncdefidentifier_mod(payload):'''An identifier accepts a payload(as dictionary of jwt decoded result),and whose return value will be stored as one of request's property named 'auth_carry'If you would like to make identification fail in middleware(before handle requests),return False.You don't need to worry about exceptions.'''if'username'inpayload:returnpayload['username']else:[email protected]('/index.html')asyncdefauthorised(request):username=request['auth_carry']['username']ifusername=='admin':returnweb.Response(text='pass')else:returnweb.Response(text='fail')secret_manager=SecretManager(secret='testsecret')jwt=JWTHelper(unauthorized_return_route='',unauthorized_return_route_handler=authorised,authorized_return_page_handler=authorised,secret_manager=secret_manager)app=web.Application(middlewares=[jwt.pre_jwt_identifier(),jwt.post_jwt_router(),])app.add_routes(routes)web.run_app(app)# Then you shall start a simulate client and encode a header with jwt authenrized payload with 'usernaem : admin' in it# and test if you got the corret response.
aiohttp-light-utils
No description available on PyPI.
aiohttp-like-django
You can coding aiohttp like django
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.
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 <[email protected]>','SMTP_HOST':'smtp.gmail.com','SMTP_PORT':465,'SMTP_USERNAME':'[email protected]','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
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 <[email protected]>','SMTP_HOST':'smtp.gmail.com','SMTP_PORT':465,'SMTP_USERNAME':'[email protected]','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
aiohttp-mako
No description available on PyPI.
aiohttpmap
No description available on PyPI.
aiohttp_metrics
No description available on PyPI.
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.
aiohttp-mock
aiohttp-mock
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 [email protected]("/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 [email protected](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 [email protected]("/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
aiohttp-negotiate
A mixin for supporting Negotiate authentication with aiohttp.Usagefrom aiohttp_negotiate import NegotiateClientSession session = NegotiateClientSession() resp = yield from session.get('https://example.com/')
aiohttp-oauth
See readme athttps://github.com/CanopyTax/aiohttp-oauth
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.
aiohttp-oauth2-session
aiohttp-oauth2-sessionA fully typed package that adds OAuth2 support for aiohttp.ClientSession.Installationpipinstallaiohttp-oauth2-sessionBasic Usagefromaiohttp_oauth2_sessionimportOAuth2SessionYou can create a session with or without a token already known.token={"access_token":"abc1234","token_type":"Bearer","expires_in":3600,"refresh_token":"def5678",}session=OAuth2Session(client_id="client_id",client_secret="client_secret",redirect_uri="https://example.com/oauth/redirect",scope="scope1 scope2",token=token,)# Which allows you to make authenticated requests straight away.resp=awaitsession.get("https://example.com/api/resource")awaitsession.close()You can also create a session without a token and fetch one later.session=OAuth2Session(client_id="client_id",client_secret="client_secret",redirect_uri="https://example.com/oauth/redirect",scope="scope1 scope2",)awaitsession.fetch_token(token_url="https://example.com/oauth/token",authorization_response="https://example.com/oauth/redirect?code=abc1234",)# now you can make authenticated requests.resp=awaitsession.get("https://example.com/api/resource")awaitsession.close()You can also use context managers to automatically close the session.asyncwithOAuth2Session(client_id="client_id",client_secret="client_secret",redirect_uri="https://example.com/oauth/redirect",scope="scope1 scope2",)assession:awaitsession.fetch_token(token_url="https://example.com/oauth/token",authorization_response="https://example.com/oauth/redirect?code=abc1234",)asyncwithsession.get("https://example.com/api/resource")asresp:print(awaitresp.json())Feel free to contribute!What still needs to be done:Add more comprehensive testsAdd typed support for other aiohttp client sessionsExpand the depency versions to be less restrictiveMake the code more readable, it's a bit messy right nowWhatever else you can think of. Please do open an issue or PR!This package is based ona gistbykellerza. Thank you very much!
aiohttp-oauthlib
This library is a port ofrequests-oauthlibforaiohttp.
aiohttp-openapi
aiohttp-openapi
aiohttp-openmetrics
This project contains a simple middleware and /metrics route endpoint for aiohttp that allow easy implementation of theopenmetricsprotocol.At the moment, this package is a thin wrapper around theprometheus_clientpackage.Example usagefromaiohttpimportwebfromaiohttp_openmetricsimportmetrics,metrics_middlewareapp=web.Application()app.middlewares.append(metrics_middlware)app.router.add_get('/metrics',metrics)web.run_app(app)LicenseThis package is licensed under the Apache v2 or later license.
aiohttp-parameter-parser
URL query string / path parameter parser and validator foraiohttpviewsDeclare and validate HTTP query and path parameters inaiohttpviews. Receive intended types instead of defaultstr. Receive single parameter or an array.Currently only path and URL query parameter locations are supported.Installationpipinstallaiohttp-parameter-parserBasic usage examplesfromdatetimeimportdatetimefromtypingimportOptionalimportpytzfromaiohttpimportwebfromaiohttp_parameter_parserimportParameterViewclassExampleView(ParameterView):date_format="%d-%m-%Y"# custom date format for date parameterstz=pytz.timezone("Europe/Berlin")# custom timezone for date parametersasyncdefget(self)->web.Response:my_tuple_of_ints:tuple[int,...]=self.query_parameter("parameter_name_in_request",required=True,is_array=True,max_items=6,# len() restriction for listis_int=True,max_value=1337,# maximum allowed value for array items)# If provided parameter is of wrong type or missing, a default# HTTP 400 response is returned to client.my_str:Optional[str]=self.path_parameter("a_string_parameter_name",# str is a default type for parsed parameter, so no# `is_string=True` flag can be usedchoices=["foo","bar","baz"],# enum)my_datetime:Optional[datetime]=self.query_parameter("my_datetime_parameter",is_date=True,)# will use custom timezone and date format provided abovereturnweb.json_response({"received_array_of_ints":my_tuple_of_ints,"received_str":my_str,"received_datetime":my_datetime.strftime(self.date_format),})Custom error response exampleSometimes you want to return custom error response instead of default HTTP 400. Here's an example how to raise custom exception if validation fails:fromaiohttpimportwebfromaiohttp_parameter_parserimportParameterViewclassCustomErrorResponseView(ParameterView):defvalidation_error_handler(self,msg:str)->web.Response:# just override this method of base class# 'msg' is a human-readable explanation of validation errorj={"ok":False,"data":None,"error":{"description":msg,},}# you can use raise or return herereturnweb.json_response(status=418,data=j)
aiohttp-patch
Failed to fetch description. HTTP Status Code: 404
aiohttp-poe
aiohttp_poeAn implementation of the Poe protocol using aiohttp.To run it:Create a virtual environment (Python 3.7 or higher)pip install .python -m aiohttp_poeIn a different terminal, runngrokto make it publicly accessibleWrite your own botThis package can also be used as a base to write your own bot. You can inherit fromaiohttp_poe.PoeBotto make a bot:fromaiohttp_poeimportPoeBot,runclassEchoBot(PoeBot):asyncdefget_response(self,query,request):last_message=query["query"][-1]["content"]yieldself.text_event(last_message)if__name__=="__main__":run(EchoBot())Enable authenticationPoe servers send requests containing Authorization HTTP header in the format "Bearer <api_key>," where api_key is the API key configured in the bot settings. \To validate the requests are from Poe Servers, you can either set the environment variable POE_API_KEY or pass the parameter api_key in the run function like:if__name__=="__main__":run(EchoBot(),api_key=<key>)For a more advanced example that exercises more of the Poe protocol, seeCatbot.
aiohttp-prometheus
HTTP metrics for a AIOHTTP applicationInstallingpipinstallaiohttp-prometheusUsagefromaiohttpimportwebfromaiohttp_prometheusimportMetricsMiddleware,MetricsViewapp=web.Application()app.middlewares.append(MetricsMiddleware())app.router.add_route('GET','/metrics',MetricsView),web.run_app(app)Example output for metric route# HELP aiohttp_http_requests_total Asyncio total Request Count # TYPE aiohttp_http_requests_total counter aiohttp_http_requests_total{handler="MetricsView",method="GET",status="2xx"} 7.0 # HELP aiohttp_http_request_duration_seconds Request latency # TYPE aiohttp_http_request_duration_seconds histogram aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="0.01",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="0.05",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="0.1",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="0.5",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="0.75",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="1.0",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="2.5",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="5.0",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="7.5",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="10.0",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="15.0",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="20.0",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="30.0",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="+Inf",method="GET"} 7.0
aiohttp-prometheus-client
HTTP metrics for a AIOHTTP applicationInstallingpipinstallaiohttp-prometheus-clientUsagefromaiohttpimportwebfromaiohttp_prometheusimportmetrics_middleware,MetricsViewapp=web.Application()app.middlewares.append(metrics_middleware)app.router.add_route('GET','/metrics',MetricsView),web.run_app(app)Example output for metric route# HELP aiohttp_http_requests_total Asyncio total Request Count # TYPE aiohttp_http_requests_total counter aiohttp_http_requests_total{handler="MetricsView",method="GET",status="2xx"} 7.0 # HELP aiohttp_http_request_duration_seconds Request latency # TYPE aiohttp_http_request_duration_seconds histogram aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="0.01",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="0.05",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="0.1",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="0.5",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="0.75",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="1.0",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="2.5",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="5.0",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="7.5",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="10.0",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="15.0",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="20.0",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="30.0",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="+Inf",method="GET"} 7.0
aiohttp-prometheus-exporter
Export aiohttp metrics for Prometheus.ioUsageRequirementsaiohttp >= 3InstallationInstall with:pipinstallaiohttp-prometheus-exporterServer quickstartfromaiohttpimportwebfromaiohttp_prometheus_exporter.handlerimportmetricsfromaiohttp_prometheus_exporter.middlewareimportprometheus_middleware_factoryasyncdefhello(request):returnweb.Response(text="Hello, world")app=web.Application()app.add_routes([web.get('/',hello)])app.middlewares.append(prometheus_middleware_factory())app.router.add_get("/metrics",metrics())web.run_app(app)Client quickstartimportaiohttpfromaiohttp_prometheus_exporter.traceimportPrometheusTraceConfigasyncwithaiohttp.ClientSession(trace_configs=[PrometheusTraceConfig())assession:asyncwithsession.get('http://httpbin.org/get')asresp:print(resp.status)print(awaitresp.text())Now, client metrics are attached to metrics exposed by your web server.CreditsThis package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.History0.2.4 (2020-04-07)Fixed building problemsConfigured black linter0.1.0 (2020-04-07)First release on PyPI.
aiohttp-prometheus-monitoring
# aiohttp_prometheus_monitoring[![PyPI](https://img.shields.io/pypi/v/aiohttp-prometheus-monitoring.svg?maxAge=3600)](https://pypi.python.org/pypi/aiohttp-prometheus-monitoring)[![Python Versions](https://img.shields.io/pypi/pyversions/aiohttp-prometheus-monitoring.svg?maxAge=3600)](https://pypi.python.org/pypi/aiohttp-prometheus-monitoring)This package allows to monitor availability of your aiohttp-application components and exports the metrics for prometheus scraper.It can monitor:- external host HTTP status- postgres database status- mysql database status- redis availability- rabbit AMQP availability- whatever else, as can be extended easilyIt periodically calls services, stores boolean result in Gauge metrics and exports the metrics via the /metrics endpoint.No additional workers required, everything is built-in into your app.Then you can build graphs based on this data:![Graphs](graphs.png)## Install:pip install aiohttp_prometheus_monitoring[amqp,redis,postgres,mysql]## Sample config:MONITORING = {'route_ping': '/ping','route_metrics': '/metrics','metrics': [{'name': 'monitoring_http','description': 'Check HTTP status','module': 'aiohttp_prometheus_monitoring.metrics.http.HttpMetric','sleep_time': 300,'params': {'url': 'http://localhost/my_ping/','timeout': 1,'verify_ssl': True,}},{'name': 'monitoring_redis','description': 'Check redis connection','module': 'aiohttp_prometheus_monitoring.metrics.redis.RedisMetric','sleep_time': 60,'params': {'host': 'localhost','port': '6379',}},{'name': 'monitoring_mq','description': 'Check MQ connection','module': 'aiohttp_prometheus_monitoring.metrics.amqp.AmqpMetric','sleep_time': 60,'params': {'host': 'localhost','port': '5672','user': 'root','password': '123','vhost': 'myvhost',}},{'name': 'monitoring_postgres','description': 'Check postgres connection','module': 'aiohttp_prometheus_monitoring.metrics.postgres.PostgresMetric','sleep_time': 60,'params': {'database': 'core','user': 'core','password': 'core','host': 'localhost','port': 5433,}},{'name': 'monitoring_mysql','description': 'Check mysql connection','module': 'aiohttp_prometheus_monitoring.metrics.mysql.MySQLMetric','sleep_time': 60,'params': {'database': 'core','user': 'core','password': 'core','host': 'localhost','port': 3007,}},]}## Usage:from aiohttp import webfrom aiohttp_prometheus_monitoring import setup_monitoringdef create_app(loop=None):app = web.Application()loop.run_until_complete(setup_monitoring(settings.MONITORING, app))return appCheck http://YOURAPP/ping and http://YOURAPP/metrics - /ping endpoint will respond "pong", /metrics endpoint will have metrics in prometheus format.
aiohttp-prometheus-swaggered
HTTP metrics for a AIOHTTP applicationInstallingpipinstallaiohttp-prometheus-clientUsagefromaiohttpimportwebfromaiohttp_prometheusimportmetrics_middleware,MetricsViewapp=web.Application()app.middlewares.append(metrics_middleware)app.router.add_route('GET','/metrics',MetricsView),web.run_app(app)Example output for metric route# HELP aiohttp_http_requests_total Asyncio total Request Count # TYPE aiohttp_http_requests_total counter aiohttp_http_requests_total{handler="MetricsView",method="GET",status="2xx"} 7.0 # HELP aiohttp_http_request_duration_seconds Request latency # TYPE aiohttp_http_request_duration_seconds histogram aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="0.01",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="0.05",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="0.1",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="0.5",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="0.75",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="1.0",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="2.5",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="5.0",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="7.5",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="10.0",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="15.0",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="20.0",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="30.0",method="GET"} 7.0 aiohttp_http_request_duration_seconds_bucket{handler="MetricsView",le="+Inf",method="GET"} 7.0
aiohttp-proxy
aiohttp-proxySOCKS proxy connector foraiohttp. HTTP, HTTPS, SOCKS4(a) and SOCKS5(h) proxies are supported.RequirementsPython >= 3.5.3aiohttp >= 2.3.2 # including v3.xInstallationpip install aiohttp_proxyUsageaiohttp usage:importaiohttpfromaiohttp_proxyimportProxyConnector,ProxyTypeasyncdeffetch(url):connector=ProxyConnector.from_url('http://user:[email protected]:1080')### or use ProxyConnector constructor# connector = ProxyConnector(# proxy_type=ProxyType.SOCKS5,# host='127.0.0.1',# port=1080,# username='user',# password='password',# rdns=True# )asyncwithaiohttp.ClientSession(connector=connector)assession:asyncwithsession.get(url)asresponse:returnawaitresponse.text()aiohttp-socks also providesopen_connectionandcreate_connectionfunctions:fromaiohttp_proxyimportopen_connectionasyncdeffetch():reader,writer=awaitopen_connection(socks_url='http://user:[email protected]:1080',host='check-host.net',port=80)request=(b"GET /ip HTTP/1.1\r\n"b"Host: check-host.net\r\n"b"Connection: close\r\n\r\n")writer.write(request)returnawaitreader.read(-1)Why give aiohttp a new proxy supportFirst must declare, our code is based onaiohttp-socks, thank you very much for the hard work.But in order to more flexible support for multiple proxy methods (not just SOCKS proxy), we decided to fork [aiohttp-socks] (https://github.com/romis2012/aiohttp-socks), which is currently based on it.Combine with native aiohttp to provide HTTP/HTTPS proxy instead of writing troublesome discriminating code based on the type of proxy.
aiohttp-pydantic
Aiohttp pydantic is anaiohttp viewto easily parse and validate request. You define using the function annotations what your methods for handling HTTP verbs expects and Aiohttp pydantic parses the HTTP request for you, validates the data, and injects that you want as parameters.Features:Query string, request body, URL path and HTTP headers validation.Open API Specification generation.How to install$pipinstallaiohttp_pydanticExample:fromtypingimportOptionalfromaiohttpimportwebfromaiohttp_pydanticimportPydanticViewfrompydanticimportBaseModel# Use pydantic BaseModel to validate request bodyclassArticleModel(BaseModel):name:strnb_page:Optional[int]# Create your PydanticView and add annotations.classArticleView(PydanticView):asyncdefpost(self,article:ArticleModel):returnweb.json_response({'name':article.name,'number_of_page':article.nb_page})asyncdefget(self,with_comments:bool=False):returnweb.json_response({'with_comments':with_comments})app=web.Application()app.router.add_view('/article',ArticleView)web.run_app(app)$curl-XGEThttp://127.0.0.1:8080/article?with_comments=a[{"in":"query string","loc":["with_comments"],"msg":"Input should be a valid boolean, unable to interpret input","input":"a","type":"bool_parsing"}]$curl-XGEThttp://127.0.0.1:8080/article?with_comments=yes{"with_comments":true}$curl-H"Content-Type: application/json"-XPOSThttp://127.0.0.1:8080/article--data'{}'[{"in":"body","loc":["name"],"msg":"Field required","input":{},"type":"missing"},{"in":"body","loc":["nb_page"],"msg":"Field required","input":{},"type":"missing"}]$curl-H"Content-Type: application/json"-XPOSThttp://127.0.0.1:8080/article--data'{"name": "toto", "nb_page": "3"}'{"name":"toto","number_of_page":3}API:Inject Path ParametersTo declare a path parameter, you must declare your argument as apositional-only parameters:Example:classAccountView(PydanticView):asyncdefget(self,customer_id:str,account_id:str,/):...app=web.Application()app.router.add_get('/customers/{customer_id}/accounts/{account_id}',AccountView)Inject Query String ParametersTo declare a query parameter, you must declare your argument as a simple argument:classAccountView(PydanticView):asyncdefget(self,customer_id:Optional[str]=None):...app=web.Application()app.router.add_get('/customers',AccountView)A query string parameter is generally optional and we do not want to force the user to set it in the URL. It’s recommended to define a default value. It’s possible to get a multiple value for the same parameter using the List typefromtypingimportListfrompydanticimportFieldclassAccountView(PydanticView):asyncdefget(self,tags:List[str]=Field(default_factory=list)):...app=web.Application()app.router.add_get('/customers',AccountView)Inject Request BodyTo declare a body parameter, you must declare your argument as a simple argument annotated withpydantic Model.classCustomer(BaseModel):first_name:strlast_name:strclassCustomerView(PydanticView):asyncdefpost(self,customer:Customer):...app=web.Application()app.router.add_view('/customers',CustomerView)Inject HTTP headersTo declare a HTTP headers parameter, you must declare your argument as akeyword-only argument.classCustomerView(PydanticView):asyncdefget(self,*,authorization:str,expire_at:datetime):...app=web.Application()app.router.add_view('/customers',CustomerView)Add route to generate Open Api Specification (OAS)aiohttp_pydantic provides a sub-application to serve a route to generate Open Api Specification reading annotation in your PydanticView. Useaiohttp_pydantic.oas.setup()to add the sub-applicationfromaiohttpimportwebfromaiohttp_pydanticimportoasapp=web.Application()oas.setup(app)By default, the route to display the Open Api Specification is /oas but you can change it usingurl_prefixparameteroas.setup(app,url_prefix='/spec-api')If you want generate the Open Api Specification from specific aiohttp sub-applications. on the same route, you must useapps_to_exposeparameter.fromaiohttpimportwebfromaiohttp_pydanticimportoasapp=web.Application()sub_app_1=web.Application()sub_app_2=web.Application()oas.setup(app,apps_to_expose=[sub_app_1,sub_app_2])You can change the title or the version of the generated open api specification usingtitle_specandversion_specparameters:oas.setup(app,title_spec="My application",version_spec="1.2.3")Add annotation to define response contentThe module aiohttp_pydantic.oas.typing provides class to annotate a response content.For exampler200[List[Pet]]means the server responses with the status code 200 and the response content is a List of Pet where Pet will be defined using a pydantic.BaseModelThe docstring of methods will be parsed to fill the descriptions in the Open Api Specification.fromaiohttp_pydanticimportPydanticViewfromaiohttp_pydantic.oas.typingimportr200,r201,r204,r404classPet(BaseModel):id:intname:strclassError(BaseModel):error:strclassPetCollectionView(PydanticView):asyncdefget(self)->r200[List[Pet]]:""" Find all pets Tags: pet """pets=self.request.app["model"].list_pets()returnweb.json_response([pet.dict()forpetinpets])asyncdefpost(self,pet:Pet)->r201[Pet]:""" Add a new pet to the store Tags: pet Status Codes: 201: The pet is created """self.request.app["model"].add_pet(pet)returnweb.json_response(pet.dict())classPetItemView(PydanticView):asyncdefget(self,id:int,/)->Union[r200[Pet],r404[Error]]:""" Find a pet by ID Tags: pet Status Codes: 200: Successful operation 404: Pet not found """pet=self.request.app["model"].find_pet(id)returnweb.json_response(pet.dict())asyncdefput(self,id:int,/,pet:Pet)->r200[Pet]:""" Update an existing pet Tags: pet Status Codes: 200: successful operation """self.request.app["model"].update_pet(id,pet)returnweb.json_response(pet.dict())asyncdefdelete(self,id:int,/)->r204:self.request.app["model"].remove_pet(id)returnweb.Response(status=204)Group parametersIf your method has lot of parameters you can group them together inside one or several Groups.fromaiohttp_pydantic.injectorsimportGroupclassPagination(Group):page_num:int=1page_size:int=15classArticleView(PydanticView):asyncdefget(self,page:Pagination):articles=Article.get(page.page_num,page.page_size)...The parameters page_num and page_size are expected in the query string, and set inside a Pagination object passed as page parameter.The code above is equivalent to:classArticleView(PydanticView):asyncdefget(self,page_num:int=1,page_size:int=15):articles=Article.get(page_num,page_size)...You can add methods or properties to your Group.classPagination(Group):page_num:int=1page_size:int=15@propertydefnum(self):returnself.page_num@propertydefsize(self):returnself.page_sizedefslice(self):returnslice(self.num,self.size)classArticleView(PydanticView):asyncdefget(self,page:Pagination):articles=Article.get(page.num,page.size)...Custom Validation errorYou can redefine the on_validation_error hook in your PydanticViewclassPetView(PydanticView):asyncdefon_validation_error(self,exception:ValidationError,context:str):errors=exception.errors()forerrorinerrors:error["in"]=context# context is "body", "headers", "path" or "query string"error["custom"]="your custom field ..."returnjson_response(data=errors,status=400)DemoHave a look atdemofor a complete examplegitclonehttps://github.com/Maillol/aiohttp-pydantic.gitcdaiohttp-pydanticpipinstall.python-mdemoGo tohttp://127.0.0.1:8080/oasYou can generate the OAS in a json or yaml file using the aiohttp_pydantic.oas command:python-maiohttp_pydantic.oasdemo.main$python3-maiohttp_pydantic.oas--helpusage:__main__.py[-h][-bFILE][-oFILE][-fFORMAT][APP[APP...]]GenerateOpenAPISpecificationpositionalarguments:APPThenameofthemodulecontainingtheasyncio.web.Application.Bydefaultthevariablenamed'app'isloadedbutyoucandefineanothervariablenameendingthenameofmodulewith:charactersandthenameofvariable.Example:my_package.my_module:my_appIfyourasyncio.web.Applicationisreturnedbyafunction,youcanusethesyntax:my_package.my_module:my_app()optionalarguments:-h,--helpshowthishelpmessageandexit-bFILE,--base-oas-fileFILEAfilethatwillbeusedasbasetogenerateOAS-oFILE,--outputFILEFiletowritetheoutput-fFORMAT,--formatFORMATTheoutputformat,canbe'json'or'yaml'(defaultisjson)
aiohttp-query-requirements
No description available on PyPI.
aiohttp-r3
importaiohttp_r3app=web.Application(router=aiohttp_r3.R3Router())
aiohttp-rapid
rapid
aiohttp-ratelimiter
aiohttp-ratelimiteraiohttp-ratelimiter is a rate limiter for the aiohttp.web framework. This is a new library, and we are always looking for people to contribute. If you see something wrong with the code or want to add a feature, please create a pull request onour github.Install from gitpython -m pip install git+https://github.com/JGLTechnologies/aiohttp-ratelimiterInstall from pypipython -m pip install aiohttp-ratelimiter // if redis is being used python -m pip install aiohttp-ratelimiter[redis] // if memcached is being used python -m pip install aiohttp-ratelimiter[memcached]Examplefromaiohttpimportwebfromaiohttplimiterimportdefault_keyfunc,Limiterfromaiohttplimiter.redis_limiterimportRedisLimiterfromaiohttplimiter.memcached_limiterimportMemcachedLimiterapp=web.Application()routes=web.RouteTableDef()# In Memorylimiter=Limiter(keyfunc=default_keyfunc)# Redislimiter=RedisLimiter(keyfunc=default_keyfunc,uri="redis://localhost:6379")# Memcachedlimiter=MemcachedLimiter(keyfunc=default_keyfunc,uri="memcached://localhost:11211")@routes.get("/")# This endpoint can only be requested 1 time per second per IP [email protected]("1/second")asyncdefhome(request):returnweb.Response(text="test")app.add_routes(routes)web.run_app(app)You can exempt an IP from rate limiting using the exempt_ips kwarg.fromaiohttplimiterimportLimiter,default_keyfuncfromaiohttpimportwebapp=web.Application()routes=web.RouteTableDef()# 192.168.1.245 is exempt from rate limiting.# Keep in mind that exempt_ips takes a set not a list.limiter=Limiter(keyfunc=default_keyfunc,exempt_ips={"192.168.1.245"})@routes.get("/")@limiter.limit("3/5minutes")asyncdeftest(request):returnweb.Response(text="test")app.add_routes(routes)web.run_app(app)You can create your own error handler by using the error_handler kwarg.fromaiohttplimiterimportAllow,RateLimitExceeded,Limiter,default_keyfuncfromaiohttpimportwebdefhandler(request:web.Request,exc:RateLimitExceeded):# If for some reason you want to allow the request, return aiohttplimitertest.Allow().ifsome_condition:returnAllow()returnweb.Response(text=f"Too many requests",status=429)limiter=Limiter(keyfunc=default_keyfunc,error_handler=handler)If multiple paths use one handler like this:@routes.get("/")@routes.get("/home")@limiter.limit("5/hour")defhome(request):returnweb.Response(text="Hello")Then they will have separate rate limits. To prevent this use the path_id [email protected]("/")@routes.get("/home")@limiter.limit("2/3days",path_id="home")defhome(request):returnweb.Response(text="Hello")Views [email protected]("/")classHome(View):@limiter.limit("1/second")defget(self):returnweb.Response(text="hello")
aiohttp-rate-limiter
No description available on PyPI.
aiohttp-raw
aiohttp-rawUseaiohttpto send HTTP raw sockets (To Test RFC Compliance)Usageimportasyncioimportaiohttp_rawasyncdefmain():req=b"GET /get HTTP/1.1\r\nHost: httpbin.org\r\n\r\n"asyncwithaiohttp_raw.ClientSession()assession:asyncwithsession.raw("http://httpbin.org/get",data=req)asresponse:print(awaitresponse.text())loop=asyncio.new_event_loop()loop.run_until_complete(main())InstallationPrerequisitesPython 3.8+pip3installaiohttp-raw# speedupspipinstallaiohttp[speedups]# sockspipinstallaiohttp[socks]# speedups-sockspipinstallaiohttp[speedups-socks]
aiohttp-remotes
The library is a set of useful tools foraiohttp.webserver.The full list of tools is:AllowedHosts– restrict a set of incoming connections to allowed hosts only.BasicAuth– protect web application bybasic authauthorization.Cloudflare– make sure that web application is protected by CloudFlare.ForwardedRelaxedandForwardedStrict– processForwardedHTTP header and modify correspondingscheme,host,remoteattributes in strong secured and relaxed modes.Secure– ensure that web application is handled by HTTPS (SSL/TLS) only, redirect plain HTTP to HTTPS automatically.XForwardedRelaxedandXForwardedStrict– the same asForwardedRelaxedandForwardedStrictbut process old-fashionX-Forwarded-*headers instead of new standardForwarded.Readhttps://aiohttp-remotes.readthedocs.iofor more information.The library was donated by Ocean S.A.https://ocean.io/Thanks to the company for contribution.
aiohttp-request
info:Global request for aiohttp serverInstallationpipinstallaiohttp_requestUsageimportasynciofromaiohttpimportwebfromaiohttp_requestimportThreadContext,middleware_factory,grequest,get_requestdefthread():assertgrequest['sense']==42asyncdeftask():# grequest is `lazy` version of requestassertgrequest['sense']==42loop=asyncio.get_event_loop()# works for threads as well with ThreadContextawaitloop.run_in_executor(None,ThreadContext(thread))asyncdefhello(request):# get_request is on-demand function to get current requestassertget_request()isrequestrequest['sense']=42# asyncio.Task is supportedawaitasyncio.ensure_future(task())returnweb.Response(text="Hello, world")app=web.Application(middlewares=[middleware_factory()])app.add_routes([web.get('/',hello)])web.run_app(app)Python 3.7+ is required, there is no way to support older python versions!!!NotesThe library relies onPEP 567and itsasyncio supportaiohttp-request works nicely with threads viacontextvars_executor, noThreadContextis neededimportasynciofromaiohttpimportwebfromaiohttp_requestimportmiddleware_factory,grequestfromcontextvars_executorimportContextVarExecutordefthread():assertgrequest['sense']==42asyncdefhello(request):request['sense']=42loop=asyncio.get_event_loop()awaitloop.run_in_executor(None,thread)returnweb.Response(text="Hello, world")loop=asyncio.get_event_loop()loop.set_default_executor(ContextVarExecutor())app=web.Application(middlewares=[middleware_factory()])app.add_routes([web.get('/',hello)])web.run_app(app)
aiohttp-requests
aiohttp-requestsBehold, the power ofaiohttpclient withRequestssimplicity:importasyncioimportaiohttpfromaiohttp_requestsimportrequestsasyncdefmain():response=awaitrequests.get('https://api.github.com',auth=aiohttp.BasicAuth('user','password'))text=awaitresponse.text()json=awaitresponse.json()returnresponse,text,jsonr,text,json=asyncio.run(main())>>>r<ClientResponse(https://api.github.com/)[200OK]>>>>r.status200>>>r.headers['Content-Type']'application/json; charset=utf-8'>>>r.get_encoding()'utf-8'>>>text'{"current_user_url":"https://api.github.com/user",...'>>>json{'current_user_url':'https://api.github.com/user',...}Plus built-in concurrency control to do multiple requests safely:asyncdefmain():# Pass in a list of urls instead of just one. Optionally pass in as_iterator=True to iterate the responses.responses=awaitrequests.get(['https://api.github.com']*2,auth=aiohttp.BasicAuth('user','password'))print(responses)# [<ClientResponse(https://...) [200 OK]>, , <ClientResponse(https://...) [200 OK]>]# It defaults to 10 concurrent requests. If you can handle more, then set it higher:requests.max_concurrency=100asyncio.run(main())Therequestsobject is just proxyinggetand other HTTP verb methods toaiohttp.ClientSession, which returnsaiohttp.ClientResponse. To do anything else, read theaiohttpdoc.Links & Contact InfoPyPI Package:https://pypi.python.org/pypi/aiohttp-requestsGitHub Source:https://github.com/maxzheng/aiohttp-requestsReport Issues/Bugs:https://github.com/maxzheng/aiohttp-requests/issuesConnect:https://www.linkedin.com/in/maxzhengContact: maxzheng.os @t gmail.com
aiohttp-rest-api
No description available on PyPI.
aiohttp-rest-api-fork
No description available on PyPI.
aiohttp-rest-api-redoc
aiohttp_rest_apiRESTful API servers with aiohttp. Forked to use ReDoc instead of Swaggeraiohttp_rest_apiis an extension for aiohttp that adds support for quickly building REST APIs. It automates the creation of REST endpoints, supports APIs versioning and openapi docstrings.pipinstallaiohttp-rest-apiDocumentation:https://aiohttp-rest-api.readthedocs.io/
aiohttp-rest-framework
aiohttp-rest-frameworkFully asynchronous rest framework for aiohttp web server, inspired byDjango Rest Framework(DRF), powered bymarshmallowandSQLAlchemy.Currently supports only combination of postgres and sqlalchemy (ORM and core). MySQL support will be shipped on demand.Installationpipinstallaiohttp-rest-frameworkUsage exampleConsider we have the following SQLAlchemy ORM models:models.pyimportsqlalchemyassafromsqlalchemy.dialects.postgresqlimportUUIDfromsqlalchemy.ormimportdeclarative_basefromapp.utilsimportget_stringified_uuidBase=declarative_base()meta=Base.metadataclassUser(Base):__tablename__="users"id=sa.Column(UUID,primary_key=True,default=get_stringified_uuid)name=sa.Column(sa.Text)email=sa.Column(sa.Text,nullable=False,unique=True)phone=sa.Column(sa.Text)company_id=sa.Column(sa.ForeignKey("companies.id"),nullable=True)classCompany(Base):__tablename__="companies"id=sa.Column(UUID,primary_key=True,default=get_stringified_uuid)name=sa.Column(sa.Text,nullable=False)SQLAlchemy Core tables are also supported.importsqlalchemyassafromsqlalchemy.dialects.postgresqlimportUUIDfromapp.utilsimportget_stringified_uuidmeta=sa.MetaData()User=sa.Table("users",meta,sa.Column("id",UUID,primary_key=True,default=get_stringified_uuid),sa.Column("name",sa.Text),sa.Column("email",sa.Text,unique=True),sa.Column("phone",sa.Text),sa.Column("company_id",sa.ForeignKey("companies.id"),nullable=True),)Company=sa.Table("companies",meta,sa.Column("id",UUID,primary_key=True,default=get_stringified_uuid),sa.Column("name",sa.Text),)Now we can use very familiar to us from DRF serializer, built on top of marshmalow'sSchema:serializers.pyfromaiohttp_rest_frameworkimportserializersfromapp.modelsimportUserclassUserSerializer(serializers.ModelSerializer):classMeta:model=Userfields="__all__"dump_only=("id",)Note: for more information about field declaration please refer tomarshmallowFor SQLAlchemy ORMModelSerializersupports generic typing:classUserSerializer(serializers.ModelSerializer[User]):# <- mention `User` hereclassMeta:model=Userfields="__all__"Now type hints will be available for serializers methods likecreate(),update(), etc.And, finally, now we can use our serializer in class based views:views.pyfromaiohttp_rest_frameworkimportviewsfromapp.serializersimportUserSerializerclassUsersListCreateView(views.ListCreateAPIView):serializer_class=UserSerializerclassUsersRetrieveUpdateDestroyView(views.RetrieveUpdateDestroyAPIView):serializer_class=UserSerializerOur simple app would look like this:main.pyfromaiohttpimportwebfromaiohttp_rest_frameworkimportsetup_rest_framework,create_connectionfromaiohttp_rest_framework.utilsimportcreate_tablesfromappimportviews,config,modelsasyncdefdb_cleanup_context(app_:web.Application)->None:app_["db"]=awaitcreate_connection(config.db_url)# in case you need to create tables in the database# for sqlalchemy this is the same as `meta.create_all()`, but asynchronousawaitcreate_tables(models.meta,app_["db"])yieldawaitapp_["db"].dispose()app=web.Application()app.cleanup_ctx.append(db_cleanup_context)app.router.add_view("/users",views.UsersListCreateView)app.router.add_view("/users/{id}",views.UsersRetrieveUpdateDestroyView)setup_rest_framework(app)web.run_app(app)Note: If you want to use other property than "db", in order to application work you have to specifyapp_connection_propertyin config, passing tosetup_rest_framework.Example:setup_rest_framework(app, {"app_connection_property": "custom_db_prop"})Mentionsetup_rest_framework()function, it is required to call it to configure framework to work with your app. For available rest framework's config options refer todocumentation. For detailed aiohttp web app configuration please refer totheir docs.After starting the app, we can make aPOST /usersrequest to create a new user.curl-H"Content-Type: application/json"-d'{"name": "John Doe","email": "[email protected]","phone": "+123456789"}'-XPOSThttp://localhost:8080/usersAnd get the followingHTTP 201 Response:{"id":"aa392cc9-c734-44ff-9d7c-1602ecb4df2a","name":"John Doe","email":"[email protected]","phone":"+123456789","company_id":null}Let's try to update user's company. MakingPATCH /users/aa392cc9-c734-44ff-9d7c-1602ecb4df2arequestcurl-H"Content-Type: application/json"-d'{"company_id": "0413de74-d9fb-494b-ba56-b56599261fb0"}'-XPATCHhttp://localhost:8080/users/a392cc9-c734-44ff-9d7c-1602ecb4df2aHTTP 200 Response:{"id":"aa392cc9-c734-44ff-9d7c-1602ecb4df2a","name":"John Doe","email":"[email protected]","phone":"+123456789","company_id":"0413de74-d9fb-494b-ba56-b56599261fb0"}For more examples and usages please refer todocumentation.RequirementsPython >= 3.6Dependencies:aiohttpsqlalchemymarshmallowIf using PostgreSQL (currently being installed by default since it's the only database supported):asyncpgpsycopg2Documentationsetup_rest_framework(app, config)Config is just a simpledictobject. Config can accept following parameters (everything is optional):schema_type: str- Specifies what combination of database and SQL toolkit to use. Currently supports only combination of SQLAlchemy and PostgreSQL.Default:"sa"app_connection_property: str- The property name of the database connection in your aiohttp application.Default:"db".custom_db_prop="db_conn"asyncdefdb_cleanup_context(app_:web.Application)->None:app_[custom_db_prop]=awaitcreate_connection(config.db_url)yieldawaitapp_[custom_db_prop].dispose()app=web.Application()app.cleanup_ctx.append(db_cleanup_context)setup_rest_framework(app,{"app_connection_property":custom_db_prop})get_connection: Callable[[], Awaitable]- An async callable that receive no arguments and returns database connection. You would only need it if you don't want to store your database connection in aiohttp application, then you have to provide it toaiohttp-rest-frameworkso framework can work with a database.Default:usesapp[app_connection_property]# somewhere in your code, function to get initialized db connectionfromapp.dbimportget_connection# this is just to show that is has to be asyncasyncdefget_db_connection():returnawaitget_connection()app=web.Application()setup_rest_framework(app,{"get_connection":get_db_connection})db_manager: BaseDBManager- Specifies what database manager to use. You would need it if you want to use custom logic in database operations (class should be inherited fromBaseDBManagerimported fromaiohttp_rest_framework.db.base). Usually you wouldn't need it because framework's built-inSAManager(if you useschema_type = "sa", which is default) already handles all CRUD operations and also hasexecute()method where you can pass custom sqlalchemy queries.Default:uses manager specific to the currentschema_type.A totally useless example just to show you how it can be used:fromaiohttp_rest_framework.db.saimportSAManagerclassSAManagerWithPrintingQuery(SAManager):asyncdefexecute(self,query,*args,**kwargs):print(query)returnawaitsuper().execute(query,*args,**kwargs)app=web.Application()setup_rest_framework(app,{"db_manager":SAManagerWithPrintingQuery})
aiohttp-retry
Simple aiohttp retry clientPython 3.7 or higher.Install:pip install aiohttp-retry.Breaking API changesEverything between [2.7.0 - 2.8.3) is yanked.There is a bug with evaluate_response_callback, it led to infinite retries2.8.0 is incorrect and yanked.https://github.com/inyutin/aiohttp_retry/issues/79Since 2.5.6 this is a new parameter inget_timeoutfunc called "response".If you have defined your ownRetryOptions, you should add this param into it. Issue about this:https://github.com/inyutin/aiohttp_retry/issues/59Examples of usage:fromaiohttp_retryimportRetryClient,ExponentialRetryasyncdefmain():retry_options=ExponentialRetry(attempts=1)retry_client=RetryClient(raise_for_status=False,retry_options=retry_options)asyncwithretry_client.get('https://ya.ru')asresponse:print(response.status)awaitretry_client.close()fromaiohttpimportClientSessionfromaiohttp_retryimportRetryClientasyncdefmain():client_session=ClientSession()retry_client=RetryClient(client_session=client_session)asyncwithretry_client.get('https://ya.ru')asresponse:print(response.status)awaitclient_session.close()fromaiohttp_retryimportRetryClient,RandomRetryasyncdefmain():retry_options=RandomRetry(attempts=1)retry_client=RetryClient(raise_for_status=False,retry_options=retry_options)response=awaitretry_client.get('/ping')print(response.status)awaitretry_client.close()fromaiohttp_retryimportRetryClientasyncdefmain():asyncwithRetryClient()asclient:asyncwithclient.get('https://ya.ru')asresponse:print(response.status)You can change parameters between attempts by passing multiple requests params:fromaiohttp_retryimportRetryClient,RequestParams,ExponentialRetryasyncdefmain():retry_client=RetryClient(raise_for_status=False)asyncwithretry_client.requests(params_list=[RequestParams(method='GET',url='https://ya.ru',),RequestParams(method='GET',url='https://ya.ru',headers={'some_header':'some_value'},),])asresponse:print(response.status)awaitretry_client.close()You can also add some logic, F.E. logging, on failures by using trace mechanic.importloggingimportsysfromtypesimportSimpleNamespacefromaiohttpimportClientSession,TraceConfig,TraceRequestStartParamsfromaiohttp_retryimportRetryClient,ExponentialRetryhandler=logging.StreamHandler(sys.stdout)logging.basicConfig(handlers=[handler])logger=logging.getLogger(__name__)retry_options=ExponentialRetry(attempts=2)asyncdefon_request_start(session:ClientSession,trace_config_ctx:SimpleNamespace,params:TraceRequestStartParams,)->None:current_attempt=trace_config_ctx.trace_request_ctx['current_attempt']ifretry_options.attempts<=current_attempt:logger.warning('Wow! We are in last attempt')asyncdefmain():trace_config=TraceConfig()trace_config.on_request_start.append(on_request_start)retry_client=RetryClient(retry_options=retry_options,trace_configs=[trace_config])response=awaitretry_client.get('https://httpstat.us/503',ssl=False)print(response.status)awaitretry_client.close()Look tests for more examples.Be aware: last request returns as it is.If the last request ended with exception, that this exception will be raised from RetryClient requestDocumentationRetryClienttakes the same arguments as ClientSession[docs]RetryClienthas methods:requestgetoptionsheadpostputpatchputdeleteThey are same as forClientSession, but take one possible additional argument:classRetryOptionsBase:def__init__(self,attempts:int=3,# How many times we should retrystatuses:Optional[Iterable[int]]=None,# On which statuses we should retryexceptions:Optional[Iterable[Type[Exception]]]=None,# On which exceptions we should retryretry_all_server_errors:bool=True,# If should retry all 500 errors or not# a callback that will run on response to decide if retryevaluate_response_callback:Optional[EvaluateResponseCallbackType]=None,):[email protected]_timeout(self,attempt:int,response:Optional[Response]=None)->float:raiseNotImplementedErrorYou can specifyRetryOptionsboth forRetryClientand it's methods.RetryOptionsin methods overrideRetryOptionsdefined inRetryClientconstructor.Important: by default all 5xx responses are retried + statuses you specified asstatusesparam If you will passretry_all_server_errors=Falsethan you can manually set what 5xx errors to retry.You can define your own timeouts logic or use:ExponentialRetrywith exponential backoffRandomRetryfor random backoffListRetrywith backoff you predefine by listFibonacciRetrywith backoff that looks like fibonacci sequenceJitterRetryexponential retry with a bit of randomnessImportant: you can proceed server response as an parameter for calculating next timeout.However this response can be None, server didn't make a response or you have set upraise_for_status=TrueLook here for an example:https://github.com/inyutin/aiohttp_retry/issues/59Additionally, you can specifyevaluate_response_callback. It receive aClientResponseand decide to retry or not by returning a bool. It can be useful, if server API sometimes response with malformed data.Request Trace ContextRetryClientaddcurrent attempt numbertorequest_trace_ctx(see examples, for more info seeaiohttp doc).Change parameters between retriesRetryClientalso has a method calledrequests. This method should be used if you want to make requests with different params.@dataclassclassRequestParams:method:strurl:_RAW_URL_TYPEtrace_request_ctx:Optional[Dict[str,Any]]=Nonekwargs:Optional[Dict[str,Any]]=Nonedefrequests(self,params_list:List[RequestParams],retry_options:Optional[RetryOptionsBase]=None,raise_for_status:Optional[bool]=None,)->_RequestContext:You can find an example of usage above or in tests.But basicallyRequestParamsis a structure to define params forClientSession.requestfunc.method,url,headerstrace_request_ctxdefined outside kwargs, because they are popular.There is also an old way to change URL between retries by specifyingurlas list of urls. Example:fromaiohttp_retryimportRetryClientretry_client=RetryClient()asyncwithretry_client.get(url=['/internal_error','/ping'])asresponse:text=awaitresponse.text()assertresponse.status==200asserttext=='Ok!'awaitretry_client.close()In this example we request/interval_error, fail and then successfully request/ping. If you specify less urls thanattemptsnumber inRetryOptions,RetryClientwill request last url at last attempts. This means that in example above we would request/pingonce again in case of failure.Typesaiohttp_retryis a typed project. It should be fully compatablie with mypy.It also introduce one special type:ClientType = Union[ClientSession, RetryClient]This type can be imported byfrom aiohttp_retry.types import ClientType
aiohttp-riak
aiohttp_riakriakhttpprotocol implementation foraiohttp.web.Exampleimportasyncioimportaiohttpfromaiohttp_riakimportRiakHTTP,Bucketasyncdefriak_requests(client):bucket=Bucket(client,'example')# Secondary indexesindexes=[('example_bin','ex'),('example_int','1')]awaitbucket.put('key','val',[indexes[0]])awaitbucket.put('key2','val2',[indexes[1]])awaitbucket.put('key3','val3',indexes)keys=awaitbucket.keys()print('KEYS',keys)keys=awaitbucket.index('example_bin','ex')print('INDEX_BIN',keys)keys=awaitbucket.index('example_int','1')print('INDEX_INT',keys)print('GET',awaitbucket.get('key2'))print('DEL',awaitbucket.delete('key2'))print('GET',awaitbucket.get('key2'))print('BUCKETS',awaitbucket.buckets())print('PING',awaitclient.ping())props=awaitbucket.props()print('PROPS',props)loop=asyncio.get_event_loop()rh=RiakHTTP('127.0.0.1',loop=loop)content=loop.run_until_complete(riak_requests(rh))rh.close()Licenseaiohttp_riakBSD license.CHANGES0.0.1 (2016-02-03)Init releaseCreditsaiohttp_riakis written byVeniamin Gvozdikov.ContributorsPlease add yourself here alphabetically when you submit your first pull request.
aiohttp-route
@route decorator for aiohttp.web that needs no global variables
aiohttp_route_decorator
aiohttp_route_decoratorThe library provides@routedecorator foraiohttp.web, resembling the contract [email protected] [email protected] isdiscouragedformultiplereasons; this one tries to solve part of those problems (theappdoesn’t need to be global at the very least).Installationpip install aiohttp_route_decoratorUsageCreate arouteobject in each of your handler modules, and decorate the handlers:# myapp/handlers.pyfromaiohttp_route_decoratorimportRouteCollectorroute=RouteCollector()@route('/')asyncdefindex(request):returnweb.Response(body=b'OK')@route('/publish',method='POST')asyncdefpublish(request):returnweb.Response(body=b'OK')@route('/login',methods=['GET','POST'],name='login')asyncdeflogin(request):ifrequest.method=='POST':returnweb.Response(body=b'OK')returnweb.Response(body=b'Login')When you init the application, push the collectedroutesintoapp.router:fromaiohttpimportwebfrommyappimporthandlersdefrun():app=web.Application()handlers.route.add_to_router(app.router)web.run_app(app)Non-decorator useIf you prefer to keep your routes together, you can construct the list manually after your handers:fromaiohttp_route_decoratorimportRouteCollector,Routeasyncdefindex(request):returnweb.Response(body=b'OK')asyncdefpublish(request):returnweb.Response(body=b'OK')asyncdeflogin(request):ifrequest.method=='POST':returnweb.Response(body=b'OK')returnweb.Response(body=b'Login')routes=RouteCollector([Route('/',index),Route('/publish',publish,method='POST'),Route('/login',login,methods=['GET','POST'],name='login'),])Prefixed routesYou can provide common route prefix that will be prepended to all routes:fromaiohttp_route_decoratorimportRouteCollectorroutes=RouteCollector(prefix='/app')@route('/')asyncdefindex(request):returnweb.Response(body=b'OK')@route('/publish',method='POST')asyncdefpublish(request):returnweb.Response(body=b'OK')...handlers.route.add_to_router(app.router)# /app/ -> index# /app/publish -> publishYou can also provide the prefix withinadd_to_router()call instead:fromaiohttp_route_decoratorimportRouteCollectorroutes=RouteCollector()@route('/')asyncdefindex(request):returnweb.Response(body=b'OK')@route('/publish',method='POST')asyncdefpublish(request):returnweb.Response(body=b'OK')...handlers.route.add_to_router(app.router,prefix='/app')# /app/ -> index# /app/publish -> publish…or use both:fromaiohttp_route_decoratorimportRouteCollectorroutes=RouteCollector(prefix='/app')@route('/')asyncdefindex(request):returnweb.Response(body=b'OK')@route('/publish',method='POST')asyncdefpublish(request):returnweb.Response(body=b'OK')...handlers.route.add_to_router(app.router,prefix='/project')# /project/app/ -> index# /project/app/publish -> publishThe non-decorator version ofRouteCollectorcan also accept prefix:fromaiohttp_route_decoratorimportRouteCollector,Routeasyncdefindex(request):returnweb.Response(body=b'OK')asyncdefpublish(request):returnweb.Response(body=b'OK')routes=RouteCollector(prefix='/app',routes=[Route('/',index),Route('/publish',publish,method='POST'),])Parameters referenceroute(path, *,method='GET',methods=None, name=None, **kwargs)path(str) — route path. Should be started with slash ('/').method(str) — HTTP method for route. Should be one of'GET','POST','PUT','DELETE','PATCH','HEAD','OPTIONS'or'*'for any method.methods(List[str]) — optional shortcut for creating several routes with different HTTP methods at once. If used, should be a list of acceptable values formethodargument.name(str) — optional route name.kwargs— other parameters to be passed toaiohttp.web.Resource.add_route().
aiohttp-route-middleware
aiohttp-routed-middlewareOverviewAn extension foraiohttpwhich provides route local middleware while remainining compatible with the existing router.With the built in router the technique for managing route local middleware is to make nested applications. However nested applications require a unique url prefix. so the following cannot be achieved:RequestMiddlewareHandlerGET /post/{id}authenticate, authorise(['post:read'])get_postPOST /post/{id}authenticate, authorise(['post:read:', 'post:write'])create_postDELETE /post/{id}authenticate, authorise(['post:read:', 'post:write'])delete_postThis router allows a chain of middleware terminated by a handler. For example:post_app=web.Application(router=UrlDispatcherEx())post_app.router.add_get('/{id}',authenticate,authorise(['post:read']),get_posts)post_app.router.add_post('/{id}',authenticate,authorise(['post:read','post:write']),get_posts)post_app.router.add_delete('/{id}',authenticate,authorise(['post:read','post:write']),get_posts)app=web.Application()app.add_subapp('/post',post_app)UsageBasicA middleware function differs from a normal request handler, in that it gets given the next handler to call.The following example shows how to add middleware to a route.fromaiohttpimportwebfromaiohttp_route_middlewareimportUrlDispatcherExapp=web.Application(router=UrlDispatcherEx())app.router.add_get('/',middleware1,middleware2,test)asyncdeftest(request):print("..entering handler")response=web.Response(text=f"extra_stuff=[{', '.join(request.extra_stuff)}]")print("..exiting handler")[email protected](request,handler):print("entering middleware 1")request.extra_stuff=['foo']response=awaithandler(request)print("exiting middleware 1")[email protected](request,handler):print(".entering middleware 2")request.extra_stuff.append('bar')response=awaithandler(request)print(".exiting middleware 2")returnresponseapp=web.Application(router=UrlDispatcherEx())app.router.add_get('/',middleware1,middleware2,test)web.run_app(app)This would print out the following:enteringmiddleware1.enteringmiddleware2..enteringhandler ..exitinghandler .exitingmiddleware2exitingmiddleware1Middleware failureA middleware function may choose not to call the next handler; for example if there was an authentication error.fromaiohttpimportwebfromaiohttp_route_middlewareimportUrlDispatcherExasyncdeftest(request):returnweb.Response(text="Success")@web.middlewareasyncdefauthenticate(request,handler):returnweb.Response(body="unauthenticated",status=401)app=web.Application(router=UrlDispatcherEx())app.router.add_get('/',authenticate,test)web.run_app(app)InstallationYou can install it using pip:pipinstallaiohttp-route-middlewareDetailsThe extension provides a routerUrlDispatcherExwhich extends from the built in classUrlDispatcher. The class can be used in the following manner:fromaiohttp_route_middlewareimportUrlDispatcherEx...app=web.Application(router=UrlDispatcherEx())The extension allows multiple handlers to be specified. The handlers are called in order until a handler returns a nonNoneresponse, at which point the response is returned and execution stops.An example of this might be a route to update a comment on a post, The sequence might be:Authenticate the user.Check the user is authorised to post a comment.Fetch the post.Post the comment.app.router.add_post('/comment?post_id=1234',authenticate,authorise,fetch_post,post_comment)Each handler is written in the same manner as a normal handler, in that it takes a single request argument. The request argument may be modified or enriched by each handler.
aiohttp-rpc
aiohttp-rpcA library for a simple integration of theJSON-RPC 2.0 protocolto a Python application usingaiohttp. The motivation is to provide a simple, fast and reliable way to integrate the JSON-RPC 2.0 protocol into your application on the server and/or client side.The library has only one dependency:aiohttp- Async http client/server frameworkTable Of ContentsInstallationpipUsageHTTP Server ExampleHTTP Client ExampleIntegrationMiddlewareWebSocketsWS Server ExampleWS Client ExampleAPI ReferenceMore examplesLicenseInstallationpippipinstallaiohttp-rpcUsageHTTP Server Examplefromaiohttpimportwebimportaiohttp_rpcdefecho(*args,**kwargs):return{'args':args,'kwargs':kwargs,}# If the function has rpc_request in arguments, then it is automatically passedasyncdefping(rpc_request):return'pong'if__name__=='__main__':aiohttp_rpc.rpc_server.add_methods([ping,echo,])app=web.Application()app.router.add_routes([web.post('/rpc',aiohttp_rpc.rpc_server.handle_http_request),])web.run_app(app,host='0.0.0.0',port=8080)HTTP Client Exampleimportaiohttp_rpcimportasyncioasyncdefrun():asyncwithaiohttp_rpc.JsonRpcClient('http://0.0.0.0:8080/rpc')asrpc:print('#1',awaitrpc.ping())print('#2',awaitrpc.echo('one','two'))print('#3',awaitrpc.call('echo',three='3'))print('#4',awaitrpc.notify('echo',123))print('#5',awaitrpc.get_methods())print('#6',awaitrpc.batch([['echo',2],'echo2','ping',]))loop=asyncio.get_event_loop()loop.run_until_complete(run())This prints:#1 pong #2 {'args': ['one', 'two'], 'kwargs': {}} #3 {'args': [], 'kwargs': {'three': '3'}} #4 None #5 {'get_method': {'doc': None, 'args': ['name'], 'kwargs': []}, 'get_methods': {'doc': None, 'args': [], 'kwargs': []}, 'ping': {'doc': None, 'args': ['rpc_request'], 'kwargs': []}, 'echo': {'doc': None, 'args': [], 'kwargs': []}} #6 ({'args': [2], 'kwargs': {}}, JsonRpcError(-32601, 'The method does not exist / is not available.'), 'pong')back to top↑ This is enough to start :sunglasses: ↑IntegrationThe purpose of this library is to simplify life, and not vice versa. And so, when you start adding existing functions, some problems may arise.Existing functions can return objects that are not serialized, but this is easy to fix. You can write ownjson_serialize:fromaiohttpimportwebimportaiohttp_rpcimportuuidimportjsonfromdataclassesimportdataclassfromfunctoolsimportpartial@dataclassclassUser:# The object that is not serializable.uuid:uuid.UUIDusername:str='mike'email:str='[email protected]'asyncdefget_user_by_uuid(user_uuid)->User:# Some function which returns not serializable object.# For example, data may be taken from a database.returnUser(uuid=uuid.UUID(user_uuid))defjson_serialize_unknown_value(value):ifisinstance(value,User):return{'uuid':str(value.uuid),'username':value.username,'email':value.email,}returnrepr(value)if__name__=='__main__':rpc_server=aiohttp_rpc.JsonRpcServer(json_serialize=partial(json.dumps,default=json_serialize_unknown_value),)rpc_server.add_method(get_user_by_uuid)app=web.Application()app.router.add_routes([web.post('/rpc',rpc_server.handle_http_request),])web.run_app(app,host='0.0.0.0',port=8080)..."""Example of response:{"id": 1,"jsonrpc": "2.0","result": {"uuid": "600d57b3-dda8-43d0-af79-3e81dbb344fa","username": "mike","email": "[email protected]"}}"""But you can go further. If you want to use functions that accept custom types, then you can do something like this:# The function (RPC method) that takes a custom type.defgenerate_user_token(user:User):returnf'token-{str(user.uuid).split("-")[0]}'asyncdefreplace_type(data):ifnotisinstance(data,dict)or'__type__'notindata:returndataifdata['__type__']=='user':returnawaitget_user_by_uuid(data['uuid'])raiseaiohttp_rpc.errors.InvalidParams# The middleware that converts typesasyncdeftype_conversion_middleware(request,handler):request.set_args_and_kwargs(args=[awaitreplace_type(arg)forarginrequest.args],kwargs={key:awaitreplace_type(value)forkey,valueinrequest.kwargs.items()},)returnawaithandler(request)rpc_server=aiohttp_rpc.JsonRpcServer(middlewares=[aiohttp_rpc.middlewares.exception_middleware,aiohttp_rpc.middlewares.extra_args_middleware,type_conversion_middleware,])"""Request:{"id": 1234,"jsonrpc": "2.0","method": "generate_user_token","params": [{"__type__": "user", "uuid": "600d57b3-dda8-43d0-af79-3e81dbb344fa"}]}Response:{"id": 1234,"jsonrpc": "2.0","result": "token-600d57b3"}"""Middlewareallows you to replace arguments, responses, and more.If you want to add permission checking for each method, then you can override the classJsonRpcMethodor usemiddleware.back to topMiddlewareMiddleware is used forRPC Request / RPC Responseprocessing. It has a similar interface asaiohttp middleware.importaiohttp_rpcimporttypingasyncdefsimple_middleware(request:aiohttp_rpc.JsonRpcRequest,handler:typing.Callable)->aiohttp_rpc.JsonRpcResponse:# Code to be executed for each RPC request before# the method (and later middleware) are called.response=awaithandler(request)# Code to be executed for each RPC request / RPC response after# the method is called.returnresponserpc_server=aiohttp_rpc.JsonRpcServer(middlewares=[aiohttp_rpc.middlewares.exception_middleware,simple_middleware,])Or useaiohttp middlewaresto processweb.Request/web.Response.back to topWebSocketsWS Server Examplefromaiohttpimportwebimportaiohttp_rpcasyncdefping(rpc_request):return'pong'if__name__=='__main__':rpc_server=aiohttp_rpc.WsJsonRpcServer(middlewares=aiohttp_rpc.middlewares.DEFAULT_MIDDLEWARES,)rpc_server.add_method(ping)app=web.Application()app.router.add_routes([web.get('/rpc',rpc_server.handle_http_request),])app.on_shutdown.append(rpc_server.on_shutdown)web.run_app(app,host='0.0.0.0',port=8080)WS Client Exampleimportaiohttp_rpcimportasyncioasyncdefrun():asyncwithaiohttp_rpc.WsJsonRpcClient('http://0.0.0.0:8080/rpc')asrpc:print(awaitrpc.ping())print(awaitrpc.notify('ping'))print(awaitrpc.batch([['echo',2],'echo2','ping',]))loop=asyncio.get_event_loop()loop.run_until_complete(run())back to topAPI Referenceserverclass JsonRpcServer(BaseJsonRpcServer)def __init__(self, *, json_serialize=json_serialize, middlewares=(), methods=None)def add_method(self, method, *, replace=False) -> JsonRpcMethoddef add_methods(self, methods, replace=False) -> typing.List[JsonRpcMethod]def get_method(self, name) -> Optional[Mapping]def get_methods(self) -> Mapping[str, Mapping]async def handle_http_request(self, http_request: web.Request) -> web.Responseclass WsJsonRpcServer(BaseJsonRpcServer)rpc_server: JsonRpcServerclientclass JsonRpcClient(BaseJsonRpcClient)async def connect(self)async def disconnect(self)async def call(self, method: str, *args, **kwargs)async def notify(self, method: str, *args, **kwargs)async def batch(self, methods])async def batch_notify(self, methods)class WsJsonRpcClient(BaseJsonRpcClient)protocolclass JsonRpcRequestid: Union[int, str, None]method: strjsonrpc: strextra_args: MutableMappingcontext: MutableMappingparams: Anyargs: Optional[Sequence]kwargs: Optional[Mapping]is_notification: boolclass JsonRpcResponseid: Union[int, str, None]jsonrpc: strresult: Anyerror: Optional[JsonRpcError]context: MutableMappingclass JsonRpcMethod(BaseJsonRpcMethod)def __init__(self, func, *, name=None, add_extra_args=True, prepare_result=None)class JsonRpcUnlinkedResultsclass JsonRpcDuplicatedResultsdecoratorsdef rpc_method(*, rpc_server=default_rpc_server, name=None, add_extra_args=True)errorsclass JsonRpcError(RuntimeError)class ServerError(JsonRpcError)class ParseError(JsonRpcError)class InvalidRequest(JsonRpcError)class MethodNotFound(JsonRpcError)class InvalidParams(JsonRpcError)class InternalError(JsonRpcError)DEFAULT_KNOWN_ERRORSmiddlewaresasync def extra_args_middleware(request, handler)async def exception_middleware(request, handler)DEFAULT_MIDDLEWARESutilsdef json_serialize(*args, **kwargs)constantsNOTHINGVERSION_2_0back to topMore examplesThe library allows you to add methods in many ways:importaiohttp_rpcdefping_1(rpc_request):return'pong 1'defping_2(rpc_request):return'pong 2'defping_3(rpc_request):return'pong 3'rpc_server=aiohttp_rpc.JsonRpcServer()rpc_server.add_method(ping_1)# 'ping_1'rpc_server.add_method(aiohttp_rpc.JsonRpcMethod(ping_2))# 'ping_2'rpc_server.add_method(aiohttp_rpc.JsonRpcMethod(ping_3,name='third_ping'))# 'third_ping'rpc_server.add_methods([ping_3])# 'ping_3'# Replace methodrpc_server.add_method(ping_1,replace=True)# 'ping_1'rpc_server.add_methods([ping_1,ping_2],replace=True)# 'ping_1', 'ping_2'Example with built-in functions:# Serverimportaiohttp_rpcrpc_server=aiohttp_rpc.JsonRpcServer(middlewares=[aiohttp_rpc.middlewares.extra_args_middleware])rpc_server.add_method(sum)rpc_server.add_method(aiohttp_rpc.JsonRpcMethod(zip,prepare_result=list))...# Clientasyncwithaiohttp_rpc.JsonRpcClient('/rpc')asrpc:assertawaitrpc.sum([1,2,3])==6assertawaitrpc.zip(['a','b'],[1,2])==[['a',1],['b',2]]Example with the decorator:importaiohttp_rpcfromaiohttpimportweb@aiohttp_rpc.rpc_method()defecho(*args,**kwargs):return{'args':args,'kwargs':kwargs,}if__name__=='__main__':app=web.Application()app.router.add_routes([web.post('/rpc',aiohttp_rpc.rpc_server.handle_http_request),])web.run_app(app,host='0.0.0.0',port=8080)It is possible to pass params into aiohttp request viadirect_call/direct_batch:importaiohttp_rpcjsonrpc_request=aiohttp_rpc.JsonRpcRequest(method_name='test',params={'test_value':1})asyncwithaiohttp_rpc.JsonRpcClient('/rpc')asrpc:awaitrpc.direct_call(jsonrpc_request,headers={'My-Customer-Header':'custom value'},timeout=10)back to topLicenseMIT
aiohttp-runner
Installpip install aiohttp-runnerExample usageimportasyncioimportaiohttp.webfromasync_generatorimportasynccontextmanagerfromaiohttp_runnerimport(simple_http_runner,gunicorn_http_runner,HttpRequest,HttpResponse,create_http_app,wait_for_interrupt,)@asynccontextmanagerasyncdefapp_factory():yieldcreate_http_app(routes=[('GET','/',http_handler),])asyncdefhttp_handler(_req:HttpRequest)->HttpResponse:returnaiohttp.web.Response(status=204)asyncdefmain()->None:bind='127.0.0.1:8080'runner=gunicorn_http_runner(app_factory,bind,workers=2)# ORrunner=simple_http_runner(app_factory,bind)asyncwithrunner:awaitwait_for_interrupt()if__name__=='__main__':asyncio.get_event_loop().run_until_complete(main())
aiohttp_runserver
Seegithub.com/samuelcolvin/aiohttp_runserverfor details.
aiohttp-s3-client
aiohttp-s3-clientThe simple module for putting and getting object from Amazon S3 compatible endpointsInstallationpipinstallaiohttp-s3-clientUsagefromhttpimportHTTPStatusfromaiohttpimportClientSessionfromaiohttp_s3_clientimportS3ClientasyncwithClientSession(raise_for_status=True)assession:client=S3Client(url="http://s3-url",session=session,access_key_id="key-id",secret_access_key="hackme",region="us-east-1")# Upload str object to bucket "bucket" and key "str"asyncwithclient.put("bucket/str","hello, world")asresp:assertresp.status==HTTPStatus.OK# Upload bytes object to bucket "bucket" and key "bytes"asyncwithawaitclient.put("bucket/bytes",b"hello, world")asresp:assertresp.status==HTTPStatus.OK# Upload AsyncIterable to bucket "bucket" and key "iterable"asyncdefgen():yieldb'some bytes'asyncwithclient.put("bucket/file",gen())asresp:assertresp.status==HTTPStatus.OK# Upload file to bucket "bucket" and key "file"asyncwithclient.put_file("bucket/file","/path_to_file")asresp:assertresp.status==HTTPStatus.OK# Check object exists using bucket+keyasyncwithclient.head("bucket/key")asresp:assertresp==HTTPStatus.OK# Get object by bucket+keyasyncwithclient.get("bucket/key")asresp:data=awaitresp.read()# Delete object using bucket+keyasyncwithclient.delete("bucket/key")asresp:assertresp==HTTPStatus.NO_CONTENT# List objects by prefixasyncforresultinclient.list_objects_v2("bucket/",prefix="prefix"):# Each result is a list of metadata objects representing an object# stored in the bucket.do_work(result)Bucket may be specified as subdomain or in object name:importaiohttpfromaiohttp_s3_clientimportS3Clientclient=S3Client(url="http://bucket.your-s3-host",session=aiohttp.ClientSession())asyncwithclient.put("key",gen())asresp:...client=S3Client(url="http://your-s3-host",session=aiohttp.ClientSession())asyncwithawaitclient.put("bucket/key",gen())asresp:...client=S3Client(url="http://your-s3-host/bucket",session=aiohttp.ClientSession())asyncwithclient.put("key",gen())asresp:...Auth may be specified with keywords or in URL:importaiohttpfromaiohttp_s3_clientimportS3Clientclient_credentials_as_kw=S3Client(url="http://your-s3-host",access_key_id="key_id",secret_access_key="access_key",session=aiohttp.ClientSession(),)client_credentials_in_url=S3Client(url="http://key_id:access_key@your-s3-host",session=aiohttp.ClientSession(),)CredentialsBy defaultS3Clienttrying to collect all available credentials from keyword arguments likeaccess_key_id=andsecret_access_key=, after that from the username and password from passedurlargument, so the next step is environment variables parsing and the last source for collection is the config file.You can pass credentials explicitly usingaiohttp_s3_client.credentialsmodule.aiohttp_s3_client.credentials.StaticCredentialsimportaiohttpfromaiohttp_s3_clientimportS3Clientfromaiohttp_s3_client.credentialsimportStaticCredentialscredentials=StaticCredentials(access_key_id='aaaa',secret_access_key='bbbb',region='us-east-1',)client=S3Client(url="http://your-s3-host",session=aiohttp.ClientSession(),credentials=credentials,)aiohttp_s3_client.credentials.URLCredentialsimportaiohttpfromaiohttp_s3_clientimportS3Clientfromaiohttp_s3_client.credentialsimportURLCredentialsurl="http://key@hack-me:your-s3-host"credentials=URLCredentials(url,region="us-east-1")client=S3Client(url="http://your-s3-host",session=aiohttp.ClientSession(),credentials=credentials,)aiohttp_s3_client.credentials.EnvironmentCredentialsimportaiohttpfromaiohttp_s3_clientimportS3Clientfromaiohttp_s3_client.credentialsimportEnvironmentCredentialscredentials=EnvironmentCredentials(region="us-east-1")client=S3Client(url="http://your-s3-host",session=aiohttp.ClientSession(),credentials=credentials,)aiohttp_s3_client.credentials.ConfigCredentialsUsing user config file:importaiohttpfromaiohttp_s3_clientimportS3Clientfromaiohttp_s3_client.credentialsimportConfigCredentialscredentials=ConfigCredentials()# Will be used ~/.aws/credentials configclient=S3Client(url="http://your-s3-host",session=aiohttp.ClientSession(),credentials=credentials,)Using the custom config location:importaiohttpfromaiohttp_s3_clientimportS3Clientfromaiohttp_s3_client.credentialsimportConfigCredentialscredentials=ConfigCredentials("~/.my-custom-aws-credentials")client=S3Client(url="http://your-s3-host",session=aiohttp.ClientSession(),credentials=credentials,)aiohttp_s3_client.credentials.merge_credentialsThis function collect all passed credentials instances and return a new one which contains all non-blank fields from passed instances. The first argument has more priority.importaiohttpfromaiohttp_s3_clientimportS3Clientfromaiohttp_s3_client.credentialsimport(ConfigCredentials,EnvironmentCredentials,merge_credentials)credentials=merge_credentials(EnvironmentCredentials(),ConfigCredentials(),)client=S3Client(url="http://your-s3-host",session=aiohttp.ClientSession(),credentials=credentials,)aiohttp_s3_client.credentials.MetadataCredentialsTrying to get credentials from the metadata service:importaiohttpfromaiohttp_s3_clientimportS3Clientfromaiohttp_s3_client.credentialsimportMetadataCredentialscredentials=MetadataCredentials()# start refresh credentials from metadata serverawaitcredentials.start()client=S3Client(url="http://your-s3-host",session=aiohttp.ClientSession(),)awaitcredentials.stop()Multipart uploadFor uploading large filesmultipart uploadingcan be used. It allows you to asynchronously upload multiple parts of a file to S3. S3Client handles retries of part uploads and calculates part hash for integrity checks.importaiohttpfromaiohttp_s3_clientimportS3Clientclient=S3Client(url="http://your-s3-host",session=aiohttp.ClientSession())awaitclient.put_file_multipart("test/bigfile.csv",headers={"Content-Type":"text/csv",},workers_count=8,)Parallel download to fileS3 supportsGETrequests withRangeheader. It's possible to download objects in parallel with multiple connections for speedup. S3Client handles retries of partial requests and makes sure that file won't be changed during download withETagheader. If your system supportspwritesyscall (Linux, macOS, etc.) it will be used to write simultaneously to a single file. Otherwise, each worker will have own file which will be concatenated after downloading.importaiohttpfromaiohttp_s3_clientimportS3Clientclient=S3Client(url="http://your-s3-host",session=aiohttp.ClientSession())awaitclient.get_file_parallel("dump/bigfile.csv","/home/user/bigfile.csv",workers_count=8,)
aiohttp-scraper
No description available on PyPI.
aiohttp-security
aiohttp_securityThe library provides identity and authorization foraiohttp.web.InstallationSimplest case (authorization via cookies)$ pip install aiohttp_securityWithaiohttp-sessionsupport$ pip install aiohttp_security[session]ExamplesTake a look at examples:Basic exampleExample with DB authand demos atdemodirectory.Documentationhttps://aiohttp-security.readthedocs.io/Developpip install-rrequirements-dev.txtLicenseaiohttp_securityis offered under the Apache 2 license.CHANGES0.5.0 (2023-11-18)Added type annotations.Added a reason message when permission is rejected.Switched toaiohttp.web.AppKey.Reverted change inJWTIdentityPolicyso identity returnsstr.0.4.0 (2018-09-27)Bump minimal supportedaiohttpversion to 3.2.Userequest.config_dictfor accessingjinja2environment. It allows to reuse jinja rendering engine from parent application.0.3.0 (2018-09-06)Deprecatelogin_requiredandhas_permissiondecorators. Usecheck_authorizedandcheck_permissionhelper functions instead.Bump supportedaiohttpversion to 3.0+.Enable strong warnings mode for test suite, clean-up all deprecation warnings.Polish documentation0.2.0 (2017-11-17)Addis_anonymous,login_required,has_permissionhelpers. (#114)0.1.2 (2017-10-17)Make aiohttp-session optional dependency. (#107)
aiohttp-send
Send file in for aiohttp.web (http server for asyncio)
aiohttp-sendgrid
SendGrid mail API wrapperInstallationpip install aiohttp_sendgridUsageCreate an instance of API client:importasynciofromaiohttp_sendgridimportSendgridapi_key='<your_sendgrid_api_key>'mailer=Sendgrid(api_key=api_key)Important to note that ifapi_keyis not provided then it will try to readSENDGRID_API_KEYenvironment variableSend email to single recipientto='[email protected]'sender='[email protected]'subject='greetings'content='<h1>Hello</h1>'send_mail=mailer.send(to,sender,subject,content)loop=asyncio.get_event_loop()loop.run_until_complete(send_mail)Bothtoandsendermight be also a dictionary withemailkey, if you want to specify name for sender or recipient then addnamekey to the dictionary. Thus,to = {'email': '[email protected]', 'name': 'Recipient'}is also a correct value.Send single email to multiple recipientsto=['[email protected]','another@example']sender='[email protected]'subject='greetings'content='<h1>Hello</h1>'send_mail=mailer.send(to,sender,subject,content)loop=asyncio.get_event_loop()loop.run_until_complete(send_mail)tomight be tuple or list of strings or dictionaries.
aiohttp-sentry
Anaiohttpserver middleware for reporting failed requests toSentryUsageJust addSentryMiddlewareas a middleware:fromaiohttpimportwebfromaiohttp_sentryimportSentryMiddlewareapp=web.Application(middlewares=[SentryMiddleware()])ConfigurationIf you want to customize error reporting, you can use the optionalsentry_kwargsparameter, which is adictof kwargs passed to the lower-level Sentry library,raven. With this, you can specify environment details, filter out specific exceptions, and so on:fromaiohttpimportwebfromaiohttp_sentryimportSentryMiddlewareapp=web.Application(middlewares=(SentryMiddleware({'environment':'foo','release':'bar','ignore_exceptions':'aiohttp.HTTPClientError'}),# ...),)If you are using the standard library’sloggingmodule, we have a convenient parameter to patch it for you, to have logger calls send events to Sentry automatically:WarningThis modifies your logging configuration globally when you instantiate the middleware. Even if you don’t end up using the middleware instance for a request, all your logs will be sent to Sentry.importloggingfromaiohttpimportwebfromaiohttp_sentryimportSentryMiddlewareapp=web.Application(middlewares=[SentryMiddleware(patch_logging=True,sentry_log_level=logging.WARNING)],)Attaching Data to EventsBy default,aiohttp-sentrypasses this data alongside reported exceptions:HTTP schemeHTTP methodURLQuery StringRequest Headers (including cookies)Requester’s IP addressIf you need more data in sentry, you can do that by subclassing fromSentryMiddlewareand overriding theget_extra_datamethod, which returns all the above by default. Here’s what that looks like:classDetailedSentryMiddleware(SentryMiddleware):asyncdefget_extra_data(self,request):return{**awaitsuper().get_extra_data(request),'settings':request.app['settings'],}Whileget_extra_datais a coroutine, which means it can make database queries, API calls, or other I/O operations, use this carefully! Make sure you understand the implications of executing expensive operations every time an error happens. If the root cause of the error is an overloaded database, you are just going to make the problem worse, while not even being able to get the extra info you wanted.
aiohttp-serve
aiohttp-serveaiohttp-servepackage allows you to runaiohttp.web.Applicationon multiple workers/processes (if for some reason you don't want to use external servers such as gunicorn etc.)RequirementsPython >= 3.7aiohttp >= 3.7.4PyYAML>=5.4.1 (optional)Installationpip install aiohttp-serveUsageweb.pyfromaiohttpimportwebasyncdefindex(request):returnweb.Response(body='Hello world')app=web.Application()app.router.add_get('/',index)simple usage:fromaiohttp_serveimportserveif__name__=='__main__':serve('web:app',host='127.0.0.1',port=8080,workers=4,)bind to multiple host/port/path:fromaiohttp_serveimportserveif__name__=='__main__':serve('web:app',bind=['http://127.0.0.1:80','https://127.0.0.1:443','unix:/path/to/unix/socket.sock',],workers=4,ssl_certfile='/path/to/cert.crt',ssl_keyfile='/path/to/key.key',)logging:Just configure logging at module levelimportyamlimportlogging.configfromaiohttp_serveimportservewithopen('./examples/logging.yaml',mode='r')asf:logging.config.dictConfig(yaml.safe_load(f))if__name__=='__main__':serve('web:app',host='127.0.0.1',port=8080,workers=4,)of uselog_configarg (dict, .json or .yaml or .conf file)fromaiohttp_serveimportserveif__name__=='__main__':serve('web:app',host='127.0.0.1',port=8080,workers=4,log_config='./examples/logging.yaml',)
aio.http.server
aio.http.serverHTTP server for theaioasyncio frameworkBuild statusInstallationRequires python >= 3.4Install with:pipinstallaio.http.serverQuick start - Hello world http serverCreate a web server that says helloSave the following into a file “hello.conf”[server/my_server]factory=aio.http.server.factoryport=8080protocol=my_example.protocolAnd save the following into a file named my_example.pyimportasyncioimportaiohttpimportaio.app@aio.app.server.protocoldefprotocol(name):loop=asyncio.get_event_loop()webapp=aiohttp.web.Application(loop=loop)@asyncio.coroutinedefhandle_hello_world(webapp):returnaiohttp.web.Response(body=b"Hello, world")webapp.router.add_route("GET","/",handle_hello_world)returnwebapp.make_handler()Run with the aio run commandaiorun-chello.confaio.http.server usageConfigurationCreate a server config with the aio.http.server.factory factory and suppressing normal output>>> config = """ ... [aio] ... log_level = ERROR ... ... [server/test] ... factory: aio.http.server.factory ... port: 7070 ... """Running an http serverBy default the http server will respond with a 404 as there are no routes set up>>> import asyncio >>> import aiohttp >>> from aio.app.runner import runner >>> import aio.testing>>> @aio.testing.run_forever(sleep=1) ... def run_http_server(): ... runner(['run'], config_string=config) ... ... def call_http_server(): ... result = yield from ( ... yield from aiohttp.request( ... "GET", "http://localhost:7070")).read() ... print(result) ... ... return call_http_server>>> run_http_server() b'404: Not Found'The server object is accessible from the aio.app.servers[{name}] var>>> import aio.app>>> aio.app.servers['test'] <Server sockets=[<socket.socket...laddr=('0.0.0.0', 7070)...]>Lets clear the app>>> aio.app.clear()Running the server with a custom protocolIf you specify a protocol in the “server/” config, the http server will use that function as a protocol factory.The function should be a coroutine and is called with the name of the server>>> config_with_protocol = """ ... [aio] ... log_level = ERROR ... ... [server/test] ... factory = aio.http.server.factory ... protocol = aio.http.server.tests._example_http_protocol ... port = 7070 ... """We need to decorate the protocol with aio.app.server.protocol>>> @aio.app.server.protocol ... def http_protocol(name): ... loop = asyncio.get_event_loop() ... http_app = aiohttp.web.Application(loop=loop) ... http_app['name'] = name ... ... @asyncio.coroutine ... def handle_hello_world(http_app): ... return aiohttp.web.Response(body=b"Hello, world") ... ... http_app.router.add_route("GET", "/", handle_hello_world) ... return http_app.make_handler()>>> aio.http.server.tests._example_http_protocol = http_protocol>>> @aio.testing.run_forever(sleep=1) ... def run_http_server(): ... runner(['run'], config_string=config_with_protocol) ... ... def call_http_server(): ... result = yield from ( ... yield from aiohttp.request( ... "GET", "http://localhost:7070")).read() ... ... print(result) ... ... return call_http_server>>> run_http_server() b'Hello, world'
aiohttp-session
aiohttp_sessionThe library provides sessions foraiohttp.web.UsageThe library allows us to store user-specific data into a session object.The session object has a dict-like interface (operations likesession[key] = value,value = session[key]etc. are present).Before processing the session in a web-handler, you have to register thesession middlewareinaiohttp.web.Application.A trivial usage example:importtimefromcryptographyimportfernetfromaiohttpimportwebfromaiohttp_sessionimportsetup,get_sessionfromaiohttp_session.cookie_storageimportEncryptedCookieStorageasyncdefhandler(request):session=awaitget_session(request)last_visit=session['last_visit']if'last_visit'insessionelseNonesession['last_visit']=time.time()text='Last visited:{}'.format(last_visit)returnweb.Response(text=text)defmake_app():app=web.Application()fernet_key=fernet.Fernet.generate_key()f=fernet.Fernet(fernet_key)setup(app,EncryptedCookieStorage(f))app.router.add_get('/',handler)returnappweb.run_app(make_app())All storages use an HTTP Cookie namedAIOHTTP_SESSIONfor storing data. This can be modified by passing the keyword argumentcookie_nameto the storage class of your choice.Available session storages are:aiohttp_session.SimpleCookieStorage()– keeps session data as a plain JSON string in the cookie body. Use the storage only for testing purposes, it’s very non-secure.aiohttp_session.cookie_storage.EncryptedCookieStorage(secret_key)– stores the session data into a cookie asSimpleCookieStoragebut encodes it via AES cipher.secrect_keyis abyteskey for AES encryption/decryption, the length should be 32 bytes.Requirescryptographylibrary:$ pip install aiohttp_session[secure]aiohttp_session.redis_storage.RedisStorage(redis_pool)– stores JSON encoded data inredis, keeping only the redis key (a random UUID) in the cookie.redis_poolis aredisobject, created byawaitaioredis.from_url(...)call.$ pip install aiohttp_session[aioredis]DevelopingInstall for local development:$ make setupRun linters:$ make lintRun tests:$ make testThird party extensionsaiohttp_session_mongoaiohttp_session_dynamodbLicenseaiohttp_sessionis offered under the Apache 2 license.2.12.0 (2022-10-28)Migrated fromaioredistoredis(if using redis without installingaiohttp-session[aioredis]then it will be necessary to manually installredis).2.11.0 (2021-01-31)Support initialisingEncryptedCookieStoragewithFernetobject directly.Fix an issue where the session would get reset before the cookie expiry.2.10.0 (2021-12-30)Typing supportAdd samesite cookie optionSupport aioredis 22.9.0 (2019-11-04)Fix memcached expiring time (#398)2.8.0 (2019-09-17)Make this compatible with Python 3.7+. Import from collections.abc, instead of from collections. (#373)2.7.0 (2018-10-13)Reset a session if the session age > max_age (#331)Reset a session on TTL expiration for EncryptedCookieStorage (#326)2.6.0 (2018-09-12)Create a new session ifNaClCookieStoragecannot decode a corrupted cookie (#317)2.5.0 (2018-05-12)Add an API for requesting new session explicitly (#281)2.4.0 (2018-05-04)Fix a bug for session fixation (#272)2.3.0 (2018-02-13)Support custom encoder and decoder by all storages (#252)Bump to aiohttp 3.02.2.0 (2018-01-31)Fixed the formatting of an error handling bad middleware return types. (#249)2.1.0 (2017-11-24)Addsession.set_new_identity()method for changing identity for a new session (#236)2.0.1 (2017-11-22)Replace assertions in aioredis installation checks byRuntimeError(#235)2.0.0 (2017-11-21)Update to aioredis 1.0+. The aiohttp-session 2.0 is not compatible with aioredis 0.X (#234)1.2.1 (2017-11-20)Pin aioredis<1.0 (#231)1.2.0 (2017-11-06)Add MemcachedStorage (#224)1.1.0 (2017-11-03)Upgrade middleware to new style from aiohttp 2.3+1.0.1 (2017-09-13)Add key_factory attribute for redis_storage (#205)1.0.0 (2017-07-27)Catch decoder exception in RedisStorage on data load (#175)Specify domain and path on cookie deletion (#171)0.8.0 (2016-12-04)Usetime.time()instead oftime.monotonic()for absolute times (#81)0.7.0 (2016-09-24)Fix tests to be compatible with aiohttp upstream API for client cookies0.6.0 (2016-09-08)Add expires field automatically to support older browsers (#43)Respect session.max_age in redis storage #45Always pass default max_age from storage into session (#45)0.5.0 (2016-02-21)Handle cryptography.fernet.InvalidToken exception by providing an empty session (#29)0.4.0 (2016-01-06)Add optional NaCl encrypted storage (#20)Relax EncryptedCookieStorage to accept base64 encoded string, e.g. generated by Fernet.generate_key.Add setup() functionSave the session even on exception in the middleware chain0.3.0 (2015-11-20)Reflect aiohttp changes: minimum required Python version is 3.4.1Use explicit ‘aiohttp_session’ package0.2.0 (2015-09-07)Add session.created property (#14)Replaced PyCrypto with crypthography library (#16)0.1.2 (2015-08-07)Add manifest file (#15)0.1.1 (2015-04-20)Fix #7: stop cookie name growing each time session is saved0.1.0 (2015-04-13)First public release
aiohttp-session-file
The library provides file sessions store foraiohttp.web.UsageA trivial usage example:importasyncioimportshutilimporttempfileimporttimefromaiohttpimportwebfromaiohttp_sessionimportsetup,get_sessionfromaiohttp_session_fileimportFileStorageasyncdefhandler(request):session=awaitget_session(request)last_visit=session['last_visit']if'last_visit'insessionelseNonesession['last_visit']=time.time()text='Last visited:{}'.format(last_visit)returnweb.Response(text=text)asyncdefsetup_dir(app):dirpath=tempfile.mkdtemp(prefix='aiohttp-session-')asyncdefremove_dir(app):shutil.rmtree(dirpath)app.on_cleanup.append(remove_dir)returndirpathasyncdefmake_app():app=web.Application()dirpath=awaitsetup_dir(app)max_age=3600*24*365# 1 yearsetup(app,FileStorage(dirpath,max_age=max_age))app.router.add_get('/',handler)returnappweb.run_app(make_app())NoteExpiry session files need to be cleaned up outside of this tiny library. Please refer toissue#1.
aiohttp_session_flash
aiohttp_session_flashThe library provides flash messages foraiohttp.webon top ofaiohttp_session.“Flash messages” are simply a queue of string messages (or other JSON-serializable objects) stored in the session.Installationpip install aiohttp_session_flashUsageAddsession_middlewareandaiohttp_session_flash.middlewareto the list ofapp’s middleware:app=web.Application(middlewares=[aiohttp_session.session_middleware(EncryptedCookieStorage(b'x'*32)),aiohttp_session_flash.middleware,])Within the handler, pull and push flash messages as needed:fromaiohttpimportwebfromaiohttp_session_flashimportflash,pop_flashasyncdeffoo(request):flash(request,"Hello")flash(request,["This","works","too"])returnweb.Response(body=b'Flashed some messages')asyncdefbar(request):formessageinpop_flash(request):print(message)returnweb.Response(body=b'OK')Template context processorThe template context processor is provided for template libraries that can use it:aiohttp_mako_context_processors.setup(app,[...aiohttp_session_flash.context_processor,])<ul>%formessageinget_flashed_messages():<li>${message}</li>%endfor</ul>ContributingRunning testspip install -r requirements_test.txt pytest
aiohttp-session-mongo
aiohttp_session_mongo===============.. image:: https://travis-ci.org/alexpantyukhin/aiohttp-session-mongo.svg?branch=master:target: https://travis-ci.org/alexpantyukhin/aiohttp-session-mongo.. image:: https://codecov.io/github/alexpantyukhin/aiohttp-session-mongo/coverage.svg?branch=master:target: https://codecov.io/github/alexpantyukhin/aiohttp-session-mongoThe library provides mongo sessions store for `aiohttp.web`__... _aiohttp_web: https://aiohttp.readthedocs.io/en/latest/web.html__ aiohttp_web_Usage-----A trivial usage example:.. code:: pythonimport timefrom aiohttp import webfrom aiohttp_session import setup, get_sessionfrom aiohttp_session_mongo import MongoStorageimport motor.motor_asyncio as aiomotorimport asyncioasync def handler(request):session = await get_session(request)last_visit = session['last_visit'] if 'last_visit' in session else Nonesession['last_visit'] = time.time()text = 'Last visited: {}'.format(last_visit)return web.Response(text=text)async def init_mongo(loop):url = "mongodb://localhost:27017"conn = aiomotor.AsyncIOMotorClient(url, maxPoolSize=2, io_loop=loop)db = 'my_db'return conn[db]async def setup_mongo(app, loop):db = await init_mongo(loop)async def close_mongo(app):db.client.close()app.on_cleanup.append(close_mongo)return dbasync def make_app():app = web.Application()loop = asyncio.get_event_loop()db = await setup_mongo(app, loop)session_collection = db['sessions']max_age = 3600 * 24 * 365 # 1 yearsetup(app, MongoStorage(session_collection, max_age=max_age))app.router.add_get('/', handler)return appweb.run_app(make_app())
aiohttp-session-ws
Simply put: associate your websockets with a user’s session, and close those connections when you see fit.For example, let’s say you’re usingaiohttp_securityand a user chooses to log in or log out. Usingaiohttp_session_wsyou can disconnect the open websocket subscriptions associated with their session, and force them to re-connect and re-authorize thier websocket subscriptions.Basic ExampleThe pieces of code in this example are taken from thedemodirectory of this repository.asyncdefhandle_root(request):returnweb.Response(text='Hello world',content_type="text/html")asyncdefhandle_reset(request):session_ws_id=awaitget_session_ws_id(request)response=web.Response(text=f"Reset called on session{session_ws_id}!",content_type="text/plain",)awaitschedule_close_all_session_ws(request,response)awaitnew_session_ws_id(request)returnresponseasyncdefhandle_websocket(request):asyncwithsession_ws(request)aswsr:connected_at=datetime.now()session_ws_id=awaitget_session_ws_id(request)whileTrue:awaitwsr.send_str(f"Websocket associated with session [{session_ws_id}] "f"connected for{(datetime.now()-connected_at).seconds}")awaitasyncio.sleep(1)returnwsrdefmake_app():app=web.Application(middlewares=[aiohttp_session.session_middleware(aiohttp_session.SimpleCookieStorage()),session_ws_middleware,])app.router.add_get("/",handle_root)app.router.add_get("/reset",handle_reset)app.router.add_get("/ws",handle_websocket)setup_session_websockets(app,SessionWSRegistry())returnappUse the code from thedemofolder, which includes a simple template to interact with the websocket in your web-browser.Narrative APIThis package is designed to be straightforward and easy to use. This lightweight documentation doesn’t attempt to replace the need to read the code, so you’re encouraged to go do exactly that.There are a few moving pieces, but if (and when) you need to do something more complex, you can subclass away.SessionWSRegistryThis is the core ofaiohttp_session_ws.It’s construction is noteworthy:SessionWSRegistry(self, *, id_factory, session_key)id_factorygenerates a session-wide id that associates the websockets. The default id_factory returns a UUID4, but you can supply your own callable (async callables are supported, too). the function signature ofid_factoryis:id_factory(request: aiohttp.web.Request)->typing.HashableSo pretty much, return something that can be the key in a dictionary (strings, integers, etc.).session_keyis the name of the key in the session that maps to the session-wide websocket identifier. By default it’s a sensibleaiohttp_session_ws_id.HelpersYou won’t need to interact withSessionWSRegistrydirectly after you’ve created it, but know that it’s available in youraiohttp.web.Application(access it like this:app['aiohttp_session_ws_registry']).The friendly global manipulators of this object are:get_session_ws_id(request)new_session_ws_id(request)delete_session_ws_id(request)ensure_session_ws_id(request)schedule_close_all_session_ws(request, response)These methods are importable directly fromaiohttp_session_ws.Notice thatschedule_close_all_session_wstakes a response object. This allows us to end thekeep-alivestatus of the response (viaaiohttp.web.Response.force_close). This means that as soon as your user has finished receiveing the response, their outstanding websockets will close.This also means that if you have users with re-connecting websockets, you should probably follow this pattern:asyncdefhandle_logout(request):response=web.HTTPFound('/')awaitschedule_close_all_session_ws(request,response)awaitaiohttp_session.new_session(request)awaitnew_session_ws_id(request)returnresponsesession_wsTo track the websockets, you’ll use the async context managersession_ws. This context manager upgrades the request, and provides itsaiothttp.web.WebSocketResponsecounterpart. Use if like this:asyncdefhandle_websocket(request):asyncwithsession_ws(request)aswsr:asyncformsginwsr:awaitwsr.send_str(f'Heard:{ws.data}')returnwsrThat’s it. Pretty simple, right? If you’d like to provide theaiohttp.web.WebSocketResponsewith initialization options (for example, the supported websocket protocols), pass those along tosession_wsas named arguments.asyncdefhandle_websocket(request):asyncwithsession_ws(request,protocols=('graphql-ws',))aswsr:asyncformsginwsr:awaitwsr.send_str(f'Heard:{ws.data}')returnwsrAs mentioned in theNotesbelow, it’s important that your users have asession_ws idprior to attempting a websocket connection (hint: Safari).Use thesession_ws_middlewareto automatically add the key to your sessions. It should be inside the call-stack ofaiohttp_session.session_middleware:web.Application(middlewares=[aiohttp_session.session_middleware(aiohttp_session.SimpleCookieStorage()),session_ws_middleware,])Finally, to set all of this up, you’ll want to use thesetupmethod (feel encourged to import it assetup_session_ws).Basic usage looks like this:web.Application(middlewares=[aiohttp_session.session_middleware(aiohttp_session.SimpleCookieStorage()),session_ws_middleware,])setup(app,SessionWSRegistry())# <------# etc...returnappNotesWhilesession_wsgenerates anaiohttp_session_ws_idupon connect (if it’s not present), some browsers don’t respectSet-Cookieon a websocket upgrade (e.g. Safari).Therefore it’s best if you ensure that anaiohttp_session_ws_idis present in the users session prior to attempting a websocket connection (if usingaiohttp_session.SimpleCookieStorageoraiohttp_session.EncryptedCookieStorage).If you’re using something more advanced that stores a reference to the session in the session cookie, and stores the actual value server-side (likeaiohttp_session.RedisStorage), then it’s not important whenaiohttp_session_ws_idis set on the cookie, but it is still important that the user has a session cookie prior to a connection attempt.If you want to put the session-ws-id (usuallyaiohttp_session_ws_id) somewhere else in the session, or derive it from the request, you can. Simply subclassSessionWSRegistryand revise theget_id,set_id, anddelete_idmethods.If you have a cluster of webservers, you’ll need to subclassSessionWSRegistryand revise theregisterandunregisterfunctions so listen on a message broker (for example, usingaioredisand its pubsub feature).
aiohttp-setup
No description available on PyPI.
aiohttp-simple
aiohttp-simplesimplify the use of aiohttp
aiohttp-socks
aiohttp-socksTheaiohttp-sockspackage provides a proxy connector foraiohttp. Supports SOCKS4(a), SOCKS5(h), HTTP (tunneling) as well as Proxy chains. It usespython-socksfor core proxy functionality.RequirementsPython >= 3.6aiohttp >= 2.3.2python-socks[asyncio] >= 1.0.1Installationpip install aiohttp_socksUsageaiohttp usage:importaiohttpfromaiohttp_socksimportProxyType,ProxyConnector,ChainProxyConnectorasyncdeffetch(url):connector=ProxyConnector.from_url('socks5://user:[email protected]:1080')### or use ProxyConnector constructor# connector = ProxyConnector(# proxy_type=ProxyType.SOCKS5,# host='127.0.0.1',# port=1080,# username='user',# password='password',# rdns=True# )### proxy chaining (since ver 0.3.3)# connector = ChainProxyConnector.from_urls([# 'socks5://user:[email protected]:1080',# 'socks4://127.0.0.1:1081',# 'http://user:[email protected]:3128',# ])asyncwithaiohttp.ClientSession(connector=connector)assession:asyncwithsession.get(url)asresponse:returnawaitresponse.text()aiohttp-socks also providesopen_connectionandcreate_connectionfunctions:fromaiohttp_socksimportopen_connectionasyncdeffetch():reader,writer=awaitopen_connection(proxy_url='socks5://user:[email protected]:1080',host='check-host.net',port=80)request=(b"GET /ip HTTP/1.1\r\n"b"Host: check-host.net\r\n"b"Connection: close\r\n\r\n")writer.write(request)returnawaitreader.read(-1)Why yet another SOCKS connector for aiohttpUnlikeaiosocksy, aiohttp_socks has only single point of integration with aiohttp. This makes it easier to maintain compatibility with new aiohttp versions.
aiohttp-socksx
aiohttp-socksTheaiohttp-sockspackage provides a proxy connector foraiohttp. Supports SOCKS4(a), SOCKS5(h), HTTP (tunneling) as well as Proxy chains. It usespython-socksfor core proxy functionality.RequirementsPython >= 3.6aiohttp >= 2.3.2python-socks[asyncio] >= 1.0.1Installationpip install aiohttp_socksUsageaiohttp usage:importaiohttpfromaiohttp_socksimportProxyType,ProxyConnector,ChainProxyConnectorasyncdeffetch(url):connector=ProxyConnector.from_url('socks5://user:[email protected]:1080')### or use ProxyConnector constructor# connector = ProxyConnector(# proxy_type=ProxyType.SOCKS5,# host='127.0.0.1',# port=1080,# username='user',# password='password',# rdns=True# )### proxy chaining (since ver 0.3.3)# connector = ChainProxyConnector.from_urls([# 'socks5://user:[email protected]:1080',# 'socks4://127.0.0.1:1081',# 'http://user:[email protected]:3128',# ])asyncwithaiohttp.ClientSession(connector=connector)assession:asyncwithsession.get(url)asresponse:returnawaitresponse.text()aiohttp-socks also providesopen_connectionandcreate_connectionfunctions:fromaiohttp_socksimportopen_connectionasyncdeffetch():reader,writer=awaitopen_connection(proxy_url='socks5://user:[email protected]:1080',host='check-host.net',port=80)request=(b"GET /ip HTTP/1.1\r\n"b"Host: check-host.net\r\n"b"Connection: close\r\n\r\n")writer.write(request)returnawaitreader.read(-1)Why yet another SOCKS connector for aiohttpUnlikeaiosocksy, aiohttp_socks has only single point of integration with aiohttp. This makes it easier to maintain compatibility with new aiohttp versions.
aiohttp_splunk_logging
No description available on PyPI.
aiohttp-spotify
An async Python interface to the Spotify API usingaiohttp.Note: This is alpha software. Use at your own risk.InstallationTo install, use pip:python-mpipinstallaiohttp_spotifyIt's best if you also install and useaiohttp-session.UsageTo add the OAuth flow to your app:fromaiohttpimportwebimportaiohttp_spotifyasyncdefhandle_auth(request:web.Request,auth:aiohttp_spotify.SpotifyAuth):# Store the `auth` object for use laterapp=web.Application()app["spotify_app"]=aiohttp_spotify.spotify_app(client_id=CLIENT_ID,client_secret=CLIENT_SECRET,redirect_uri=REDIRECT_URI,handle_auth=handle_auth,)app.add_subapp("/spotify",app["spotify_app"])Then you can make calls to the API as follows:fromaiohttpimportClientSessionasyncdefcall_api(request:web.Request)->web.Response:asyncwithClientSession()assession:response=app["spotify_app"]["spotify_client"].request(session,auth,"/me")# The auth object will be updated as tokens expire so you should# update this however you have it stored:ifresponse.auth_changed:awaithandle_auth(request,response.auth)returnweb.json_request(response.json())whereauthis theSpotifyAuthobject from above.Take a look atthe demo directoryfor a more complete example.
aiohttp-spyne
AboutAiohttp transport for Spyne RPC library.Requirements:Python 3.7, 3.8, 3.9, 3.10, 3.11Aiohttp >= 3.7.0Spyne >= 2.14.0Spyne alpha versions should also work.InstallationJust runpip install aiohttp-spyne:)ExamplesTest server:python -m examples.hello_worldThreaded test server:python -m examples.hello_world_threadsTest client:python -m examples.test_clientUsageFirst, initialize your spyne application as normal. Here's an example for a simple SOAP service (See spyne examples and documentation for a more complete service setup).spyne_app = spyne.Application( [HelloWorldService], tns='aiohttp_spyne.examples.hello', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11())Next, wrap your Spyne application with AIOSpyne. Note that you can run your application entrypoints in a thread by setting the "threads" parameter. If you want to keep your entrypoints running in the same thread as the main application, just leave this None. If you DO run your entrypoints in threads, be aware that some signals sent by spyne will also be run in threads, and be extra careful of using your main loop!handler = AIOSpyne(spyne_app, threads=25)Lastly, make an aiohttp application as usual, and just bind GET and POST entrypoints from AIOSpyne to wherever. Note that both paths need to be the same.With GET, if the request address ends ?wsdl or .wsdl, a WSDL schema is returned in a response. Otherwise, requests are redirected to spynes RPC handler.app = web.Application() app.router.add_get('/{tail:.*}', handler.get) app.router.add_post('/{tail:.*}', handler.post) web.run_app(app, port=8080)Chunked encodingIf you offer large result sets in your soap entrypoints, and yield the results properly, you may want to enable chunked encoding. This way the aiohttp server can stream your results and reduce memory usage.handler = AIOSpyne(spyne_app, chunked=True)WSDL cachingBy default, aiohttp-spyne will cache WSDL documents generated by spyne. This makes it cheap to offer the WSDL documents to any clients. If for some reason you want to disable this caching, you can do so by setting the cache_wsdl argument as False.handler = AIOSpyne(spyne_app, cache_wsdl=False)Testing and formattingpytestmypy -p aiohttp_spyneblack aiohttp_spyne/LicenseLGPL-2.1 -- Please see LICENSE for details.
aiohttp-sqlalchemy
SQLAlchemy 1.4 / 2.0support forAIOHTTP.The library provides the next features:initializing asynchronous sessions through a middlewares;initializing asynchronous sessions through a decorators;simple access to one asynchronous session by default key;preventing attributes from being expired after commit by default;support different types of request handlers;support nested applications.Documentationhttps://aiohttp-sqlalchemy.readthedocs.ioInstallationpip install aiohttp-sqlalchemySimple exampleInstallaiosqlitefor work with sqlite3:pip install aiosqliteCopy and paste this code in a file and run:fromdatetimeimportdatetimeimportsqlalchemyassafromaiohttpimportwebfromsqlalchemyimportormimportaiohttp_sqlalchemyasahsametadata=sa.MetaData()Base=orm.declarative_base(metadata=metadata)classMyModel(Base):__tablename__='my_table'pk=sa.Column(sa.Integer,primary_key=True)timestamp=sa.Column(sa.DateTime(),default=datetime.now)asyncdefmain(request):sa_session=ahsa.get_session(request)asyncwithsa_session.begin():sa_session.add(MyModel())result=awaitsa_session.execute(sa.select(MyModel))result=result.scalars()data={instance.pk:instance.timestamp.isoformat()forinstanceinresult}returnweb.json_response(data)asyncdefapp_factory():app=web.Application()ahsa.setup(app,[ahsa.bind('sqlite+aiosqlite:///'),])awaitahsa.init_db(app,metadata)app.add_routes([web.get('/',main)])returnappif__name__=='__main__':web.run_app(app_factory())
aiohttp-sse
No description available on PyPI.