MIME-types datastore. This datastore can handle information from mime.types-style files and supports basic determination of MIME type from a filename or URL, and can guess a reasonable extension given a MIME type.
| 57 | |
| 58 | |
| 59 | class MimeTypes: |
| 60 | """MIME-types datastore. |
| 61 | |
| 62 | This datastore can handle information from mime.types-style files |
| 63 | and supports basic determination of MIME type from a filename or |
| 64 | URL, and can guess a reasonable extension given a MIME type. |
| 65 | """ |
| 66 | |
| 67 | def __init__(self, filenames=(), strict=True): |
| 68 | if not inited: |
| 69 | init() |
| 70 | self.encodings_map = _encodings_map_default.copy() |
| 71 | self.suffix_map = _suffix_map_default.copy() |
| 72 | self.types_map = ({}, {}) # dict for (non-strict, strict) |
| 73 | self.types_map_inv = ({}, {}) |
| 74 | for (ext, type) in _types_map_default.items(): |
| 75 | self.add_type(type, ext, True) |
| 76 | for (ext, type) in _common_types_default.items(): |
| 77 | self.add_type(type, ext, False) |
| 78 | for name in filenames: |
| 79 | self.read(name, strict) |
| 80 | |
| 81 | def add_type(self, type, ext, strict=True): |
| 82 | """Add a mapping between a type and an extension. |
| 83 | |
| 84 | When the extension is already known, the new |
| 85 | type will replace the old one. When the type |
| 86 | is already known the extension will be added |
| 87 | to the list of known extensions. |
| 88 | |
| 89 | If strict is true, information will be added to |
| 90 | list of standard types, else to the list of non-standard |
| 91 | types. |
| 92 | |
| 93 | Valid extensions are empty or start with a '.'. |
| 94 | """ |
| 95 | if ext and not ext.startswith('.'): |
| 96 | from warnings import _deprecated |
| 97 | |
| 98 | _deprecated( |
| 99 | "Undotted extensions", |
| 100 | "Using undotted extensions is deprecated and " |
| 101 | "will raise a ValueError in Python {remove}", |
| 102 | remove=(3, 16), |
| 103 | ) |
| 104 | |
| 105 | if not type: |
| 106 | return |
| 107 | self.types_map[strict][ext] = type |
| 108 | exts = self.types_map_inv[strict].setdefault(type, []) |
| 109 | if ext not in exts: |
| 110 | exts.append(ext) |
| 111 | |
| 112 | def guess_type(self, url, strict=True): |
| 113 | """Guess the type of a file which is either a URL or a path-like object. |
| 114 | |
| 115 | Return value is a tuple (type, encoding) where type is None if |
| 116 | the type can't be guessed (no or unknown suffix) or a string |
no outgoing calls
no test coverage detected
searching dependent graphs…