Debian Codegraph @

src/globus_sdk/transport/encoders.py

raw
1 from __future__ import annotations
2
3 import enum
4 import typing as t
5 import uuid
6
7 import requests
8
9 from globus_sdk._missing import MISSING, filter_missing
10
11
12 class RequestEncoder:
13 """
14 A RequestEncoder takes input parameters and outputs a requests.Requests object.
15
16 The default encoder requires that the data is text and is a no-op. It can also be
17 referred to as the ``"text"`` encoder.
18 """
19
20 def encode(
21 self,
22 method: str,
23 url: str,
24 params: dict[str, t.Any] | None,
25 data: t.Any,
26 headers: dict[str, str],
27 ) -> requests.Request:
28 if not isinstance(data, (str, bytes)):
29 raise TypeError(
30 "Cannot encode non-text in a text request. "
31 "Either manually encode the data or use `encoding=form|json` to "
32 "correctly format this data."
33 )
34 return requests.Request(
35 method,
36 url,
37 data=self._prepare_data(data),
38 params=self._prepare_params(params),
39 headers=self._prepare_headers(headers),
40 )
41
42 def _format_primitive(self, value: t.Any) -> t.Any:
43 """
44 Transformations for primitive values (e.g. stringifiable items) for query
45 params, headers, and body elements.
46
47 Transforms data as follows:
48
49 x: UUID -> str(x)
50 x: Enum -> x.value
51 x: _ -> x
52 """
53 if isinstance(value, uuid.UUID):
54 return str(value)
55 if isinstance(value, enum.Enum):
56 return value.value
57 return value
58
59 def _prepare_params(
60 self, params: dict[str, t.Any] | None
61 ) -> dict[str, t.Any] | None:
62 """
63 Prepare the query params for a request.
64
65 Filters out MISSING and formats primitives.
66 """
67 if params is None:
68 return None
69 return filter_missing({k: self._format_primitive(v) for k, v in params.items()})
70
71 def _prepare_headers(
72 self, headers: dict[str, t.Any] | None
73 ) -> dict[str, t.Any] | None:
74 """
75 Prepare the headers for a request.
76
77 Filters out MISSING and formats primitives.
78 """
79 if headers is None:
80 return None
81 return filter_missing(
82 {k: self._format_primitive(v) for k, v in headers.items()}
83 )
84
85 def _prepare_data(self, data: t.Any) -> t.Any:
86 """
87 Prepare the data (body) for a request.
88
89 If the body is a dict, list, or tuple, it will be recursively processed to
90 filter out MISSING and format primitives.
91
92 Otherwise, it is returned as-is.
93 """
94 if isinstance(data, dict):
95 return filter_missing({k: self._prepare_data(v) for k, v in data.items()})
96 elif isinstance(data, (list, tuple)):
97 return [self._prepare_data(x) for x in data if x is not MISSING]
98 else:
99 return self._format_primitive(data)
100
101
102 class JSONRequestEncoder(RequestEncoder):
103 """
104 This encoder prepares the data as JSON. It also ensures that content-type is set, so
105 that APIs requiring a content-type of "application/json" are able to read the data.
106 """
107
108 def encode(
109 self,
110 method: str,
111 url: str,
112 params: dict[str, t.Any] | None,
113 data: t.Any,
114 headers: dict[str, str],
115 ) -> requests.Request:
116 if data is not None:
117 headers = {"Content-Type": "application/json", **headers}
118 return requests.Request(
119 method,
120 url,
121 json=self._prepare_data(data),
122 params=self._prepare_params(params),
123 headers=self._prepare_headers(headers),
124 )
125
126
127 class FormRequestEncoder(RequestEncoder):
128 """
129 This encoder formats data as a form-encoded body. It requires that the input data is
130 a dict -- any other datatype will result in errors.
131 """
132
133 def encode(
134 self,
135 method: str,
136 url: str,
137 params: dict[str, t.Any] | None,
138 data: t.Any,
139 headers: dict[str, str],
140 ) -> requests.Request:
141 if not isinstance(data, dict):
142 raise TypeError("FormRequestEncoder cannot encode non-dict data")
143 return requests.Request(
144 method,
145 url,
146 data=self._prepare_data(data),
147 params=self._prepare_params(params),
148 headers=self._prepare_headers(headers),
149 )