A :class:`MultiDict` is a dictionary subclass customized to deal with multiple values for the same key which is for example used by the parsing functions in the wrappers. This is necessary because some HTML form elements pass multiple values for the same key. :class:`MultiDict` imp
| 135 | |
| 136 | |
| 137 | class MultiDict(TypeConversionDict[K, V]): |
| 138 | """A :class:`MultiDict` is a dictionary subclass customized to deal with |
| 139 | multiple values for the same key which is for example used by the parsing |
| 140 | functions in the wrappers. This is necessary because some HTML form |
| 141 | elements pass multiple values for the same key. |
| 142 | |
| 143 | :class:`MultiDict` implements all standard dictionary methods. |
| 144 | Internally, it saves all values for a key as a list, but the standard dict |
| 145 | access methods will only return the first value for a key. If you want to |
| 146 | gain access to the other values, too, you have to use the `list` methods as |
| 147 | explained below. |
| 148 | |
| 149 | Basic Usage: |
| 150 | |
| 151 | >>> d = MultiDict([('a', 'b'), ('a', 'c')]) |
| 152 | >>> d |
| 153 | MultiDict([('a', 'b'), ('a', 'c')]) |
| 154 | >>> d['a'] |
| 155 | 'b' |
| 156 | >>> d.getlist('a') |
| 157 | ['b', 'c'] |
| 158 | >>> 'a' in d |
| 159 | True |
| 160 | |
| 161 | It behaves like a normal dict thus all dict functions will only return the |
| 162 | first value when multiple values for one key are found. |
| 163 | |
| 164 | From Werkzeug 0.3 onwards, the `KeyError` raised by this class is also a |
| 165 | subclass of the :exc:`~exceptions.BadRequest` HTTP exception and will |
| 166 | render a page for a ``400 BAD REQUEST`` if caught in a catch-all for HTTP |
| 167 | exceptions. |
| 168 | |
| 169 | A :class:`MultiDict` can be constructed from an iterable of |
| 170 | ``(key, value)`` tuples, a dict, a :class:`MultiDict` or from Werkzeug 0.2 |
| 171 | onwards some keyword parameters. |
| 172 | |
| 173 | :param mapping: the initial value for the :class:`MultiDict`. Either a |
| 174 | regular dict, an iterable of ``(key, value)`` tuples |
| 175 | or `None`. |
| 176 | |
| 177 | .. versionchanged:: 3.1 |
| 178 | Implement ``|`` and ``|=`` operators. |
| 179 | """ |
| 180 | |
| 181 | def __init__( |
| 182 | self, |
| 183 | mapping: ( |
| 184 | MultiDict[K, V] |
| 185 | | cabc.Mapping[K, V | list[V] | tuple[V, ...] | set[V]] |
| 186 | | cabc.Iterable[tuple[K, V]] |
| 187 | | None |
| 188 | ) = None, |
| 189 | ) -> None: |
| 190 | if mapping is None: |
| 191 | super().__init__() |
| 192 | elif isinstance(mapping, MultiDict): |
| 193 | super().__init__((k, vs[:]) for k, vs in mapping.lists()) # type: ignore[misc] |
| 194 | elif isinstance(mapping, cabc.Mapping): |
no outgoing calls