Skip to content

Commit

Permalink
Return directory index list if we allow to show it
Browse files Browse the repository at this point in the history
Also I now return in place, instead of creating variable and returning
later, I am not a fan of returning somewehere inside a method, though if
we tried to return `ret` at the end as before, but I guess it's the most
clean pattern to do this.

This is because we have to conditional blocks, either of which can
return from the method. If first condtitonal creates `ret` variable,
later conditional may just raise `HTTPNotFound` which we do not want.
Though, I do not want to check that `ret` is populated either. Thus
return in place.

Related: aio-libs#921
  • Loading branch information
trimailov committed Jul 23, 2016
1 parent 24c5fc2 commit 6db10c5
Showing 1 changed file with 24 additions and 2 deletions.
26 changes: 24 additions & 2 deletions aiohttp/web_urldispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -497,17 +497,39 @@ def handle(self, request):
# on opening a dir, load it's contents if allowed
if filepath.is_dir():
if self._show_index:
ret = Response(text="")
return Response(text=self._dir_index_html(filepath))
else:
raise HTTPForbidden()

# on opening a file, load it's contents if they exist
if filepath.is_file():
ret = yield from self._file_sender.send(request, filepath)
return ret
else:
raise HTTPNotFound

return ret
def _dir_index_html(self, filepath):
"returns directory's index as html"
assert filepath.is_dir()
dir_index = filepath.iterdir()
index_of = "Index of {}".format(filepath.as_posix())
head = "<head><title>{}</title></head>".format(index_of)
h1 = "<h1>{}</h1>".format(index_of)

index_list = []
for i in dir_index:
# remove the beginning of posix path, so it would be relative
# to our added static url
posix_dir_len = len(self._directory.as_posix())
file_url = i.as_posix()[posix_dir_len:]
index_list.append(
'<li><a href="{url}">{url}</a></li>'.format(url=file_url)
)
ul = "<ul>{}</ul>".format(''.join(index_list))
body = "<body>{}{}</body>".format(h1, ul)

html = "<html>{}{}</html".format(head, body)
return html

def __repr__(self):
name = "'" + self.name + "' " if self.name is not None else ""
Expand Down

0 comments on commit 6db10c5

Please sign in to comment.