MCPcopy Create free account
hub / github.com/python/cpython / guess_type

Method guess_type

Lib/mimetypes.py:112–166  ·  view source on GitHub ↗

Guess the type of a file which is either a URL or a path-like object. Return value is a tuple (type, encoding) where type is None if the type can't be guessed (no or unknown suffix) or a string of the form type/subtype, usable for a MIME Content-type header; and enco

(self, url, strict=True)

Source from the content-addressed store, hash-verified

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
117 of the form type/subtype, usable for a MIME Content-type
118 header; and encoding is None for no encoding or the name of
119 the program used to encode (e.g. compress or gzip). The
120 mappings are table driven. Encoding suffixes are case
121 sensitive; type suffixes are first tried case sensitive, then
122 case insensitive.
123
124 The suffixes .tgz, .taz and .tz (case sensitive!) are all
125 mapped to '.tar.gz'. (This is table-driven too, using the
126 dictionary suffix_map.)
127
128 Optional 'strict' argument when False adds a bunch of commonly found,
129 but non-standard types.
130 """
131 # Lazy import to improve module import time
132 import os
133 import urllib.parse
134
135 # TODO: Deprecate accepting file paths (in particular path-like objects).
136 url = os.fspath(url)
137 p = urllib.parse.urlparse(url)
138 if p.scheme and len(p.scheme) > 1:
139 scheme = p.scheme
140 url = p.path
141 else:
142 return self.guess_file_type(url, strict=strict)
143 if scheme == 'data':
144 # syntax of data URLs:
145 # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
146 # mediatype := [ type "/" subtype ] *( ";" parameter )
147 # data := *urlchar
148 # parameter := attribute "=" value
149 # type/subtype defaults to "text/plain"
150 comma = url.find(',')
151 if comma < 0:
152 # bad data URL
153 return None, None
154 semi = url.find(';', 0, comma)
155 if semi >= 0:
156 type = url[:semi]
157 else:
158 type = url[:comma]
159 if '=' in type or '/' not in type:
160 type = 'text/plain'
161 return type, None # never compressed, so encoding is None
162
163 # Lazy import to improve module import time
164 import posixpath
165
166 return self._guess_file_type(url, strict, posixpath.splitext)
167
168 def guess_file_type(self, path, *, strict=True):
169 """Guess the type of a file based on its path.

Callers 1

guess_typeFunction · 0.45

Calls 3

guess_file_typeMethod · 0.95
_guess_file_typeMethod · 0.95
findMethod · 0.45

Tested by

no test coverage detected