-
-
Save bdougherty/e1ab28b15296147f8719 to your computer and use it in GitHub Desktop.
Simple static webserver using tornado
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import os | |
import tornado.web | |
from tornado.ioloop import IOLoop | |
from tornado.options import define, options | |
# config options | |
define('port', default=8080, type=int, help='port to run web server on') | |
define('debug', default=False, help='start app in debug mode') | |
options.parse_command_line(final=True) | |
PORT = options.port | |
DEBUG = options.debug | |
settings = { | |
'debug': DEBUG, | |
'gzip': not DEBUG | |
} | |
class DirectoryHandler(tornado.web.StaticFileHandler): | |
def validate_absolute_path(self, root, absolute_path): | |
if (os.path.isdir(absolute_path)): | |
index = absolute_path + os.path.sep + 'index.html' | |
if (os.path.isfile(index)): | |
return index | |
return absolute_path | |
return super(DirectoryHandler, self).validate_absolute_path(root, absolute_path) | |
def get_content(self, abspath, start=None, end=None): | |
if (os.path.isdir(abspath)): | |
print self.request | |
html = '<html><title>Directory listing for %s</title><body><h2>Directory listing for %s</h2><hr><ul>' % (self.request.uri, self.request.uri) | |
for file in os.listdir(abspath): | |
filename = file | |
if (os.path.isdir(file)): | |
filename += '/' | |
html += '<li><a href="%s">%s</a>' % (filename, filename) | |
return html + '</ul><hr>' | |
return super(DirectoryHandler, self).get_content(abspath, start=start, end=end) | |
application = tornado.web.Application([ | |
(r'/(.*)', DirectoryHandler, {'path': './'}) | |
], **settings) | |
if __name__ == "__main__": | |
print("Listening on port %d..." % PORT) | |
application.listen(PORT) | |
IOLoop.instance().start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment