Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 17 additions & 7 deletions Lib/http/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -872,13 +872,13 @@ def list_directory(self, path):

"""
try:
list = os.listdir(path)
with os.scandir(path) as it:
entries = sorted(it, key=lambda e: e.name.lower())
except OSError:
self.send_error(
HTTPStatus.NOT_FOUND,
"No permission to list directory")
return None
list.sort(key=lambda a: a.lower())
r = []
displaypath = self.path
displaypath = displaypath.split('#', 1)[0]
Expand All @@ -899,14 +899,24 @@ def list_directory(self, path):
r.append(f'<title>{title}</title>\n</head>')
r.append(f'<body>\n<h1>{title}</h1>')
r.append('<hr>\n<ul>')
for name in list:
fullname = os.path.join(path, name)
for entry in entries:
name = entry.name
displayname = linkname = name
# Append / for directories or @ for symbolic links
if os.path.isdir(fullname):
# Append / for directories or @ for symbolic links. is_dir() and
# is_symlink() can raise OSError where os.path.isdir()/islink()
# return False, so fall back to False to keep the same behavior.
try:
is_dir = entry.is_dir()
except OSError:
is_dir = False
try:
is_symlink = entry.is_symlink()
except OSError:
is_symlink = False
if is_dir:
displayname = name + "/"
linkname = name + "/"
if os.path.islink(fullname):
if is_symlink:
displayname = name + "@"
# Note: a link to a directory displays with @ and links with /
r.append('<li><a href="%s">%s</a></li>'
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
:class:`http.server.SimpleHTTPRequestHandler` now uses :func:`os.scandir`
instead of :func:`os.listdir` to build directory listings, avoiding an
:func:`os.stat` call per entry. This can improve
:meth:`~http.server.SimpleHTTPRequestHandler.list_directory` performance where
``stat`` calls are slow.
Loading