mimetypes — Mapeia nomes de arquivos para tipos MIME

Código-fonte: Lib/mimetypes.py


O módulo mimetypes converte entre um nome de arquivo ou URL e o tipo MIME associado à extensão do arquivo. As conversões são fornecidas do nome do arquivo para o tipo MIME e da extensão do tipo MIME para o nome do arquivo; codificações não são suportadas para a última conversão.

O módulo fornece uma classe e várias funções convenientes. As funções são a interface normal para este módulo, mas algumas aplicações também podem estar interessadas na classe.

As funções descritas abaixo fornecem a interface principal para este módulo. Se o módulo não foi inicializado, eles chamarão init() se confiarem nas informações configuradas por init().

mimetypes.guess_type(url, strict=True)

Adivinha o tipo de arquivo com base em seu nome de arquivo, caminho ou URL, fornecido por url. A URL pode ser uma string ou um objeto caminho ou similar.

O valor de retorno é uma tupla (type, encoding) onde o tipo é None se o tipo não puder ser ser adivinhado (sufixo ausente ou desconhecido) ou uma string no formato 'type/subtype', utilizável para um cabeçalho MIME content-type.

encoding é None para nenhuma codificação ou o nome do programa usado para codificar (por exemplo compress ou gzip). A codificação é adequada para uso como cabeçalho Content-Encoding , não como cabeçalho Content-Transfer-Encoding. Os mapeamentos são orientados por tabela. Os sufixos de codificação diferenciam maiúsculas de minúsculas; os sufixos de tipo são testados primeiro considerando maiúsculas e minúsculas e depois sem considerar.

O argumento opcional strict é um sinalizador que especifica se a lista de tipos MIME conhecidos é limitada apenas aos tipos oficiais registrados na IANA. No entanto, o comportamento deste módulo também depende do sistema operacional subjacente. Somente tipos de arquivo reconhecidos pelo sistema operacional ou registrados explicitamente no banco de dados interno do Python podem ser identificados. Quando strict é True (o padrão), apenas os tipos IANA são suportados; quando strict é False, alguns tipos MIME adicionais não padronizados, mas geralmente usados, também são reconhecidos.

Alterado na versão 3.8: Adicionado suporte para que a url seja um objeto caminho ou similar.

Descontinuado desde a versão 3.13: Passar um caminho de arquivo em vez de URL está suavemente descontinuado. Use guess_file_type() para isso.

mimetypes.guess_file_type(path, *, strict=True)

Adivinha o tipo de um arquivo com base em seu caminho, dado por path. Semelhante à função guess_type(), mas aceita um caminho em vez de URL. O caminho pode ser uma string, um objeto bytes ou um objeto caminho ou similar.

Adicionado na versão 3.13.

mimetypes.guess_all_extensions(type, strict=True)

Adivinha as extensões para um arquivo com base em seu tipo MIME, fornecido por type. O valor de retorno é uma lista de strings que fornecem todas as extensões possíveis de nome de arquivo, incluindo o ponto ('.'). Não é garantido que as extensões tenham sido associadas a qualquer fluxo de dados específico, mas seriam mapeadas para o tipo MIME type por guess_type() e guess_file_type().

O argumento opcional strict tem o mesmo significado que usado com a função guess_type().

mimetypes.guess_extension(type, strict=True)

Adivinha a extensão para um arquivo com base em seu tipo MIME, fornecido por type. O valor de retorno é uma string que fornece uma extensão de nome de arquivo, incluindo o ponto ('.'). Não é garantido que a extensão tenha sido associada a qualquer fluxo de dados específico, mas seria mapeada para o tipo MIME type por guess_type() e guess_file_type(). Se nenhuma extensão puder ser adivinhada para type, None é retornado.

O argumento opcional strict tem o mesmo significado que usado com a função guess_type().

Algumas funções e dados adicionais estão disponíveis para controlar o comportamento do módulo.

mimetypes.init(files=None)

Inicializa as estruturas de dados internas. Se fornecido, files deverá ser uma sequência de nomes de arquivos que devem ser usados para aumentar o mapa de tipos padrão. Se for omitido, os nomes de arquivos a serem usados serão retirados de knownfiles; no Windows, as configurações atuais do registro são carregadas. Cada arquivo nomeado em files ou knownfiles tem precedência sobre os definidos anteriormente. É permitido chamar init() repetidamente.

Especificar uma lista vazia para files impedirá que os padrões do sistema sejam carregados: apenas os valores bem conhecidos estarão presentes em uma lista interna.

Se files for None, a estrutura de dados interna será completamente reconstruída com seu valor inicial padrão. Essa é uma operação estável e produzirá os mesmos resultados quando chamada várias vezes.

Alterado na versão 3.2: Anteriormente, as configurações do registro do Windows eram ignoradas.

mimetypes.read_mime_types(filename)

Load the type map given in the file filename, if it exists. The type map is returned as a dictionary mapping filename extensions, including the leading dot ('.'), to strings of the form 'type/subtype'. If the file filename does not exist or cannot be read, None is returned.

mimetypes.add_type(type, ext, strict=True)

Add a mapping from the MIME type type to the extension ext. When the extension is already known, the new type will replace the old one. When the type is already known the extension will be added to the list of known extensions.

When strict is True (the default), the mapping will be added to the official MIME types, otherwise to the non-standard ones.

mimetypes.inited

Flag indicating whether or not the global data structures have been initialized. This is set to True by init().

mimetypes.knownfiles

List of type map file names commonly installed. These files are typically named mime.types and are installed in different locations by different packages.

mimetypes.suffix_map

Dictionary mapping suffixes to suffixes. This is used to allow recognition of encoded files for which the encoding and the type are indicated by the same extension. For example, the .tgz extension is mapped to .tar.gz to allow the encoding and type to be recognized separately.

mimetypes.encodings_map

Dictionary mapping filename extensions to encoding types.

mimetypes.types_map

Dictionary mapping filename extensions to MIME types.

mimetypes.common_types

Dictionary mapping filename extensions to non-standard, but commonly found MIME types.

An example usage of the module:

>>> import mimetypes
>>> mimetypes.init()
>>> mimetypes.knownfiles
['/etc/mime.types', '/etc/httpd/mime.types', ... ]
>>> mimetypes.suffix_map['.tgz']
'.tar.gz'
>>> mimetypes.encodings_map['.gz']
'gzip'
>>> mimetypes.types_map['.tgz']
'application/x-tar-gz'

MimeTypes objects

The MimeTypes class may be useful for applications which may want more than one MIME-type database; it provides an interface similar to the one of the mimetypes module.

class mimetypes.MimeTypes(filenames=(), strict=True)

This class represents a MIME-types database. By default, it provides access to the same database as the rest of this module. The initial database is a copy of that provided by the module, and may be extended by loading additional mime.types-style files into the database using the read() or readfp() methods. The mapping dictionaries may also be cleared before loading additional data if the default data is not desired.

The optional filenames parameter can be used to cause additional files to be loaded “on top” of the default database.

suffix_map

Dictionary mapping suffixes to suffixes. This is used to allow recognition of encoded files for which the encoding and the type are indicated by the same extension. For example, the .tgz extension is mapped to .tar.gz to allow the encoding and type to be recognized separately. This is initially a copy of the global suffix_map defined in the module.

encodings_map

Dictionary mapping filename extensions to encoding types. This is initially a copy of the global encodings_map defined in the module.

types_map

Tuple containing two dictionaries, mapping filename extensions to MIME types: the first dictionary is for the non-standards types and the second one is for the standard types. They are initialized by common_types and types_map.

types_map_inv

Tuple containing two dictionaries, mapping MIME types to a list of filename extensions: the first dictionary is for the non-standards types and the second one is for the standard types. They are initialized by common_types and types_map.

guess_extension(type, strict=True)

Similar to the guess_extension() function, using the tables stored as part of the object.

guess_type(url, strict=True)

Similar to the guess_type() function, using the tables stored as part of the object.

guess_file_type(path, *, strict=True)

Similar to the guess_file_type() function, using the tables stored as part of the object.

Adicionado na versão 3.13.

guess_all_extensions(type, strict=True)

Similar to the guess_all_extensions() function, using the tables stored as part of the object.

read(filename, strict=True)

Load MIME information from a file named filename. This uses readfp() to parse the file.

If strict is True, information will be added to list of standard types, else to the list of non-standard types.

readfp(fp, strict=True)

Carrega informações do tipo MIME de um arquivo aberto fp. O arquivo precisa estar no formato padrão dos arquivos mime.types.

If strict is True, information will be added to the list of standard types, else to the list of non-standard types.

read_windows_registry(strict=True)

Carrega informações do tipo MIME a partir do registro do Windows.

Disponibilidade: Windows.

If strict is True, information will be added to the list of standard types, else to the list of non-standard types.

Adicionado na versão 3.2.

add_type(type, ext, strict=True)

Add a mapping from the MIME type type to the extension ext. Valid extensions start with a ‘.’ or are empty. When the extension is already known, the new type will replace the old one. When the type is already known the extension will be added to the list of known extensions.

When strict is True (the default), the mapping will be added to the official MIME types, otherwise to the non-standard ones.

Deprecated since version 3.14, will be removed in version 3.16: Invalid, undotted extensions will raise a ValueError in Python 3.16.

Uso na linha de comando

The mimetypes module can be executed as a script from the command line.

python -m mimetypes [-h] [-e] [-l] type [type ...]

As seguintes opções são aceitas:

-h
--help

Mostra a mensagem de ajuda e sai.

-e
--extension

Guess extension instead of type.

-l
--lenient

Additionally search for some common, but non-standard types.

By default the script converts MIME types to file extensions. However, if --extension is specified, it converts file extensions to MIME types.

For each type entry, the script writes a line into the standard output stream. If an unknown type occurs, it writes an error message into the standard error stream and exits with the return code 1.

Exemplos na linha de comando

Here are some examples of typical usage of the mimetypes command-line interface:

$ # get a MIME type by a file name
$ python -m mimetypes filename.png
type: image/png encoding: None

$ # get a MIME type by a URL
$ python -m mimetypes https://example.com/filename.txt
type: text/plain encoding: None

$ # get a complex MIME type
$ python -m mimetypes filename.tar.gz
type: application/x-tar encoding: gzip

$ # get a MIME type for a rare file extension
$ python -m mimetypes filename.pict
error: unknown extension of filename.pict

$ # now look in the extended database built into Python
$ python -m mimetypes --lenient filename.pict
type: image/pict encoding: None

$ # get a file extension by a MIME type
$ python -m mimetypes --extension text/javascript
.js

$ # get a file extension by a rare MIME type
$ python -m mimetypes --extension text/xul
error: unknown type text/xul

$ # now look in the extended database again
$ python -m mimetypes --extension --lenient text/xul
.xul

$ # try to feed an unknown file extension
$ python -m mimetypes filename.sh filename.nc filename.xxx filename.txt
type: application/x-sh encoding: None
type: application/x-netcdf encoding: None
error: unknown extension of filename.xxx

$ # try to feed an unknown MIME type
$ python -m mimetypes --extension audio/aac audio/opus audio/future audio/x-wav
.aac
.opus
error: unknown type audio/future