Skip to content

Instantly share code, notes, and snippets.

@glowinthedark
Created July 6, 2019 22:57
Show Gist options
  • Select an option

  • Save glowinthedark/b2c255c7548f2ac4312851b760fd1ab7 to your computer and use it in GitHub Desktop.

Select an option

Save glowinthedark/b2c255c7548f2ac4312851b760fd1ab7 to your computer and use it in GitHub Desktop.
Python Bottle file server with directory index
#!/usr/bin/env python3
import os
import sys
import bottle
from bottle import run, static_file
def resolve_path(path):
if (sys.platform == 'win32'):
return "\\" + path.replace('/', '\\')
return path
app = bottle.Bottle()
serve_path = (len(sys.argv) > 1) and sys.argv[1] or os.getcwd()
HTML_HEADER = '''<html>
<head>
<title></title>
<style>
ul { padding: 0; list-style: none}
li {
list-style: none;
padding: 0 .1em .1em .7em;
margin: 0;
}
a:link {
color: #808080;
text-decoration: none;
}
/* visited link */
a:visited {
color: #808080;
text-decoration: none;
}
/* mouse over link */
a:hover {
color: #ff7d12;
}
/* selected link */
a:active {
color: #ff7d12;
}
.odd { background-color: white}
.even { background-color: #f8f8f8}
</style>
</head>
<body><a href="..">..</a><br>
<ul>'''
class FileServer:
def __init__(self, hostname='0.0.0.0', port=8088):
run(app, host=hostname, port=port)
@app.route('/<filename:re:.*>')
def serve(filename):
alt = False # for alternate row color
path = os.path.join(serve_path, resolve_path(filename))
html = HTML_HEADER
if os.path.isfile(path):
return static_file(resolve_path(filename), root=serve_path) # serve a file
else:
try:
for fname in sorted(os.listdir(path), key=lambda p: (not os.path.isdir(os.path.join(path, p)), p.casefold())):
scheme = bottle.request.urlparts.scheme
host = bottle.request.urlparts.netloc
css_class = alt and "odd" or "even"
alt = not alt
web_path = os.path.join(filename, fname)
abs_path = os.path.join(serve_path, filename, fname)
is_dir = os.path.isdir(abs_path)
icon = is_dir and '&#128193;' or '&#x1F4C3;'
html = html + f'<li class="{css_class}"><a href="{scheme}://{host}/{web_path}">{icon}&nbsp;{fname}</a></li>'
except Exception as e:
html = "Server Error:" + str(e)
return html + """
</ul>
</body>
</html>
"""
if __name__ == '__main__':
FileServer()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment