v0.166.0
  1import codecs
  2import copy
  3import json
  4import secrets
  5import uuid
  6from collections.abc import Iterator
  7from functools import cached_property
  8from io import BytesIO
  9from itertools import chain
 10from typing import TYPE_CHECKING, Any, Protocol, TypeVar, overload
 11from urllib.parse import parse_qsl, quote, urlencode, urljoin, urlsplit
 12
 13if TYPE_CHECKING:
 14    from plain.urls import ResolverMatch
 15
 16from plain.exceptions import ImproperlyConfigured
 17from plain.http.cookie import parse_cookie, unsign_cookie_value
 18from plain.http.multipartparser import (
 19    MultiPartParser,
 20)
 21from plain.runtime import settings
 22from plain.utils.datastructures import CaseInsensitiveMapping, MultiValueDict
 23from plain.utils.encoding import iri_to_uri
 24from plain.utils.http import parse_header_parameters
 25
 26from .exceptions import (
 27    BadRequestError400,
 28    ContentTooLargeError413,
 29    TooManyFieldsSentError400,
 30    UnsupportedMediaTypeError415,
 31)
 32
 33_T = TypeVar("_T")
 34
 35
 36class RequestStream(Protocol):
 37    """A request body that is read rather than held: what `Request(body=...)`
 38    takes when the body isn't `bytes`. Anything providing `read`, `readline`
 39    and `close` over bytes will work — the server passes the file it
 40    received the body into.
 41    """
 42
 43    def read(self, size: int | None = ..., /) -> bytes: ...
 44    def readline(self, size: int | None = ..., /) -> bytes: ...
 45    def close(self) -> None: ...
 46
 47
 48class UnreadablePostError(OSError):
 49    pass
 50
 51
 52class RawPostDataException(Exception):
 53    """
 54    You cannot access raw_post_data from a request that has
 55    multipart/* POST data if it has been accessed via POST,
 56    FILES, etc..
 57    """
 58
 59
 60class Request:
 61    """A basic HTTP request."""
 62
 63    non_picklable_attrs = frozenset(["resolver_match", "_stream"])
 64
 65    def __init__(
 66        self,
 67        *,
 68        method: str,
 69        path: str,
 70        headers: dict[str, str] | None = None,
 71        query_string: str = "",
 72        body: bytes | RequestStream = b"",
 73        body_ingest_seconds: float | None = None,
 74        server_scheme: str = "http",
 75        server_name: str = "",
 76        server_port: str = "",
 77        remote_addr: str = "",
 78    ):
 79        """
 80        `body` is the request's body: `bytes`, or a stream to read it from.
 81        It is only the bytes — the `Content-Type` and `Content-Length`
 82        headers that describe it are the caller's to pass in `headers`.
 83
 84        `body_ingest_seconds` is how long receiving the body took, for the
 85        request span to report (a slow upload happens before the view runs
 86        and would otherwise be invisible in traces). The server passes it;
 87        a request that didn't arrive over a connection has none.
 88        """
 89        self.unique_id = str(uuid.uuid4())
 90        self.resolver_match: ResolverMatch | None = None
 91
 92        self.method = method
 93        self.path = path
 94        self.server_name = server_name
 95        self.server_port = server_port
 96        self.remote_addr = remote_addr
 97        self.query_string = query_string
 98        self.server_scheme = server_scheme
 99        self.headers = RequestHeaders(headers or {})
