]> jfr.im git - dlqueue.git/blob - venv/lib/python3.11/site-packages/werkzeug/datastructures/etag.py
init: venv aand flask
[dlqueue.git] / venv / lib / python3.11 / site-packages / werkzeug / datastructures / etag.py
1 from __future__ import annotations
2
3 from collections.abc import Collection
4
5
6 class ETags(Collection):
7 """A set that can be used to check if one etag is present in a collection
8 of etags.
9 """
10
11 def __init__(self, strong_etags=None, weak_etags=None, star_tag=False):
12 if not star_tag and strong_etags:
13 self._strong = frozenset(strong_etags)
14 else:
15 self._strong = frozenset()
16
17 self._weak = frozenset(weak_etags or ())
18 self.star_tag = star_tag
19
20 def as_set(self, include_weak=False):
21 """Convert the `ETags` object into a python set. Per default all the
22 weak etags are not part of this set."""
23 rv = set(self._strong)
24 if include_weak:
25 rv.update(self._weak)
26 return rv
27
28 def is_weak(self, etag):
29 """Check if an etag is weak."""
30 return etag in self._weak
31
32 def is_strong(self, etag):
33 """Check if an etag is strong."""
34 return etag in self._strong
35
36 def contains_weak(self, etag):
37 """Check if an etag is part of the set including weak and strong tags."""
38 return self.is_weak(etag) or self.contains(etag)
39
40 def contains(self, etag):
41 """Check if an etag is part of the set ignoring weak tags.
42 It is also possible to use the ``in`` operator.
43 """
44 if self.star_tag:
45 return True
46 return self.is_strong(etag)
47
48 def contains_raw(self, etag):
49 """When passed a quoted tag it will check if this tag is part of the
50 set. If the tag is weak it is checked against weak and strong tags,
51 otherwise strong only."""
52 from ..http import unquote_etag
53
54 etag, weak = unquote_etag(etag)
55 if weak:
56 return self.contains_weak(etag)
57 return self.contains(etag)
58
59 def to_header(self):
60 """Convert the etags set into a HTTP header string."""
61 if self.star_tag:
62 return "*"
63 return ", ".join(
64 [f'"{x}"' for x in self._strong] + [f'W/"{x}"' for x in self._weak]
65 )
66
67 def __call__(self, etag=None, data=None, include_weak=False):
68 if [etag, data].count(None) != 1:
69 raise TypeError("either tag or data required, but at least one")
70 if etag is None:
71 from ..http import generate_etag
72
73 etag = generate_etag(data)
74 if include_weak:
75 if etag in self._weak:
76 return True
77 return etag in self._strong
78
79 def __bool__(self):
80 return bool(self.star_tag or self._strong or self._weak)
81
82 def __str__(self):
83 return self.to_header()
84
85 def __len__(self):
86 return len(self._strong)
87
88 def __iter__(self):
89 return iter(self._strong)
90
91 def __contains__(self, etag):
92 return self.contains(etag)
93
94 def __repr__(self):
95 return f"<{type(self).__name__} {str(self)!r}>"