hip 0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
hip/_content.py ADDED
@@ -0,0 +1,557 @@
1
+ import copy
2
+ import json
3
+ import os
4
+ import typing
5
+
6
+ from ._headers import Headers, parse_opts_header
7
+ from ._streams import ByteStream, FileStream, MultiPartStream, Stream
8
+ from ._urlencode import urldecode, urlencode
9
+
10
+ __all__ = [
11
+ "HTML",
12
+ "JSON",
13
+ "Binary",
14
+ "Content",
15
+ "Empty",
16
+ "File",
17
+ "Files",
18
+ # Request Content Types
19
+ "Form",
20
+ "MultiPart",
21
+ # Response Content Types
22
+ "Text",
23
+ ]
24
+
25
+ # https://github.com/nginx/nginx/blob/master/conf/mime.types
26
+ _content_types = {
27
+ ".json": "application/json",
28
+ ".js": "application/javascript",
29
+ ".txt": "text/plain",
30
+ ".html": "text/html",
31
+ ".css": "text/css",
32
+ ".png": "image/png",
33
+ ".jpeg": "image/jpeg",
34
+ ".jpg": "image/jpeg",
35
+ ".gif": "image/gif",
36
+ }
37
+
38
+
39
+ class Content:
40
+ def open(self) -> Stream:
41
+ raise NotImplementedError()
42
+
43
+ def headers(self) -> Headers:
44
+ raise NotImplementedError()
45
+
46
+ @classmethod
47
+ def parse(self, stream: Stream) -> "Content":
48
+ raise NotImplementedError()
49
+
50
+ def __bytes__(self):
51
+ raise TypeError(
52
+ f"Content {self.__class__.__name__} does not support a bytes interface."
53
+ )
54
+
55
+
56
+ class Form(typing.Mapping[str, str], Content):
57
+ """
58
+ HTML form data, as an immutable multi-dict.
59
+ Form parameters, as a multi-dict.
60
+ """
61
+
62
+ def __init__(
63
+ self,
64
+ form: (
65
+ typing.Mapping[str, str | typing.Sequence[str]]
66
+ | typing.Sequence[tuple[str, str]]
67
+ | str
68
+ | None
69
+ ) = None,
70
+ ) -> None:
71
+ d: dict[str, list[str]] = {}
72
+
73
+ if form is None:
74
+ d = {}
75
+ elif isinstance(form, str):
76
+ d = urldecode(form)
77
+ elif isinstance(form, typing.Mapping):
78
+ # Convert dict inputs like:
79
+ # {"a": "123", "b": ["456", "789"]}
80
+ # To dict inputs where values are always lists, like:
81
+ # {"a": ["123"], "b": ["456", "789"]}
82
+ d = {k: [v] if isinstance(v, str) else list(v) for k, v in form.items()}
83
+ else:
84
+ # Convert list inputs like:
85
+ # [("a", "123"), ("a", "456"), ("b", "789")]
86
+ # To a dict representation, like:
87
+ # {"a": ["123", "456"], "b": ["789"]}
88
+ for k, v in form:
89
+ d.setdefault(k, []).append(v)
90
+
91
+ self._dict = d
92
+ self._content = str(self).encode("ascii")
93
+
94
+ # Content API
95
+
96
+ def open(self) -> Stream:
97
+ return ByteStream(self._content)
98
+
99
+ def headers(self) -> Headers:
100
+ content_length = len(self._content)
101
+ return Headers(
102
+ {
103
+ "Content-Type": "application/x-www-form-urlencoded",
104
+ "Content-Length": f"{content_length}",
105
+ }
106
+ )
107
+
108
+ def __bytes__(self) -> bytes:
109
+ return self._content
110
+
111
+ # Dict operations
112
+
113
+ def keys(self) -> typing.KeysView[str]:
114
+ return self._dict.keys()
115
+
116
+ def values(self) -> typing.ValuesView[str]:
117
+ return {k: v[0] for k, v in self._dict.items()}.values()
118
+
119
+ def items(self) -> typing.ItemsView[str, str]:
120
+ return {k: v[0] for k, v in self._dict.items()}.items()
121
+
122
+ def get(self, key: str, default: typing.Any = None) -> typing.Any:
123
+ if key in self._dict:
124
+ return self._dict[key][0]
125
+ return default
126
+
127
+ # Multi-dict operations
128
+
129
+ def multi_items(self) -> list[tuple[str, str]]:
130
+ multi_items: list[tuple[str, str]] = []
131
+ for k, v in self._dict.items():
132
+ multi_items.extend([(k, i) for i in v])
133
+ return multi_items
134
+
135
+ def multi_dict(self) -> dict[str, list[str]]:
136
+ return {k: list(v) for k, v in self._dict.items()}
137
+
138
+ def get_list(self, key: str) -> list[str]:
139
+ return list(self._dict.get(key, []))
140
+
141
+ # Update operations
142
+
143
+ def copy_set(self, key: str, value: str) -> "Form":
144
+ d = self.multi_dict()
145
+ d[key] = [value]
146
+ return Form(d)
147
+
148
+ def copy_append(self, key: str, value: str) -> "Form":
149
+ d = self.multi_dict()
150
+ d[key] = d.get(key, []) + [value]
151
+ return Form(d)
152
+
153
+ def copy_remove(self, key: str) -> "Form":
154
+ d = self.multi_dict()
155
+ d.pop(key, None)
156
+ return Form(d)
157
+
158
+ # Accessors & built-ins
159
+
160
+ def __getitem__(self, key: str) -> str:
161
+ return self._dict[key][0]
162
+
163
+ def __contains__(self, key: typing.Any) -> bool:
164
+ return key in self._dict
165
+
166
+ def __iter__(self) -> typing.Iterator[str]:
167
+ return iter(self.keys())
168
+
169
+ def __len__(self) -> int:
170
+ return len(self._dict)
171
+
172
+ def __bool__(self) -> bool:
173
+ return bool(self._dict)
174
+
175
+ def __hash__(self) -> int:
176
+ return hash(str(self))
177
+
178
+ def __eq__(self, other: object) -> bool:
179
+ return isinstance(other, Form) and sorted(self.multi_items()) == sorted(
180
+ other.multi_items()
181
+ )
182
+
183
+ def __str__(self) -> str:
184
+ return urlencode(self.multi_dict())
185
+
186
+ def __repr__(self) -> str:
187
+ return f"<Form {self.multi_items()!r}>"
188
+
189
+
190
+ class File(Content):
191
+ """
192
+ Wrapper class used for files in uploads and multipart requests.
193
+ """
194
+
195
+ def __init__(self, path: str):
196
+ self._path = path
197
+
198
+ def name(self) -> str:
199
+ return os.path.basename(self._path)
200
+
201
+ def open(self) -> Stream:
202
+ return FileStream(self._path).open()
203
+
204
+ def headers(self) -> Headers:
205
+ content_length = os.path.getsize(self._path)
206
+
207
+ _, ext = os.path.splitext(self._path)
208
+ content_type = _content_types.get(ext, "application/octet-stream")
209
+ if content_type.startswith("text/"):
210
+ content_type += "; charset='utf-8'"
211
+
212
+ return Headers(
213
+ {
214
+ "Content-Type": f"{content_type}",
215
+ "Content-Length": f"{content_length}",
216
+ }
217
+ )
218
+
219
+ def __lt__(self, other: typing.Any) -> bool:
220
+ return isinstance(other, File) and other._path < self._path
221
+
222
+ def __eq__(self, other: object) -> bool:
223
+ return isinstance(other, File) and other._path == self._path
224
+
225
+ def __repr__(self) -> str:
226
+ return f"<File {self._path!r}>"
227
+
228
+
229
+ class Files(typing.Mapping[str, File], Content):
230
+ """
231
+ File parameters, as a multi-dict.
232
+ """
233
+
234
+ def __init__(
235
+ self,
236
+ files: (
237
+ typing.Mapping[str, File | typing.Sequence[File]]
238
+ | typing.Sequence[tuple[str, File]]
239
+ | None
240
+ ) = None,
241
+ boundary: str = "",
242
+ ) -> None:
243
+ d: dict[str, list[File]] = {}
244
+
245
+ if files is None:
246
+ d = {}
247
+ elif isinstance(files, typing.Mapping):
248
+ d = {k: [v] if isinstance(v, File) else list(v) for k, v in files.items()}
249
+ else:
250
+ d = {}
251
+ for k, v in files:
252
+ d.setdefault(k, []).append(v)
253
+
254
+ self._dict = d
255
+ self._boundary = boundary or os.urandom(16).hex()
256
+
257
+ # Standard dict interface
258
+ def keys(self) -> typing.KeysView[str]:
259
+ return self._dict.keys()
260
+
261
+ def values(self) -> typing.ValuesView[File]:
262
+ return {k: v[0] for k, v in self._dict.items()}.values()
263
+
264
+ def items(self) -> typing.ItemsView[str, File]:
265
+ return {k: v[0] for k, v in self._dict.items()}.items()
266
+
267
+ def get(self, key: str, default: typing.Any = None) -> typing.Any:
268
+ if key in self._dict:
269
+ return self._dict[key][0]
270
+ return None
271
+
272
+ # Multi dict interface
273
+ def multi_items(self) -> list[tuple[str, File]]:
274
+ multi_items: list[tuple[str, File]] = []
275
+ for k, v in self._dict.items():
276
+ multi_items.extend([(k, i) for i in v])
277
+ return multi_items
278
+
279
+ def multi_dict(self) -> dict[str, list[File]]:
280
+ return {k: list(v) for k, v in self._dict.items()}
281
+
282
+ def get_list(self, key: str) -> list[File]:
283
+ return list(self._dict.get(key, []))
284
+
285
+ # Content interface
286
+ def open(self) -> Stream:
287
+ return MultiPart(files=self, boundary=self._boundary).open()
288
+
289
+ def headers(self) -> Headers:
290
+ content_type = f"multipart/form-data; boundary={self._boundary}"
291
+ return Headers(
292
+ {
293
+ "Content-Type": f"{content_type}",
294
+ "Transfer-Encoding": "chunked",
295
+ }
296
+ )
297
+
298
+ # Builtins
299
+ def __getitem__(self, key: str) -> File:
300
+ return self._dict[key][0]
301
+
302
+ def __contains__(self, key: typing.Any) -> bool:
303
+ return key in self._dict
304
+
305
+ def __iter__(self) -> typing.Iterator[str]:
306
+ return iter(self.keys())
307
+
308
+ def __len__(self) -> int:
309
+ return len(self._dict)
310
+
311
+ def __bool__(self) -> bool:
312
+ return bool(self._dict)
313
+
314
+ def __eq__(self, other: object) -> bool:
315
+ return isinstance(other, Files) and sorted(self.multi_items()) == sorted(
316
+ other.multi_items()
317
+ )
318
+
319
+ def __repr__(self) -> str:
320
+ return f"<Files {self.multi_items()!r}>"
321
+
322
+
323
+ class JSON(Content):
324
+ def __init__(self, data: typing.Any, source: bytes | None = None) -> None:
325
+ self._data = data
326
+ self._content = (
327
+ json.dumps(
328
+ self._data, ensure_ascii=False, separators=(",", ":"), allow_nan=False
329
+ ).encode("utf-8")
330
+ if source is None
331
+ else source
332
+ )
333
+
334
+ def open(self) -> Stream:
335
+ return ByteStream(self._content)
336
+
337
+ def headers(self) -> Headers:
338
+ content_type = "application/json"
339
+ content_length = len(self._content)
340
+ return Headers(
341
+ {
342
+ "Content-Type": f"{content_type}",
343
+ "Content-Length": f"{content_length}",
344
+ }
345
+ )
346
+
347
+ @classmethod
348
+ def parse(self, stream: Stream) -> "Content":
349
+ source = stream.read()
350
+ data = json.loads(source)
351
+ return JSON(data, source)
352
+
353
+ # Return the underlying data. Copied to ensure immutability.
354
+ @property
355
+ def value(self) -> typing.Any:
356
+ return copy.deepcopy(self._data)
357
+
358
+ # dict and list style accessors, eg. for casting.
359
+ def keys(self) -> typing.KeysView[str]:
360
+ return self._data.keys()
361
+
362
+ def __len__(self) -> int:
363
+ return len(self._data)
364
+
365
+ def __getitem__(self, key: typing.Any) -> typing.Any:
366
+ return copy.deepcopy(self._data[key])
367
+
368
+ # Built-ins.
369
+ def __eq__(self, other: object) -> bool:
370
+ if isinstance(other, JSON):
371
+ return self._data == other._data
372
+ return self._data == other
373
+
374
+ def __str__(self) -> str:
375
+ return self._content.decode("utf-8")
376
+
377
+ def __bytes__(self) -> bytes:
378
+ return self._content
379
+
380
+ def __repr__(self) -> str:
381
+ return f"<JSON {self._data!r}>"
382
+
383
+
384
+ class Text(Content):
385
+ def __init__(self, text: str, source: bytes | None = None) -> None:
386
+ self._text = text
387
+ self._content = self._text.encode("utf-8") if source is None else source
388
+
389
+ def open(self) -> Stream:
390
+ return ByteStream(self._content)
391
+
392
+ def headers(self) -> Headers:
393
+ content_type = "text/plain; charset='utf-8'"
394
+ content_length = len(self._content)
395
+ return Headers(
396
+ {
397
+ "Content-Type": f"{content_type}",
398
+ "Content-Length": f"{content_length}",
399
+ }
400
+ )
401
+
402
+ @classmethod
403
+ def parse(self, stream: Stream) -> Content:
404
+ source = stream.read()
405
+ text = source.decode("utf-8")
406
+ return Text(text, source)
407
+
408
+ def __str__(self) -> str:
409
+ return self._text
410
+
411
+ def __bytes__(self) -> bytes:
412
+ return self._content
413
+
414
+ def __repr__(self) -> str:
415
+ return f"<Text {self._text!r}>"
416
+
417
+
418
+ class HTML(Content):
419
+ def __init__(self, text: str, source: bytes | None = None) -> None:
420
+ self._text = text
421
+ self._content = self._text.encode("utf-8") if source is None else source
422
+
423
+ def open(self) -> Stream:
424
+ return ByteStream(self._content)
425
+
426
+ def headers(self) -> Headers:
427
+ content_type = "text/html; charset='utf-8'"
428
+ content_length = len(self._content)
429
+ return Headers(
430
+ {
431
+ "Content-Type": f"{content_type}",
432
+ "Content-Length": f"{content_length}",
433
+ }
434
+ )
435
+
436
+ @classmethod
437
+ def parse(self, stream: Stream) -> Content:
438
+ source = stream.read()
439
+ text = source.decode("utf-8")
440
+ return HTML(text, source)
441
+
442
+ def __str__(self) -> str:
443
+ return self._text
444
+
445
+ def __bytes__(self) -> bytes:
446
+ return self._content
447
+
448
+ def __repr__(self) -> str:
449
+ return f"<HTML {self._text!r}>"
450
+
451
+
452
+ class Binary(Content):
453
+ def __init__(self, content: bytes | None) -> None:
454
+ self._content = b"" if (content is None) else content
455
+
456
+ def open(self) -> Stream:
457
+ return ByteStream(self._content)
458
+
459
+ def headers(self) -> Headers:
460
+ content_length = len(self._content)
461
+ return Headers({"Content-Length": f"{content_length}"})
462
+
463
+ @classmethod
464
+ def parse(self, stream: Stream) -> Content:
465
+ source = stream.read()
466
+ return Binary(source)
467
+
468
+ def __bytes__(self) -> bytes:
469
+ return self._content
470
+
471
+ def __repr__(self) -> str:
472
+ return f"<Binary {self._content!r}>"
473
+
474
+
475
+ class Empty(Content):
476
+ def __init__(self) -> None:
477
+ pass
478
+
479
+ def open(self) -> Stream:
480
+ return ByteStream(b"")
481
+
482
+ def headers(self) -> Headers:
483
+ return Headers()
484
+
485
+ def __bytes__(self) -> bytes:
486
+ return b""
487
+
488
+ def __repr__(self) -> str:
489
+ return "<Empty>"
490
+
491
+
492
+ class MultiPart(Content):
493
+ def __init__(
494
+ self,
495
+ form: (
496
+ Form
497
+ | typing.Mapping[str, str | typing.Sequence[str]]
498
+ | typing.Sequence[tuple[str, str]]
499
+ | str
500
+ | None
501
+ ) = None,
502
+ files: (
503
+ Files
504
+ | typing.Mapping[str, File | typing.Sequence[File]]
505
+ | typing.Sequence[tuple[str, File]]
506
+ | None
507
+ ) = None,
508
+ boundary: str | None = None,
509
+ ):
510
+ self._form = form if isinstance(form, Form) else Form(form)
511
+ self._files = files if isinstance(files, Files) else Files(files)
512
+ self._boundary = os.urandom(16).hex() if boundary is None else boundary
513
+
514
+ @property
515
+ def form(self) -> Form:
516
+ return self._form
517
+
518
+ @property
519
+ def files(self) -> Files:
520
+ return self._files
521
+
522
+ def open(self) -> Stream:
523
+ form = [(key, value) for key, value in self._form.items()]
524
+ files = [(key, file._path) for key, file in self._files.items()]
525
+ return MultiPartStream(form, files, boundary=self._boundary)
526
+
527
+ def headers(self) -> Headers:
528
+ return Headers(
529
+ {
530
+ "Content-Type": f"multipart/form-data; boundary={self._boundary}",
531
+ "Transfer-Encoding": "chunked",
532
+ }
533
+ )
534
+
535
+ def __repr__(self) -> str:
536
+ return f"<MultiPart form={self._form.multi_items()!r}, files={self._files.multi_items()!r}>"
537
+
538
+
539
+ def select_media(choices: dict[str, type[Content]], content_type: str) -> type[Content]:
540
+ # Eg. multipart/form-data; boundary=398hjiun98jhhi87g98h76g8
541
+ ct, _ = parse_opts_header(content_type)
542
+ # Eg. application/json
543
+ main, _, subtype = ct.partition("/")
544
+
545
+ if "+" in subtype:
546
+ # RFC 6839. Eg. application/schema+json
547
+ _, _, subtype = subtype.partition("+")
548
+
549
+ primary = choices.get(f"{main}/{subtype}")
550
+ if primary is not None:
551
+ return primary
552
+
553
+ secondary = choices.get(f"{main}/*")
554
+ if secondary is not None:
555
+ return secondary
556
+
557
+ return choices["*/*"]