File: middlewares.py

package info (click to toggle)
python-aiohttp-apispec 3.0.0~b2%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 204 kB
  • sloc: python: 439; makefile: 4
file content (48 lines) | stat: -rw-r--r-- 1,479 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from aiohttp import web

from .utils import issubclass_py37fix


@web.middleware
async def validation_middleware(request: web.Request, handler) -> web.Response:
    """
    Validation middleware for aiohttp web app

    Usage:

    .. code-block:: python

        app.middlewares.append(validation_middleware)


    """
    orig_handler = request.match_info.handler
    if not hasattr(orig_handler, "__schemas__"):
        if not issubclass_py37fix(orig_handler, web.View):
            return await handler(request)
        sub_handler = getattr(orig_handler, request.method.lower(), None)
        if sub_handler is None:
            return await handler(request)
        if not hasattr(sub_handler, "__schemas__"):
            return await handler(request)
        schemas = sub_handler.__schemas__
    else:
        schemas = orig_handler.__schemas__
    result = {}
    for schema in schemas:
        data = await request.app["_apispec_parser"].parse(
            schema["schema"],
            request,
            location=schema["location"],
            unknown=None,  # Pass None to use the schema’s setting instead.
        )
        if schema["put_into"]:
            request[schema["put_into"]] = data
        elif data:
            try:
                result.update(data)
            except (ValueError, TypeError):
                result = data
                break
    request[request.app["_apispec_request_data_name"]] = result
    return await handler(request)