Saravanan666/pypi-org huggingface dataset:
Package: aiohttp-swagger3
aiohttp-swagger3AboutPackage for displaying swagger docs via different UI backends and
optionally validating/parsing aiohttp requests using swagger
specification 3.0, known as OpenAPI3.Supported UI backendsMultiple UI backends can be used or UI backend can be disabled at all if only needed
validation without being able to view documentation.Swagger UI -https://github.com/swagger-api/swagger-uiReDoc -https://github.com/Redocly/redocRapiDoc -https://github.com/mrin9/RapiDocDocumentationhttps://aiohttp-swagger3.readthedocs.io/en/latest/Disable validationPassvalidate=FalsetoSwaggerDocs/SwaggerFileclass, the default isTrueAlso, sometimes validation has to be disabled for a route,
to do this you have to passvalidate=Falseduring the initialization of the route.ex.web.post("/route",handler, validate=False), the default isTrueRequirementspython >= 3.8aiohttp >= 3.8.0pyyaml >= 5.4attrs >= 19.3.0python-fastjsonschema >= 2.15.0rfc3339-validator >= 0.1.4Limitationsonly application/json and application/x-www-form-urlencoded supported
for now, but you can create ownhandlerheader/query parameters only supported simple/form array
serialization, e.g. 1,2,3,4see TODO belowInstallationpip installaiohttp-swagger3Examplefromaiohttpimportwebfromaiohttp_swagger3importSwaggerDocs,SwaggerInfo,SwaggerUiSettingsasyncdefget_one_pet(request:web.Request,pet_id:int)->web.Response:"""
    Optional route description
    ---
    summary: Info for a specific pet
    tags:
      - pets
    parameters:
      - name: pet_id
        in: path
        required: true
        description: The id of the pet to retrieve
        schema:
          type: integer
          format: int32
    responses:
      '200':
        description: Expected response to a valid request
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/Pet"
    """ifpet_idnotinrequest.app['storage']:raiseweb.HTTPNotFound()returnweb.json_response(request.app['storage'][pet_id])defmain():app=web.Application()swagger=SwaggerDocs(app,swagger_ui_settings=SwaggerUiSettings(path="/docs/"),info=SwaggerInfo(title="Swagger Petstore",version="1.0.0",),components="components.yaml")swagger.add_routes([web.get("/pets/{pet_id}",get_one_pet),])app['storage']={}web.run_app(app)MoreexamplesHow it helpsFeaturesapplication/jsonapplication/x-www-form-urlencoded (except array and object)itemspropertiespatternrequiredenumminimum, maximumexclusiveMinimum, exclusiveMaximumminLength, maxLengthminItems, maxItemsuniqueItemsminProperties, maxPropertiesdefault (only primitives)additionalPropertiesnullablereadOnlyallOf, oneOf, anyOfstring formats: date, date-time, byte, email, uuid, hostname, ipv4, ipv6custom string format validatorsTODO (raise an issue if needed)multipleOfnotallowEmptyValueCommon Parameters for All Methods of a Path (spec file only)more serialization methods, see:https://swagger.io/docs/specification/serialization/encodingform data serialization (array, object)default (array, object)