100
101        # Every body is read the same way, through `_stream`: bytes in hand
102        # are wrapped, so `body`, `form_data`, `files` and `read()` don't
103        # know which they were given.
104        self._stream: RequestStream = BytesIO(body) if isinstance(body, bytes) else body
105        self._read_started = False
106        self.body_ingest_seconds = body_ingest_seconds
107
108        # Parse content type, params, and encoding from headers
109        self.content_type: str | None
110        self.content_params: dict[str, str] | None
111        self.content_type, self.content_params = parse_header_parameters(
112            self.headers.get("Content-Type", "")
113        )
114        self.encoding: str | None = None
115        if "charset" in (self.content_params or {}):
116            try:
117                codecs.lookup(self.content_params["charset"])
118            except LookupError:
119                pass
120            else:
121                self.encoding = self.content_params["charset"]
122
123    def __repr__(self) -> str:
124        if not self.get_full_path():
125            return f"<{self.__class__.__name__}>"
126        return f"<{self.__class__.__name__}: {self.method} {self.get_full_path()!r}>"
127
128    def __getstate__(self) -> dict[str, Any]:
129        obj_dict = self.__dict__.copy()
130        for attr in self.non_picklable_attrs:
131            if attr in obj_dict:
132                del obj_dict[attr]
133        return obj_dict
134
135    def __deepcopy__(self, memo: dict[int, Any]) -> Request:
136        obj = copy.copy(self)
137        for attr in self.non_picklable_attrs:
138            if hasattr(self, attr):
139                setattr(obj, attr, copy.deepcopy(getattr(self, attr), memo))
140        memo[id(self)] = obj
141        return obj
142
143    @cached_property
144    def query_params(self) -> QueryDict:
145        return QueryDict(self.query_string, encoding=self.encoding)
146
147    @cached_property
148    def cookies(self) -> dict[str, str]:
149        return parse_cookie(self.headers.get("Cookie", ""))
150
151    @cached_property
152    def csp_nonce(self) -> str:
153        """Generate a cryptographically secure nonce for Content Security Policy.
154
155        The nonce is generated once per request and cached. It can be used in
156        CSP headers and templates to allow specific inline scripts/styles while
157        blocking others.
158        """
159        return secrets.token_urlsafe(16)
160
161    @cached_property
162    def accepted_types(self) -> list[MediaType]:
163        """Return accepted media types sorted by quality value (highest first).
164
165        When quality values are equal, the original order from the Accept header
166        is preserved (as per HTTP spec).
167        """
168        header = self.headers.get("Accept", "*/*")
169        types = [MediaType(token) for token in header.split(",") if token.strip()]
170        return sorted(types, key=lambda t: t.quality, reverse=True)
171
172    def get_preferred_type(self, *media_types: str) -> str | None:
173        """Return the most preferred media type from the given options.
174
175        Checks the Accept header in priority order (by quality value) and returns
176        the first matching media type from the provided options.
177
178        Returns None if none of the options are accepted.
179
180        Example:
181            # Accept: text/html;q=1.0, application/json;q=0.5
182            request.get_preferred_type("application/json", "text/html")  # Returns "text/html"
183        """
184        for accepted in self.accepted_types:
185            for option in media_types:
186                if accepted.match(option):
187                    return option
188        return None
189
190    def accepts(self, media_type: str) -> bool:
191        """Check if the given media type is accepted."""
192        return self.get_preferred_type(media_type) is not None
193
194    @cached_property
195    def host(self) -> str:
196        """
197        Return the HTTP host using the environment or request headers.
198
199        Host validation is performed by HostValidationMiddleware, so this
200        property can safely return the host without any validation.
201        """
202        # We try three options, in order of decreasing preference.
203        if settings.HTTP_X_FORWARDED_HOST and (
204            xff_host := self.headers.get("X-Forwarded-Host")
205        ):
206            host = xff_host
207        elif http_host := self.headers.get("Host"):
208            host = http_host
209        else:
210            # Reconstruct the host from server_name/port.
211            host = self.server_name
212            server_port = self.port
213            if server_port != ("443" if self.is_https() else "80"):
214                host = f"{host}:{server_port}"
215        return host
216
217    @cached_property
218    def port(self) -> str:
219        """Return the port number for the request as a string."""
220        if settings.HTTP_X_FORWARDED_PORT and (
221            xff_port := self.headers.get("X-Forwarded-Port")
222        ):
223            port = xff_port
224        else:
225            port = self.server_port
226        return str(port)
227
228    @cached_property
229    def client_ip(self) -> str:
230        """Return the client's IP address.
231
232        If HTTP_X_FORWARDED_FOR is True, checks the X-Forwarded-For header first
233        (using the first/leftmost IP). Otherwise returns REMOTE_ADDR directly.
234
235        Only enable HTTP_X_FORWARDED_FOR when behind a trusted proxy that
236        overwrites the X-Forwarded-For header.
237        """
238        if settings.HTTP_X_FORWARDED_FOR and (
239            xff := self.headers.get("X-Forwarded-For")
240        ):
241            return xff.split(",")[0].strip()
242        return self.remote_addr
243
244    @property
245    def content_length(self) -> int:
246        """Return the Content-Length header value, or 0 if not provided."""
247        try:
248            return int(self.headers.get("Content-Length") or 0)
249        except ValueError, TypeError:
250            return 0
251
252    def get_full_path(self) -> str:
253        """Return the full path for the request, including query string."""
254        # RFC 3986 requires query string arguments to be in the ASCII range.
255        # Rather than crash if this doesn't happen, we encode defensively.
256
257        def escape_uri_path(path: str) -> str:
258            """
259            Escape the unsafe characters from the path portion of a Uniform Resource
260            Identifier (URI).
261            """
262            # These are the "reserved" and "unreserved" characters specified in RFC
263            # 3986 Sections 2.2 and 2.3:
264            #   reserved    = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | ","
265            #   unreserved  = alphanum | mark
266            #   mark        = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
267            # The list of safe characters here is constructed subtracting ";", "=",
268            # and "?" according to RFC 3986 Section 3.3.
269            # The reason for not subtracting and escaping "/" is that we are escaping
270            # the entire path, not a path segment.
271            return quote(path, safe="/:@&+$,-_.!~*'()")
272
273        return "{}{}".format(
274            escape_uri_path(self.path),
275            ("?" + (iri_to_uri(self.query_string) or "")) if self.query_string else "",
276        )
277
278    def build_absolute_uri(self, location: str | None = None) -> str:
279        """
280        Build an absolute URI from the location and the variables available in
281        this request. If no ``location`` is specified, build the absolute URI
282        using request.get_full_path(). If the location is absolute, convert it
283        to an RFC 3987 compliant URI and return it. If location is relative or
284        is scheme-relative (i.e., ``//example.com/``), urljoin() it to a base
285        URL constructed from the request variables.
286        """
287        if location is None:
288            # Make it an absolute url (but schemeless and domainless) for the
289            # edge case that the path starts with '//'.
290            location = f"//{self.get_full_path()}"
291        else:
292            # Coerce lazy locations.
293            location = str(location)
294        bits = urlsplit(location)
295        if not (bits.scheme and bits.netloc):
296            current_scheme_host = f"{self.scheme}://{self.host}"
297
298            # Handle the simple, most common case. If the location is absolute
299            # and a scheme or host (netloc) isn't provided, skip an expensive
300            # urljoin() as long as no path segments are '.' or '..'.
301            if (
302                bits.path.startswith("/")
303                and not bits.scheme
304                and not bits.netloc
305                and "/./" not in bits.path
306                and "/../" not in bits.path
307            ):
308                # If location starts with '//' but has no netloc, reuse the
309                # schema and netloc from the current request. Strip the double
310                # slashes and continue as if it wasn't specified.
311                location = current_scheme_host + location.removeprefix("//")
312            else:
313                # Join the constructed URL with the provided location, which
314                # allows the provided location to apply query strings to the
315                # base path.
316                location = urljoin(current_scheme_host + self.path, location)
317
318        return iri_to_uri(location) or ""
319
320    @property
321    def scheme(self) -> str:
322        if settings.HTTPS_PROXY_HEADER:
323            if ":" not in settings.HTTPS_PROXY_HEADER:
324                raise ImproperlyConfigured(
325                    "The HTTPS_PROXY_HEADER setting must be a string in the format "
326                    "'Header-Name: value' (e.g., 'X-Forwarded-Proto: https')."
327                )
328            header, secure_value = settings.HTTPS_PROXY_HEADER.split(":", 1)
329            header = header.strip()
330            secure_value = secure_value.strip()
331            header_value = self.headers.get(header)
332            if header_value is not None:
333                header_value, *_ = header_value.split(",", 1)
334                return "https" if header_value.strip() == secure_value else "http"
335        return self.server_scheme
336
337    def is_https(self) -> bool:
338        return self.scheme == "https"
339
340    @property
341    def body(self) -> bytes:
342        if not hasattr(self, "_body"):
343            if self._read_started:
344                raise RawPostDataException(
345                    "You cannot access body after reading from request's data stream"
346                )
347
348            max_size = settings.DATA_UPLOAD_MAX_MEMORY_SIZE
349
350            # Fast path: reject immediately if Content-Length exceeds the limit.
351            if max_size is not None and self.content_length > max_size:
352                raise ContentTooLargeError413(
353                    "Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE."
354                )
355
356            try:
357                if max_size is not None:
358                    # Read in chunks to enforce the limit without buffering
359                    # an arbitrarily large body (e.g. chunked transfers
360                    # with no Content-Length).
361                    chunks = []
362                    bytes_read = 0
363                    while True:
364                        chunk = self.read(max_size - bytes_read + 1)
365                        if not chunk:
366                            break
367                        bytes_read += len(chunk)
368                        if bytes_read > max_size:
369                            raise ContentTooLargeError413(
370                                "Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE."
371                            )
372                        chunks.append(chunk)
373                    self._body = b"".join(chunks)
374                else:
375                    self._body = self.read()
376            except OSError as e:
377                raise UnreadablePostError(*e.args) from e
378            finally:
379                self._stream.close()
380            self._stream = BytesIO(self._body)
381        return self._body
382
383    @cached_property
384    def _multipart_data(self) -> tuple[QueryDict, MultiValueDict]:
385        """Parse multipart/form-data. Used internally by form_data and files properties.
386
387        Raises MultiPartParserError or TooManyFilesSentError400 for malformed uploads,
388        which are handled by response_for_exception() as 400 errors.
389        """
390        return MultiPartParser(self).parse()
391
392    @cached_property
393    def json_data(self) -> dict[str, Any]:
394        """
395        Parsed JSON object from request body.
396
397        Returns dict for JSON objects.
398        Raises BadRequestError400 if JSON is invalid or not an object.
399        Raises UnsupportedMediaTypeError415 if request content-type is not JSON.
400
401        Use this when you expect JSON object data and want type-safe dict access.
402        """
403        if not self.content_type or not self.content_type.startswith(
404            "application/json"
405        ):
406            raise UnsupportedMediaTypeError415(
407                f"Request content-type is not JSON (got: {self.content_type})"
408            )
409        try:
410            parsed = json.loads(self.body)
411        except json.JSONDecodeError as e:
412            raise BadRequestError400(f"Invalid JSON in request body: {e}") from e
413
414        if not isinstance(parsed, dict):
415            raise BadRequestError400(
416                f"Expected JSON object, got {type(parsed).__name__}"
417            )
418        return parsed
419
420    @cached_property
421    def form_data(self) -> QueryDict:
422        """
423        Form data from POST body.
424
425        Returns QueryDict for application/x-www-form-urlencoded or
426        multipart/form-data content types.
427        Returns empty QueryDict if Content-Type is missing (e.g., GET requests).
428        Raises UnsupportedMediaTypeError415 if request has a different content-type with a body.
429
430        Use this when you expect form data and want type-safe QueryDict access.
431        """
432        if self.content_type == "application/x-www-form-urlencoded":
433            return QueryDict(self.body, encoding=self.encoding)
434        elif self.content_type == "multipart/form-data":
435            return self._multipart_data[0]
436        elif not self.content_type:
437            # No Content-Type (e.g., GET requests) - return empty QueryDict
438            return QueryDict(b"", encoding=self.encoding)
439        else:
440            raise UnsupportedMediaTypeError415(
441                f"Request content-type is not form data (got: {self.content_type})"
442            )
443
444    @cached_property
445    def files(self) -> MultiValueDict:
446        """
447        File uploads from multipart/form-data requests.
448
449        Returns MultiValueDict of uploaded files for multipart requests,
450        or empty MultiValueDict for other content types.
451        """
452        if self.content_type == "multipart/form-data":
453            return self._multipart_data[1]
454        return MultiValueDict()
455
456    def close(self) -> None:
457        # Close any uploaded files if they were accessed
458        if self.content_type == "multipart/form-data" and hasattr(
459            self, "_multipart_data"
460        ):
461            _, files = self._multipart_data
462            for f in chain.from_iterable(list_[1] for list_ in files.lists()):
463                f.close()
464
465    # File-like and iterator interface.
466    #
467    # Reads come from self._stream, the body the request was constructed
468    # with. Once request.json_data, request.form_data, or request.body has
469    # read it all, self._stream points to a BytesIO holding that data.
470
471    def read(self, *args: Any, **kwargs: Any) -> bytes:
472        self._read_started = True
473        try:
474            return self._stream.read(*args, **kwargs)
475        except OSError as e:
476            raise UnreadablePostError(*e.args) from e
477
478    def readline(self, *args: Any, **kwargs: Any) -> bytes:
479        self._read_started = True
480        try:
481            return self._stream.readline(*args, **kwargs)
482        except OSError as e:
483            raise UnreadablePostError(*e.args) from e
484
485    def __iter__(self) -> Iterator[bytes]:
486        return iter(self.readline, b"")
487
488    def readlines(self) -> list[bytes]:
489        return list(self)
490
491    def get_signed_cookie(
492        self,
493        key: str,
494        default: str | None = None,
495        salt: str = "",
496        max_age: int | None = None,
497    ) -> str | None:
498        """
499        Retrieve a cookie value signed with the SECRET_KEY.
500
501        Return default if the cookie doesn't exist or signature verification fails.
502        """
503
504        try:
505            cookie_value = self.cookies[key]
506        except KeyError:
507            return default
508
509        return unsign_cookie_value(key, cookie_value, salt, max_age, default)
510
511
512class RequestHeaders(CaseInsensitiveMapping):
513    def __init__(self, headers: dict[str, str]):
514        normalized = {
515            name.replace("_", "-").title(): value for name, value in headers.items()
516        }
517        super().__init__(normalized)
518
519    def __getitem__(self, key: str) -> str:
520        """Allow header lookup using underscores in place of hyphens."""
521        return super().__getitem__(key.replace("_", "-"))
522
523
524class QueryDict(MultiValueDict):
525    """
526    A specialized MultiValueDict which represents a query string.
527
528    A QueryDict can be used to represent GET or POST data. It subclasses
529    MultiValueDict since keys in such data can be repeated, for instance
530    in the data from a form with a <select multiple> field.
531
532    By default QueryDicts are immutable, though the copy() method
533    will always return a mutable copy.
534
535    Both keys and values set on this class are converted from the given encoding
536    (UTF-8 by default) to str.
537    """
538
539    # These are both reset in __init__, but is specified here at the class
540    # level so that unpickling will have valid values
541    _mutable = True
542    _encoding = None
543
544    def __init__(
545        self,
546        query_string: str | bytes | None = None,
547        mutable: bool = False,
548        encoding: str | None = None,
549    ):
550        super().__init__()
551        self.encoding = encoding or "utf-8"
552        query_string = query_string or ""
553        parse_qsl_kwargs: dict[str, Any] = {
554            "keep_blank_values": True,
555            "encoding": self.encoding,
556            "max_num_fields": settings.DATA_UPLOAD_MAX_NUMBER_FIELDS,
557        }
558        if isinstance(query_string, bytes):
559            # query_string normally contains URL-encoded data, a subset of ASCII.
560            query_bytes = query_string
561            try:
562                query_string = query_bytes.decode(self.encoding)
563            except UnicodeDecodeError:
564                # ... but some user agents are misbehaving :-(
565                query_string = query_bytes.decode("iso-8859-1")
566        try:
567            for key, value in parse_qsl(query_string, **parse_qsl_kwargs):
568                self.appendlist(key, value)
569        except ValueError as e:
570            # ValueError can also be raised if the strict_parsing argument to
571            # parse_qsl() is True. As that is not used by Plain, assume that
572            # the exception was raised by exceeding the value of max_num_fields
573            # instead of fragile checks of exception message strings.
574            raise TooManyFieldsSentError400(
575                "The number of GET/POST parameters exceeded "
576                "settings.DATA_UPLOAD_MAX_NUMBER_FIELDS."
577            ) from e
578        self._mutable = mutable
579
580    @classmethod
581    def fromkeys(  # ty: ignore[invalid-method-override]
582        cls,
583        iterable: Any,
584        value: str = "",
585        mutable: bool = False,
586        encoding: str | None = None,
587    ) -> QueryDict:
588        """
589        Return a new QueryDict with keys (may be repeated) from an iterable and
590        values from value.
591        """
592        q = cls("", mutable=True, encoding=encoding)
593        for key in iterable:
594            q.appendlist(key, value)
595        if not mutable:
596            q._mutable = False
597        return q
598
599    @property
600    def encoding(self) -> str:
601        if self._encoding is None:
602            self._encoding = "utf-8"
603        return self._encoding
604
605    @encoding.setter
606    def encoding(self, value: str) -> None:
607        self._encoding = value
608
609    def _assert_mutable(self) -> None:
610        if not self._mutable:
611            raise AttributeError("This QueryDict instance is immutable")
612
613    def __setitem__(self, key: str, value: Any) -> None:
614        self._assert_mutable()
615        key = self.bytes_to_text(key, self.encoding)
616        value = self.bytes_to_text(value, self.encoding)
617        super().__setitem__(key, value)
618
619    def __delitem__(self, key: str) -> None:
620        self._assert_mutable()
621        super().__delitem__(key)
622
623    def __getitem__(self, key: str) -> str:  # ty: ignore[invalid-method-override]
624        """
625        Return the last data value for this key as a string.
626        QueryDict values are always strings.
627        """
628        return super().__getitem__(key)
629
630    def __copy__(self) -> QueryDict:
631        result = self.__class__("", mutable=True, encoding=self.encoding)
632        for key, value in self.lists():
633            result.setlist(key, value)
634        return result
635
636    def __deepcopy__(self, memo: dict[int, Any]) -> QueryDict:
637        result = self.__class__("", mutable=True, encoding=self.encoding)
638        memo[id(self)] = result
639        for key, value in self.lists():
640            result.setlist(copy.deepcopy(key, memo), copy.deepcopy(value, memo))
641        return result
642
643    def setlist(self, key: str, list_: list[Any]) -> None:
644        self._assert_mutable()
645        key = self.bytes_to_text(key, self.encoding)
646        list_ = [self.bytes_to_text(elt, self.encoding) for elt in list_]
647        super().setlist(key, list_)
648
649    def setlistdefault(
650        self, key: str, default_list: list[Any] | None = None
651    ) -> list[Any]:
652        self._assert_mutable()
653        return super().setlistdefault(key, default_list)
654
655    def appendlist(self, key: str, value: Any) -> None:
656        self._assert_mutable()
657        key = self.bytes_to_text(key, self.encoding)
658        value = self.bytes_to_text(value, self.encoding)
659        super().appendlist(key, value)
660
661    def getlist(self, key: str, default: list[str] | None = None) -> list[str]:
662        """
663        Return the list of values for the key as strings.
664        QueryDict values are always strings.
665        """
666        return super().getlist(key, default)
667
668    @overload
669    def get(self, key: str) -> str | None: ...
670
671    @overload
672    def get(self, key: str, default: str) -> str: ...
673
674    @overload
675    def get(self, key: str, default: _T) -> str | _T: ...
676
677    def get(self, key: str, default: Any = None) -> str | Any:  # ty: ignore[invalid-method-override]
678        """
679        Return the last data value for the passed key. If key doesn't exist
680        or value is an empty list, return `default`.
681
682        QueryDict values are always strings (from URL parsing), but the
683        return type preserves the type of the default parameter for type safety.
684
685        Examples:
686            get("page")         -> str | None
687            get("page", "1")    -> str
688            get("page", 1)      -> str | int
689        """
690        return super().get(key, default)
691
692    @overload
693    def pop(self, key: str) -> str: ...
694
695    @overload
696    def pop(self, key: str, default: str) -> str: ...
697
698    @overload
699    def pop(self, key: str, default: _T) -> str | _T: ...
700
701    def pop(self, key: str, *args: Any) -> str | Any:  # ty: ignore[invalid-method-override]
702        """
703        Remove and return a value for the key.
704
705        QueryDict values are always strings, but the return type preserves
706        the type of the default parameter for type safety.
707
708        Examples:
709            pop("page")         -> str (or raises KeyError)
710            pop("page", "1")    -> str
711            pop("page", 1)      -> str | int
712        """
713        self._assert_mutable()
714        return super().pop(key, *args)
715
716    def popitem(self) -> tuple[str, Any]:
717        self._assert_mutable()
718        return super().popitem()
719
720    def clear(self) -> None:
721        self._assert_mutable()
722        super().clear()
723
724    def setdefault(self, key: str, default: Any = None) -> Any:
725        self._assert_mutable()
726        key = self.bytes_to_text(key, self.encoding)
727        default = self.bytes_to_text(default, self.encoding)
728        return super().setdefault(key, default)
729
730    def copy(self) -> QueryDict:
731        """Return a mutable copy of this object."""
732        return self.__deepcopy__({})
733
734    def urlencode(self, safe: str | None = None) -> str:
735        """
736        Return an encoded string of all query string arguments.
737
738        `safe` specifies characters which don't require quoting, for example::
739
740            >>> q = QueryDict(mutable=True)
741            >>> q['next'] = '/a&b/'
742            >>> q.urlencode()
743            'next=%2Fa%26b%2F'
744            >>> q.urlencode(safe='/')
745            'next=/a%26b/'
746        """
747        output = []
748        if safe:
749            safe_bytes: bytes = safe.encode(self.encoding)
750
751            def encode(k: bytes, v: bytes) -> str:
752                return f"{quote(k, safe_bytes)}={quote(v, safe_bytes)}"
753
754        else:
755
756            def encode(k: bytes, v: bytes) -> str:
757                return urlencode({k: v})
758
759        for k, list_ in self.lists():
760            output.extend(
761                encode(k.encode(self.encoding), str(v).encode(self.encoding))
762                for v in list_
763            )
764        return "&".join(output)
765
766    # It's neither necessary nor appropriate to use
767    # plain.utils.encoding.force_str() for parsing URLs and form inputs. Thus,
768    # this slightly more restricted function, used by QueryDict.
769    @staticmethod
770    def bytes_to_text(s: Any, encoding: str) -> str:
771        """
772        Convert bytes objects to strings, using the given encoding. Illegally
773        encoded input characters are replaced with Unicode "unknown" codepoint
774        (\ufffd).
775
776        Return any non-bytes objects without change.
777        """
778        if isinstance(s, bytes):
779            return str(s, encoding, "replace")
780        else:
781            return s
782
783
784class MediaType:
785    def __init__(self, media_type_raw_line: str | MediaType):
786        line = str(media_type_raw_line) if media_type_raw_line else ""
787        full_type, self.params = parse_header_parameters(line)
788        self.main_type, _, self.sub_type = full_type.partition("/")
789
790    def __str__(self) -> str:
791        params_str = "".join(f"; {k}={v}" for k, v in self.params.items())
792        return "{}{}{}".format(
793            self.main_type,
794            (f"/{self.sub_type}") if self.sub_type else "",
795            params_str,
796        )
797
798    def __repr__(self) -> str:
799        return f"<{self.__class__.__qualname__}: {self}>"
800
801    @property
802    def is_all_types(self) -> bool:
803        return self.main_type == "*" and self.sub_type == "*"
804
805    @property
806    def quality(self) -> float:
807        """Return the quality value from the Accept header (default 1.0)."""
808        return float(self.params.get("q", 1.0))
809
810    def match(self, other: str | MediaType) -> bool:
811        if self.is_all_types:
812            return True
813        other = MediaType(other)
814        return self.main_type == other.main_type and self.sub_type in {
815            "*",
816            other.sub_type,
817        }