Skip to content

Commit 5907e61

Browse files
aiskzooba
authored andcommitted
bpo-35292: Avoid calling mimetypes.init when http.server is imported (GH-17822)
1 parent 2e6a8ef commit 5907e61

File tree

3 files changed

+17
-16
lines changed

3 files changed

+17
-16
lines changed

Doc/library/http.server.rst

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -335,11 +335,14 @@ provides three different variants:
335335

336336
.. attribute:: extensions_map
337337

338-
A dictionary mapping suffixes into MIME types. The default is
339-
signified by an empty string, and is considered to be
340-
``application/octet-stream``. The mapping is used case-insensitively,
338+
A dictionary mapping suffixes into MIME types, contains custom overrides
339+
for the default system mappings. The mapping is used case-insensitively,
341340
and so should contain only lower-cased keys.
342341

342+
.. versionchanged:: 3.9
343+
This dictionary is no longer filled with the default system mappings,
344+
but only contains overrides.
345+
343346
.. attribute:: directory
344347

345348
If not specified, the directory to serve is the current working directory.

Lib/http/server.py

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -639,6 +639,12 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
639639
"""
640640

641641
server_version = "SimpleHTTP/" + __version__
642+
extensions_map = _encodings_map_default = {
643+
'.gz': 'application/gzip',
644+
'.Z': 'application/octet-stream',
645+
'.bz2': 'application/x-bzip2',
646+
'.xz': 'application/x-xz',
647+
}
642648

643649
def __init__(self, *args, directory=None, **kwargs):
644650
if directory is None:
@@ -866,25 +872,16 @@ def guess_type(self, path):
866872
slow) to look inside the data to make a better guess.
867873
868874
"""
869-
870875
base, ext = posixpath.splitext(path)
871876
if ext in self.extensions_map:
872877
return self.extensions_map[ext]
873878
ext = ext.lower()
874879
if ext in self.extensions_map:
875880
return self.extensions_map[ext]
876-
else:
877-
return self.extensions_map['']
878-
879-
if not mimetypes.inited:
880-
mimetypes.init() # try to read system mime.types
881-
extensions_map = mimetypes.types_map.copy()
882-
extensions_map.update({
883-
'': 'application/octet-stream', # Default
884-
'.py': 'text/plain',
885-
'.c': 'text/plain',
886-
'.h': 'text/plain',
887-
})
881+
guess, _ = mimetypes.guess_type(path)
882+
if guess:
883+
return guess
884+
return 'application/octet-stream'
888885

889886

890887
# Utilities for CGIHTTPRequestHandler
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Proxy the `SimpleHTTPRequestHandler.guess_type` to `mimetypes.guess_type` so the `mimetypes.init` is called lazily to avoid unnecessary costs when :mod:`http.server` module is imported.

0 commit comments

Comments
 (0)