Package: aiohttp-swagger-fix
LOOCKING FOR MAINTAINERS!!!!!![Logo](doc/source/_static/logo.png)[![Build Status](https://travis-ci.org/cr0hn/aiohttp-swagger.svg?branch=master)](https://travis-ci.org/cr0hn/aiohttp-swagger)
[![codecov.io](https://codecov.io/github/cr0hn/aiohttp-swagger/coverage.svg?branch=master)](https://codecov.io/github/cr0hn/aiohttp-swagger)aiohttp-swagger: Swagger API Documentation builder for aiohttp serverDocumentation |http://aiohttp-swagger.readthedocs.io/en/latest/————- | ————————————————-
Code |https://github.com/cr0hn/aiohttp-swaggerIssues |https://github.com/cr0hn/aiohttp-swagger/issues/Python version | Python 3.4 and aboveWhat’s aiohttp-swaggeraiohttp-swagger is a plugin for aiohttp.web server that allow to document APIs using Swagger show the Swagger-ui console.What’s new?### Version 1.0.0First version releasedYou can read entire list in [CHANGELOG](https://github.com/cr0hn/aiohttp-swagger/blob/master/CHANGELOG) file.
Package: aiohttp_swaggerify
aiohttp_swaggerifyLibrary to automatically generate swagger2.0 definition for aiohttp endpointsFree software: MIT licenseDocumentation:https://aiohttp-swaggerify.readthedocs.io.FeaturesTODOCreditsThis package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.History0.1.0 (2016-10-12)First release on PyPI.
Package: aiohttp-tal
aiohttp_talTALChameleontemplate engine renderer foraiohttp.web.
Based onaiohttp_jinja2.InstallationInstall from PyPI:pip install aiohttp-talDevelopingInstall requirement and launch tests:pip install -r requirements-dev.txt
pytest testsUsageFor more details on usage, seehttps://aiohttp-tal.readthedocs.io/en/latest/usage.html.Before template rendering you have to setupTAL environmentfirst:app=web.Application()aiohttp_tal.setup(app,loader=chameleon.PageTemplateLoader('/path/to/templates/folder'))Import:importaiohttp_talimportchameleonAfter that you may to use template engine in yourweb-handlers. The
most convenient way is to decorate aweb-handler.Using the function based web handlers:@aiohttp_tal.template('tmpl.pt')defhandler(request):return{'name':'Andrew','surname':'Svetlov'}Licenseaiohttp_talis offered under the GPLv3 license.This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.CHANGES0.1.0 (2019-03-28)Initial release.
Based on aiohttp-jinja2 copyright by Andrew Svetlo and aio-libs team.
Package: aiohttp_tests
Unittest helper utilities for aiohttp-based applications.Example usage:importasyncioimporttimefromunittestimportmockimportaiohttp_testsasatfromaiohttpimportwebsettings=mock.Mock()@at.override_settings(settings,SETTINGS_VALUE='new_value')classExampleTestCase(at.BaseTestCase):""" Aiohttp tests utilities example"""@asyncio.coroutinedefsample_view(self,request):text=yield fromself.sample_async_method()returnweb.Response(text=text)@asyncio.coroutinedefsample_async_method(self):yield fromasyncio.sleep(0.1)return'OK'definit_app(self,loop):""" You must initialize aiohttp application correctly."""app=web.Application(loop=loop)app.router.add_route('GET','/',self.sample_view)returnappdefinit_patchers(self):super().init_patchers()# Short alias for mock.patch that stores patcher and mock objects# locally. Patchers are stopped automatically on teardown.# Method is called by BaseTestCase.setUpself.mock('time.time',return_value=self.now)defsetUp(self):self.now=time.time()super().setUp()deftestMockUtils(self):""" Shows usage of get_mock and get_patcher methods."""self.assertEqual(time.time(),self.now)self.get_mock('time.time').return_value=self.now-1self.assertEqual(time.time(),self.now-1)self.get_patcher('time.time').stop()self.assertGreater(time.time(),self.now)deftestOverrideSettings(self):""" Django-style override_settings decorator for any settings module."""self.assertEqual(settings.SETTINGS_VALUE,'new_value')withat.override_settings(settings,SETTINGS_VALUE='other_value'):self.assertEqual(settings.SETTINGS_VALUE,'other_value')deftestSyncClient(self):""" Synchronous execution of requests, with new event loop every time.
        Other HTTP methods, HTTP headers, request body or form/data are also
        supported.
        """response=self.client.get('/',headers={'Accept':'application/json'})self.assertEqual(response.status,200)self.assertEqual(response.text,'OK')self.assertEqual(response.headers.get('content-type'),'text/plain; charset=utf-8')# other HTTP methodsresponse=self.client.post('/',body='POST body')self.assertEqual(response.status,405)# urlencoded form/data also supportedresponse=self.client.request('PUT','/',data={'field':'value'})self.assertEqual(response.status,405)@at.async_testdeftestAsyncClient(self):""" test client requests could be done async, if needed."""# you can mock any coroutine to return a 'done' Future with custom# result.done_future=self.empty_result("async response")# mock.patck.object shortcutself.mock_object(self,'sample_async_method',return_value=done_future)response=yield fromself.client.get('/')self.assertEqual(response.text,"async response")
Package: aiohttp-things
Modest utility collection for development withAIOHTTPframework.Documentationhttps://aiohttp-things.readthedocs.ioInstallationInstallingaiohttp-thingswith pip:pip install aiohttp-thingsSimple exampleExample of AIOHTTP applicationimportjsonimportuuidimportaiohttp_thingsasahthfromaiohttpimportwebdefsafe_json_value(value):try:json.dumps(value)returnvalueexcept(TypeError,OverflowError):returnstr(value)classBase(web.View,ahth.JSONMixin,ahth.PrimaryKeyMixin):asyncdefget(self):self.context['Type of primary key']=safe_json_value(type(self.pk))self.context['Value of primary key']=safe_json_value(self.pk)returnawaitself.finalize_response()classIntegerExample(Base):pk_adapter=intclassUUIDExample(Base):pk_adapter=uuid.UUIDUUID='[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}'ROUTES=[web.view('/integer/{pk:[0-9]+}',IntegerExample),web.view(f'/uuid/{{pk:{UUID}}}',UUIDExample),]asyncdefapp_factory():app=web.Application()app.add_routes(ROUTES)returnappif__name__=='__main__':web.run_app(app_factory())Examples HTTP requests and responsehttp://0.0.0.0:8080/integer/1{"Type of primary key":"<class 'int'>","Value of primary key":1}http://0.0.0.0:8080/integer/9999999999999{"Type of primary key":"<class 'int'>","Value of primary key":9999999999999}http://0.0.0.0:8080/integer/a352da04-c1af-4a44-8a94-c37f8f37b2bc404: Not Foundhttp://0.0.0.0:8080/integer/abc404: Not Foundhttp://0.0.0.0:8080/uuid/a352da04-c1af-4a44-8a94-c37f8f37b2bc{"Type of primary key":"<class 'uuid.UUID'>","Value of primary key":"a352da04-c1af-4a44-8a94-c37f8f37b2bc"}http://0.0.0.0:8080/uuid/13d1d0e0-4787-4feb-8684-b3da32609743{"Type of primary key":"<class 'uuid.UUID'>","Value of primary key":"13d1d0e0-4787-4feb-8684-b3da32609743"}http://0.0.0.0:8080/uuid/1404: Not Foundhttp://0.0.0.0:8080/uuid/abc404: Not Found
Package: aiohttp-tokenauth
aiohttp-tokenauthAiohttp simple token auth middleware that can check any token that assign to user or group of users in database or some another place.Installationpipinstallaiohttp_tokenauthDocumentationBasic usageFirst of all, let's create a simple app.# Full text in example/simple_app.pyfromaiohttpimportwebfromaiohttp_tokenauthimporttoken_auth_middlewareasyncdefexample_resource(request):returnweb.json_response(request['user'])asyncdefinit():asyncdefuser_loader(token:str):"""Checks that token is validIt's the callback that will get the token from "Authorization" header.It can check that token is exist in a database or some another place.Args:token (str): A token from "Authorization" http header.Returns:Dict or something else. If the callback returns None thenthe aiohttp.web.HTTPForbidden will be raised."""user=Noneiftoken=='fake-token':user={'uuid':'fake-uuid'}returnuserapp=web.Application(middlewares=[token_auth_middleware(user_loader)])app.router.add_get('/',example_resource)returnappif__name__=='__main__':web.run_app(init())Then, run the aiohttp app.$pythonexample/simple_app.py========Runningonhttp://0.0.0.0:8080========(PressCTRL+Ctoquit)Now try to get access to url with token in "Authorization" header.$curl-H'Authorization: Bearer fake-token'http://0.0.0.0:8080{"uuid":"fake-uuid"}And result without token.$curlhttp://0.0.0.0:8080401:MissingauthorizationheaderIgnoring routes and http methodsYou can ignore specific routes, app the paths to "exclude_routes".app=web.Application(middlewares=[token_auth_middleware(user_loader=user_loader,# You can use regular expressions hereexclude_routes=('/exclude',r'/exclude/\w+/info'),exclude_methods=('POST',),),])Change auth schemeFor changing the scheme (prefix in "Authorization" header) useauth_schemeargument.app=web.Application(middlewares=[token_auth_middleware(user_loader=user_loader,auth_scheme='Token',),])Now such request is valid:$curl-H'Authorization: Token fake-token'http://0.0.0.0:8080{"uuid":"fake-uuid"}
Package: aiohttp-toolbox
Tools for aiohttp I want to reuse.InstallationRequirespython 3.7.pipinstallaiohttp-toolboxTo test:atoolbox --root tests/demo webHistoryv0.6.3 (2019-12-12)addparse_requestmethod toExecViewv0.6.2 (2019-10-23)uprev. pydantic to Version 1v0.6.1 (2019-10-17)fixDummyPgPoolto not allow direct transactions.v0.6.0 (2019-10-08)drop and recreate schema with a different connection before populating the databasefix CSRF failure on file upload on firefox by allowing no Origin for uploadsv0.5.3 (2019-08-21)Switch to direct usage of sentry-sdk (sigh)v0.5.2 (2019-08-20)switch from raven to sentry-sdkv0.5.1 (2019-08-20)upgrade pypi deploy to use API tokensv0.5 (2019-08-20)reprand timeout forDummyPgPoolimprove error middleware for better fingerprint inlog_warningimprove error middleware for better compatibility with sentryv0.4.4 (2019-07-31)addshellcommandtweak dummy server request logging, add response codeupgradearqtov0.16upgradepydantictov0.31.1v0.4.1 (2019-04-29)404 for.well-known/*urls inspa_static_handlerallow google recaptcha test keysv0.4.0 (2019-04-09)addspa_static_handlerv0.3.3 (2019-03-21)tweakpatch_pathsv0.3.2 (2019-03-15)addpatch_pathsto settingsexc_infoadding middleware warningv0.3.1 (2019-03-13)addautocommand to CLIv0.3.0 (2019-03-08)supportarq >= 0.16andpydantic > 0.20, #12v0.2.2 (2019-02-13)pg_middlewarenow respectspg_middleware_checkfunction, fix #10v0.2.1 (2019-02-07)tweak imports, repr method forJsonErrorsv0.2.0 (2019-02-04)improvedclass_viewsuseargparsein clifix logging setupallow patches to not be coroutinesaddskip_if_offlinepytest decoratorv0.1.0 (2019-01-24)improve logging output #9cleanup cliadd commands:flush_redisandcheck_web, implementwait_for_services#7v0.0.11 (2018-12-27)uprev aiohttp-sessionsupport latest aiohttpv0.0.9 (2018-12-16)allow settings and redis and postgres to be optional when creating appsv0.0.8 (2018-12-12)optionalconnonViewimproveraw_json_responseaddJsonErrors.HTTPAcceptedrenameparse_request->parse_request_jsonaddparse_request_queryv0.0.7 (2018-11-28)improved CSRFv0.0.6 (2018-11-22)allow for requests without aconnv0.0.5 (2018-11-22)improve bread, usehandlenotcheck_permissionsv0.0.4 (2018-11-21)addcheck_grecaptchaimprove middlewarev0.0.3 (2018-11-20)tweak cli and how worker is runv0.0.2 (2018-11-19)change module namev0.0.1 (2018-11-19)first release
Package: aiohttp-tools
It contains:url_for- flask-like url reverserjsonify- flask-like json-dumper with support ofdatetime, andObjectIdredirect- django-like redirectget_argument- tornado-like util to get GET / POST argumentsstatic_url- tornado-like url-wrapper to add version hast to static assetflash- simple flash messages, usage described bellowget_client_ip- client IP addressfix_host- middleware for redirect requests by IP to right domaintemplate_handler- handler that just render templateurl_for_processor- context processor for usingurl_forwithout passing requestsession_processor- context_processor foraiohttp_sessionLook at theexamplefolder for working example.Installationpip install aiohttp_toolsRepository:https://github.com/imbolc/aiohttp_toolsFlash messagesfromaiohttp_tools.flashimportflash# you should include session middleware before flash middlewareaiohttp_session.setup(app,...)app.middlewares.append(aiohttp_tools.flash.middleware)context_processors.append(aiohttp_tools.flash.context_processor)asyncdefhandler(request):flash.message(request,'Message','level')# shortcutsflash.info(request,'Some message')flash.success(...)flash.warning(...)flash.error(...){% for message, level in get_flashed_messages() %}<divclass="flash {{ level }}">{{ message }}</div>{% endfor %}
Package: aiohttp-tus
tus.ioserver implementation foraiohttp.webapplications.For uploading large files, please consider usingaiotus(Python 3.7+) library instead.Works on Python 3.6+Works with aiohttp 3.5+BSD licensedLatest documentationon Read The DocsSource, issues, and pull requestson GitHubQuickstartCode belows shows how to enable tus-compatible uploads on/uploadsURL foraiohttp.webapplication. After upload, files will be available at../uploadsdirectory.frompathlibimportPathfromaiohttpimportwebfromaiohttp_tusimportsetup_tusapp=setup_tus(web.Application(),upload_url="/uploads",upload_path=Path(__file__).parent.parent/"uploads",)Chunk SizePlease, make sure to configureclient_max_sizeforaiohttp.webApplication and
supply properchunkSizefor Uppy.io or other tus.io client.DocumentationCORS HeadersTo setup CORS headers you need to usecors_middlewarefromaiohttp-middlewarespackage.aiohttp-corslibrary not supported cause ofaio-libs/aiohttp-cors#241issue.DocumentationReverse proxy and HTTPSWhenaiohttpapplication deployed under the reverse proxy (such as nginx) with HTTPS
support, it is needed to usehttps_middlewarefromaiohttp-middlewarespackage to ensure thatweb.Requestinstance has proper
schema.DocumentationExamplesexamples/directory
contains several examples, which illustrate how to useaiohttp-tuswith some tus.io
clients, such astus.pyandUppy.io.
Package: aiohttp-utils
aiohttp-utilsprovides handy utilities for buildingaiohttp.webapplications.Method-based handlers (“resources”)Routing utilitiesContent negotiation with JSON rendering by defaultEverything is optional. You can use as much (or as little) of this toolkit as you need.fromaiohttpimportwebfromaiohttp_utilsimportResponse,routing,negotiationapp=web.Application(router=routing.ResourceRouter())# Method-based handlersclassHelloResource:asyncdefget(self,request):name=request.GET.get('name','World')returnResponse({'message':'Hello '+name})app.router.add_resource_object('/',HelloResource())# Content negotiationnegotiation.setup(app,renderers={'application/json':negotiation.render_json})Install$ pip install aiohttp-utilsDocumentationFull documentation is available athttps://aiohttp-utils.readthedocs.io/.Project LinksDocs:https://aiohttp-utils.readthedocs.io/Changelog:https://aiohttp-utils.readthedocs.io/en/latest/changelog.htmlPyPI:https://pypi.python.org/pypi/aiohttp-utilsIssues:https://github.com/sloria/aiohttp-utils/issuesLicenseMIT licensed. See the bundledLICENSEfile for more details.
Package: aiohttp-valera-validator
aiohttp-valera-validatorRequest validation foraiohttp(viavalera)Installation$pip3installaiohttp-valera-validatorUsagefromaiohttp.webimportApplication,json_response,route,run_appfromdistrict42importschemafromaiohttp_valera_validatorimportvalidateParamsSchema=schema.dict({"q":schema.str.len(1,...)})@validate(params=ParamsSchema)asyncdefhandler(request):q=request.query["q"]returnjson_response({"q":q})app=Application()app.add_routes([route("GET","/users",handler)])run_app(app)// http /users?q=Bob{"q":"Bob"}// http /users{"errors":["Value <class 'str'> at _['q'] must have at least 1 element, but it has 0 elements"]}DocsQuery params validationfromdistrict42importschemafromaiohttp_valera_validatorimportvalidate# schema.dict is strict by default (all keys must be present)ParamsSchema=schema.dict({"q":schema.str.len(1,...)})@routes.get("/users")@validate(params=ParamsSchema)asyncdefhandler(request):q=request.query["q"]returnjson_response({"q":q})Headers validationfromdistrict42importschemafromaiohttp_valera_validatorimportvalidatefrommultidictimportistr# "..." means that there can be any other keys# headers are case-insensitive, so we use istr forHeadersSchema=schema.dict({istr("User-Agent"):schema.str.len(1,...),...:...})@routes.get("/users")@validate(headers=HeadersSchema)asyncdefhandler(request):user_agent=request.headers["User-Agent"]returnjson_response({"user_agent":user_agent})JSON body validationfromdistrict42importschemafromaiohttp_valera_validatorimportvalidateBodySchema=schema.dict({"id":schema.int.min(1),"name":schema.str.len(1,...),})@routes.post("/users")@validate(json=BodySchema)asyncdefhandler(request):payload=awaitrequest.json()returnjson_response({"id":payload["id"],"name":payload["name"]})URL segments validationSegments — is a variable part of URL path (aiohttpusesmatch_infofor it)fromdistrict42importschemafromaiohttp_valera_validatorimportvalidateSegmentsSchema=schema.dict({"user_id":schema.str.regex(r"[1-9][0-9]*"),})@routes.get("/users/{user_id}")@validate(segments=SegmentsSchema)asyncdefhandler(request):user_id=int(request.match_info["user_id"])returnjson_response({"user_id":user_id})Custom responsefromhttpimportHTTPStatusfromaiohttp.webimportRequest,Responsefromaiohttp_valera_validatorimportvalidateasvalidate_origclassvalidate(validate_orig):defcreate_error_response(self,request:Request,errors:List[str])->Response:status=HTTPStatus.UNPROCESSABLE_ENTITYbody="<ul>"+"".join(f"<li>{error}</li>"forerrorinerrors)+"</ul>"returnResponse(status=status,text=body,headers={"Content-Type":"text/html"})—Fore more information readvalera docs
Package: aiohttp_validate
aiohttp_validateSimple library that helps you validate your API endpoints requests/responses withjsonschema. Documentation is also available here athttps://aiohttp-validate.readthedocs.io.InstallationInstall from PyPI:pip install aiohttp_validateUsageComplete example of validation fortext tokenization microservice:from aiohttp_validate import validate

@validate(
    request_schema={
        "type": "object",
        "properties": {
            "text": {"type": "string"},
        },
        "required": ["text"],
        "additionalProperties": False
    },
    response_schema={
        "type": "array",
        "items": {
            "type": "array",
            "items": {
                "type": "array",
                "items": {"type": "string"}
            }
        }
    }
)
async def tokenize_text_handler(request, *args):
    return tokenize_text(request["text"])FeaturesThe decorator to (optionally) validate the request to your aiohttp endpoint and it’s response.Easily integrates withaiohttp_swaggerifyto automatically document your endpoints with swagger.Validation errors are standardized and can be easily parsed by the clients of your service and also human-readable.DevelopingInstall requirement and launch tests:pip install -r requirements-dev.txt
py.testCreditsThat package is influenced byTornado-JSONwritten by Hamza Faran
Code to parse errors is written byRuslan KaralkinLicenseFree software: MIT licenseHistory1.0.0 (2016-12-12)Better documentation.Updated requirements.Out of alpha!0.1.0 (2016-10-12)First release on PyPI.