File: aws_headers.py

package info (click to toggle)
python-moto 5.1.18-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 116,520 kB
  • sloc: python: 636,725; javascript: 181; makefile: 39; sh: 3
file content (66 lines) | stat: -rw-r--r-- 1,808 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
from functools import wraps
from typing import TYPE_CHECKING, Any, Callable, Optional, TypeVar

if TYPE_CHECKING:
    from typing_extensions import Protocol
else:
    Protocol = object

import binascii

TypeDec = TypeVar("TypeDec", bound=Callable[..., Any])


class GenericFunction(Protocol):
    def __call__(self, *args: Any, **kwargs: Any) -> Any: ...


def gen_amz_crc32(response: Any, headerdict: Optional[dict[str, Any]] = None) -> int:
    if not isinstance(response, bytes):
        response = response.encode("utf-8")

    crc = binascii.crc32(response)

    if headerdict is not None and isinstance(headerdict, dict):
        headerdict.update({"x-amz-crc32": str(crc)})

    return crc


def gen_amzn_requestid_long(headerdict: Optional[dict[str, Any]] = None) -> str:
    from moto.moto_api._internal import mock_random as random

    req_id = random.get_random_string(length=52)

    if headerdict is not None and isinstance(headerdict, dict):
        headerdict.update({"x-amzn-requestid": req_id})

    return req_id


def amz_crc32(f: TypeDec) -> GenericFunction:
    @wraps(f)
    def _wrapper(*args: Any, **kwargs: Any) -> Any:  # type: ignore[misc]
        response = f(*args, **kwargs)

        headers = {}
        status = 200

        if isinstance(response, str):
            body = response
        else:
            if len(response) == 2:
                body, new_headers = response
                status = new_headers.get("status", status)
            else:
                status, new_headers, body = response
            headers.update(new_headers)
            # Cast status to string
            if "status" in headers:
                headers["status"] = str(headers["status"])

        gen_amz_crc32(body, headers)

        return status, headers, body

    return _wrapper