Skip to main content

Request validation for aiohttp

Project description

aiohttp-valera-validator

⚠️ This package has been renamed to aiohttp-d42-validator. The aiohttp-valera-validator package on PyPI is no longer maintained. For updates and improvements, please use aiohttp-d42-validator going forward.

PyPI PyPI - Downloads Python Version

Request validation for aiohttp (via valera).

Installation

$ pip3 install aiohttp-valera-validator

Usage

from aiohttp.web import Application, json_response, route, run_app
from district42 import schema
from aiohttp_valera_validator import validate

ParamsSchema = schema.dict({
    "q": schema.str.len(1, ...)
})

@validate(params=ParamsSchema)
async def handler(request):
    q = request.query["q"]
    return json_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"
    ]
}

Docs

Query params validation

from district42 import schema
from aiohttp_valera_validator import validate

# 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)
async def handler(request):
    q = request.query["q"]
    return json_response({"q": q})

Headers validation

from district42 import schema
from aiohttp_valera_validator import validate
from multidict import istr

# "..." means that there can be any other keys
# headers are case-insensitive, so we use istr for
HeadersSchema = schema.dict({
    istr("User-Agent"): schema.str.len(1, ...),
    ...: ...
})

@routes.get("/users")
@validate(headers=HeadersSchema)
async def handler(request):
    user_agent = request.headers["User-Agent"]
    return json_response({"user_agent": user_agent})

JSON body validation

from district42 import schema
from aiohttp_valera_validator import validate

BodySchema = schema.dict({
    "id": schema.int.min(1),
    "name": schema.str.len(1, ...),
})

@routes.post("/users")
@validate(json=BodySchema)
async def handler(request):
    payload = await request.json()
    return json_response({
        "id": payload["id"],
        "name": payload["name"]
    })

URL segments validation

Segments — is a variable part of URL path (aiohttp uses match_info for it)

from district42 import schema
from aiohttp_valera_validator import validate

SegmentsSchema = schema.dict({
    "user_id": schema.str.regex(r"[1-9][0-9]*"),
})

@routes.get("/users/{user_id}")
@validate(segments=SegmentsSchema)
async def handler(request):
    user_id = int(request.match_info["user_id"])
    return json_response({"user_id": user_id})

Custom response

from http import HTTPStatus
from aiohttp.web import Request, Response
from aiohttp_valera_validator import validate as validate_orig

class validate(validate_orig):
    def create_error_response(self, request: Request, errors: List[str]) -> Response:
        status = HTTPStatus.UNPROCESSABLE_ENTITY
        body = "<ul>" + "".join(f"<li>{error}</li>" for error in errors) + "</ul>"
        return Response(status=status, text=body, headers={"Content-Type": "text/html"})

Fore more information read valera docs.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

aiohttp_valera_validator-0.1.1.tar.gz (8.7 kB view details)

Uploaded Source

Built Distribution

aiohttp_valera_validator-0.1.1-py3-none-any.whl (8.4 kB view details)

Uploaded Python 3

File details

Details for the file aiohttp_valera_validator-0.1.1.tar.gz.

File metadata

File hashes

Hashes for aiohttp_valera_validator-0.1.1.tar.gz
Algorithm Hash digest
SHA256 fe4af5e0c5ec247a3205c93eee9f42e94cf1426c390980df101b8d0c7aa1da15
MD5 a4b8aa4ec2816690efab98364a609eb6
BLAKE2b-256 aee36f2bcba42393a1bf3b7b250a34cb20c98d267f77ae9bfbd3df6d36004ef8

See more details on using hashes here.

File details

Details for the file aiohttp_valera_validator-0.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for aiohttp_valera_validator-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 9a390baf7240d2e63befa92da8d7982e5a850a6089b7550c7ff02bab90c3cdaa
MD5 58d3413ebfed5d3088b19b05d268991f
BLAKE2b-256 48052c4eac9095885f9ef60c7b5c9bb8bbd6fc866a2f408fb0d40fff5aa0de06

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page