File: content_type.py

package info (click to toggle)
python-testtools 2.8.2-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,244 kB
  • sloc: python: 15,086; makefile: 127; sh: 3
file content (41 lines) | stat: -rw-r--r-- 1,318 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# Copyright (c) 2009-2012 testtools developers. See LICENSE for details.

"""ContentType - a MIME Content Type."""


class ContentType:
    """A content type from http://www.iana.org/assignments/media-types/

    :ivar type: The primary type, e.g. "text" or "application"
    :ivar subtype: The subtype, e.g. "plain" or "octet-stream"
    :ivar parameters: A dict of additional parameters specific to the
        content type.
    """

    def __init__(self, primary_type, sub_type, parameters=None):
        """Create a ContentType."""
        if None in (primary_type, sub_type):
            raise ValueError(f"None not permitted in {primary_type!r}, {sub_type!r}")
        self.type = primary_type
        self.subtype = sub_type
        self.parameters = parameters or {}

    def __eq__(self, other):
        if type(other) is not ContentType:
            return False
        return self.__dict__ == other.__dict__

    def __repr__(self):
        if self.parameters:
            params = "; "
            params += "; ".join(
                sorted(f'{k}="{v}"' for k, v in self.parameters.items())
            )
        else:
            params = ""
        return f"{self.type}/{self.subtype}{params}"


JSON = ContentType("application", "json")

UTF8_TEXT = ContentType("text", "plain", {"charset": "utf8"})