Debian Codegraph @

Doc/library/mimetypes.rst

raw
1 :mod:`!mimetypes` --- Map filenames to MIME types
2 =================================================
3
4 .. module:: mimetypes
5 :synopsis: Mapping of filename extensions to MIME types.
6
7 .. sectionauthor:: Fred L. Drake, Jr. <[email protected]>
8
9 **Source code:** :source:`Lib/mimetypes.py`
10
11 .. index:: pair: MIME; content type
12
13 --------------
14
15 The :mod:`!mimetypes` module converts between a filename or URL and the MIME type
16 associated with the filename extension. Conversions are provided from filename
17 to MIME type and from MIME type to filename extension; encodings are not
18 supported for the latter conversion.
19
20 The module provides one class and a number of convenience functions. The
21 functions are the normal interface to this module, but some applications may be
22 interested in the class as well.
23
24 The functions described below provide the primary interface for this module. If
25 the module has not been initialized, they will call :func:`init` if they rely on
26 the information :func:`init` sets up.
27
28
29 .. function:: guess_type(url, strict=True)
30
31 .. index:: pair: MIME; headers
32
33 Guess the type of a file based on its filename, path or URL, given by *url*.
34 URL can be a string or a :term:`path-like object`.
35
36 The return value is a tuple ``(type, encoding)`` where *type* is ``None`` if the
37 type can't be guessed (missing or unknown suffix) or a string of the form
38 ``'type/subtype'``, usable for a MIME :mailheader:`content-type` header.
39
40 *encoding* is ``None`` for no encoding or the name of the program used to encode
41 (e.g. :program:`compress` or :program:`gzip`). The encoding is suitable for use
42 as a :mailheader:`Content-Encoding` header, **not** as a
43 :mailheader:`Content-Transfer-Encoding` header. The mappings are table driven.
44 Encoding suffixes are case sensitive; type suffixes are first tried case
45 sensitively, then case insensitively.
46
47 The optional *strict* argument is a flag specifying whether the list of known MIME types
48 is limited to only the official types `registered with IANA
49 <https://www.iana.org/assignments/media-types/media-types.xhtml>`_.
50 However, the behavior of this module also depends on the underlying operating
51 system. Only file types recognized by the OS or explicitly registered with
52 Python's internal database can be identified. When *strict* is ``True`` (the
53 default), only the IANA types are supported; when *strict* is ``False``, some
54 additional non-standard but commonly used MIME types are also recognized.
55
56 .. versionchanged:: 3.8
57 Added support for *url* being a :term:`path-like object`.
58
59 .. soft-deprecated:: 3.13
60 Passing a file path instead of URL is :term:`soft deprecated`.
61 Use :func:`guess_file_type` for this.
62
63
64 .. function:: guess_file_type(path, *, strict=True)
65
66 .. index:: pair: MIME; headers
67
68 Guess the type of a file based on its path, given by *path*.
69 Similar to the :func:`guess_type` function, but accepts a path instead of URL.
70 Path can be a string, a bytes object or a :term:`path-like object`.
71
72 .. versionadded:: 3.13
73
74
75 .. function:: guess_all_extensions(type, strict=True)
76
77 Guess the extensions for a file based on its MIME type, given by *type*. The
78 return value is a list of strings giving all possible filename extensions,
79 including the leading dot (``'.'``). The extensions are not guaranteed to have
80 been associated with any particular data stream, but would be mapped to the MIME
81 type *type* by :func:`guess_type` and :func:`guess_file_type`.
82
83 The optional *strict* argument has the same meaning as with the :func:`guess_type` function.
84
85
86 .. function:: guess_extension(type, strict=True)
87
88 Guess the extension for a file based on its MIME type, given by *type*. The
89 return value is a string giving a filename extension, including the leading dot
90 (``'.'``). The extension is not guaranteed to have been associated with any
91 particular data stream, but would be mapped to the MIME type *type* by
92 :func:`guess_type` and :func:`guess_file_type`.
93 If no extension can be guessed for *type*, ``None`` is returned.
94
95 The optional *strict* argument has the same meaning as with the :func:`guess_type` function.
96
97 Some additional functions and data items are available for controlling the
98 behavior of the module.
99
100
101 .. function:: init(files=None)
102
103 Initialize the internal data structures. If given, *files* must be a sequence
104 of file names which should be used to augment the default type map. If omitted,
105 the file names to use are taken from :const:`knownfiles`; on Windows, the
106 current registry settings are loaded. Each file named in *files* or
107 :const:`knownfiles` takes precedence over those named before it. Calling
108 :func:`init` repeatedly is allowed.
109
110 Specifying an empty list for *files* will prevent the system defaults from
111 being applied: only the well-known values will be present from a built-in list.
112
113 If *files* is ``None`` the internal data structure is completely rebuilt to its
114 initial default value. This is a stable operation and will produce the same results
115 when called multiple times.
116
117 .. versionchanged:: 3.2
118 Previously, Windows registry settings were ignored.
119
120
121 .. function:: read_mime_types(filename)
122
123 Load the type map given in the file *filename*, if it exists. The type map is
124 returned as a dictionary mapping filename extensions, including the leading dot
125 (``'.'``), to strings of the form ``'type/subtype'``. If the file *filename*
126 does not exist or cannot be read, ``None`` is returned.
127
128
129 .. function:: add_type(type, ext, strict=True)
130
131 Add a mapping from the MIME type *type* to the extension *ext*. When the
132 extension is already known, the new type will replace the old one. When the type
133 is already known the extension will be added to the list of known extensions.
134
135 When *strict* is ``True`` (the default), the mapping will be added to the
136 official MIME types, otherwise to the non-standard ones.
137
138
139 .. data:: inited
140
141 Flag indicating whether or not the global data structures have been initialized.
142 This is set to ``True`` by :func:`init`.
143
144
145 .. data:: knownfiles
146
147 .. index:: single: file; mime.types
148
149 List of type map file names commonly installed. These files are typically named
150 :file:`mime.types` and are installed in different locations by different
151 packages.
152
153
154 .. data:: suffix_map
155
156 Dictionary mapping suffixes to suffixes. This is used to allow recognition of
157 encoded files for which the encoding and the type are indicated by the same
158 extension. For example, the :file:`.tgz` extension is mapped to :file:`.tar.gz`
159 to allow the encoding and type to be recognized separately.
160
161
162 .. data:: encodings_map
163
164 Dictionary mapping filename extensions to encoding types.
165
166
167 .. data:: types_map
168
169 Dictionary mapping filename extensions to MIME types.
170
171
172 .. data:: common_types
173
174 Dictionary mapping filename extensions to non-standard, but commonly found MIME
175 types.
176
177
178 An example usage of the module::
179
180 >>> import mimetypes
181 >>> mimetypes.init()
182 >>> mimetypes.knownfiles
183 ['/etc/mime.types', '/etc/httpd/mime.types', ... ]
184 >>> mimetypes.suffix_map['.tgz']
185 '.tar.gz'
186 >>> mimetypes.encodings_map['.gz']
187 'gzip'
188 >>> mimetypes.types_map['.tgz']
189 'application/x-tar-gz'
190
191
192 .. _mimetypes-objects:
193
194 MimeTypes objects
195 -----------------
196
197 The :class:`MimeTypes` class may be useful for applications which may want more
198 than one MIME-type database; it provides an interface similar to the one of the
199 :mod:`!mimetypes` module.
200
201
202 .. class:: MimeTypes(filenames=(), strict=True)
203
204 This class represents a MIME-types database. By default, it provides access to
205 the same database as the rest of this module. The initial database is a copy of
206 that provided by the module, and may be extended by loading additional
207 :file:`mime.types`\ -style files into the database using the :meth:`read` or
208 :meth:`readfp` methods. The mapping dictionaries may also be cleared before
209 loading additional data if the default data is not desired.
210
211 The optional *filenames* parameter can be used to cause additional files to be
212 loaded "on top" of the default database.
213
214
215 .. attribute:: MimeTypes.suffix_map
216
217 Dictionary mapping suffixes to suffixes. This is used to allow recognition of
218 encoded files for which the encoding and the type are indicated by the same
219 extension. For example, the :file:`.tgz` extension is mapped to :file:`.tar.gz`
220 to allow the encoding and type to be recognized separately. This is initially a
221 copy of the global :data:`suffix_map` defined in the module.
222
223
224 .. attribute:: MimeTypes.encodings_map
225
226 Dictionary mapping filename extensions to encoding types. This is initially a
227 copy of the global :data:`encodings_map` defined in the module.
228
229
230 .. attribute:: MimeTypes.types_map
231
232 Tuple containing two dictionaries, mapping filename extensions to MIME types:
233 the first dictionary is for the non-standards types and the second one is for
234 the standard types. They are initialized by :data:`common_types` and
235 :data:`types_map`.
236
237
238 .. attribute:: MimeTypes.types_map_inv
239
240 Tuple containing two dictionaries, mapping MIME types to a list of filename
241 extensions: the first dictionary is for the non-standards types and the
242 second one is for the standard types. They are initialized by
243 :data:`common_types` and :data:`types_map`.
244
245
246 .. method:: MimeTypes.guess_extension(type, strict=True)
247
248 Similar to the :func:`guess_extension` function, using the tables stored as part
249 of the object.
250
251
252 .. method:: MimeTypes.guess_type(url, strict=True)
253
254 Similar to the :func:`guess_type` function, using the tables stored as part of
255 the object.
256
257
258 .. method:: MimeTypes.guess_file_type(path, *, strict=True)
259
260 Similar to the :func:`guess_file_type` function, using the tables stored
261 as part of the object.
262
263 .. versionadded:: 3.13
264
265
266 .. method:: MimeTypes.guess_all_extensions(type, strict=True)
267
268 Similar to the :func:`guess_all_extensions` function, using the tables stored
269 as part of the object.
270
271
272 .. method:: MimeTypes.read(filename, strict=True)
273
274 Load MIME information from a file named *filename*. This uses :meth:`readfp` to
275 parse the file.
276
277 If *strict* is ``True``, information will be added to list of standard types,
278 else to the list of non-standard types.
279
280
281 .. method:: MimeTypes.readfp(fp, strict=True)
282
283 Load MIME type information from an open file *fp*. The file must have the format of
284 the standard :file:`mime.types` files.
285
286 If *strict* is ``True``, information will be added to the list of standard
287 types, else to the list of non-standard types.
288
289
290 .. method:: MimeTypes.read_windows_registry(strict=True)
291
292 Load MIME type information from the Windows registry.
293
294 .. availability:: Windows.
295
296 If *strict* is ``True``, information will be added to the list of standard
297 types, else to the list of non-standard types.
298
299 .. versionadded:: 3.2
300
301
302 .. method:: MimeTypes.add_type(type, ext, strict=True)
303
304 Add a mapping from the MIME type *type* to the extension *ext*.
305 Valid extensions start with a '.' or are empty. When the
306 extension is already known, the new type will replace the old one. When the type
307 is already known the extension will be added to the list of known extensions.
308
309 When *strict* is ``True`` (the default), the mapping will be added to the
310 official MIME types, otherwise to the non-standard ones.
311
312 .. deprecated-removed:: 3.14 3.16
313 Invalid, undotted extensions will raise a
314 :exc:`ValueError` in Python 3.16.
315
316
317 .. _mimetypes-cli:
318
319 Command-line usage
320 ------------------
321
322 The :mod:`!mimetypes` module can be executed as a script from the command line.
323
324 .. code-block:: sh
325
326 python -m mimetypes [-h] [-e] [-l] type [type ...]
327
328 The following options are accepted:
329
330 .. program:: mimetypes
331
332 .. cmdoption:: -h
333 --help
334
335 Show the help message and exit.
336
337 .. cmdoption:: -e
338 --extension
339
340 Guess extension instead of type.
341
342 .. cmdoption:: -l
343 --lenient
344
345 Additionally search for some common, but non-standard types.
346
347 By default the script converts MIME types to file extensions.
348 However, if ``--extension`` is specified,
349 it converts file extensions to MIME types.
350
351 For each ``type`` entry, the script writes a line into the standard output
352 stream. If an unknown type occurs, it writes an error message into the
353 standard error stream and exits with the return code ``1``.
354
355
356 .. mimetypes-cli-example:
357
358 Command-line example
359 --------------------
360
361 Here are some examples of typical usage of the :mod:`!mimetypes` command-line
362 interface:
363
364 .. code-block:: console
365
366 $ # get a MIME type by a file name
367 $ python -m mimetypes filename.png
368 type: image/png encoding: None
369
370 $ # get a MIME type by a URL
371 $ python -m mimetypes https://example.com/filename.txt
372 type: text/plain encoding: None
373
374 $ # get a complex MIME type
375 $ python -m mimetypes filename.tar.gz
376 type: application/x-tar encoding: gzip
377
378 $ # get a MIME type for a rare file extension
379 $ python -m mimetypes filename.pict
380 error: unknown extension of filename.pict
381
382 $ # now look in the extended database built into Python
383 $ python -m mimetypes --lenient filename.pict
384 type: image/pict encoding: None
385
386 $ # get a file extension by a MIME type
387 $ python -m mimetypes --extension text/javascript
388 .js
389
390 $ # get a file extension by a rare MIME type
391 $ python -m mimetypes --extension text/xul
392 error: unknown type text/xul
393
394 $ # now look in the extended database again
395 $ python -m mimetypes --extension --lenient text/xul
396 .xul
397
398 $ # try to feed an unknown file extension
399 $ python -m mimetypes filename.sh filename.nc filename.xxx filename.txt
400 type: application/x-sh encoding: None
401 type: application/x-netcdf encoding: None
402 error: unknown extension of filename.xxx
403
404 $ # try to feed an unknown MIME type
405 $ python -m mimetypes --extension audio/aac audio/opus audio/future audio/x-wav
406 .aac
407 .opus
408 error: unknown type audio/future