Skip to content

Instantly share code, notes, and snippets.

@courtarro
Last active Jan 20, 2016
Embed
What would you like to do?
Simple Tornado-based webserver for Python
#!/usr/bin/env python
import threading
import time
import tornado.ioloop
import tornado.web
LISTEN_PORT = 8000
class FancyStaticFileHandler(tornado.web.StaticFileHandler):
def set_default_headers(self):
# Allow other domains, prevent any caching
self.set_header("Access-Control-Allow-Origin", "*")
self.set_header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
class WebServer():
def __init__(self, port_number, www_root):
self.port_number = port_number
self.www_root = www_root
# --- Tornado Server Startup ---
self.application = tornado.web.Application([
(r"/(.*)", FancyStaticFileHandler, {"path": self.www_root, "default_filename": "index.html"}), # static
])
def stop(self):
tornado.ioloop.IOLoop.instance().add_callback(self._shutdown)
def run(self):
self.application.listen(self.port_number)
print "HTTP server listening on port " + str(self.port_number)
tornado.ioloop.IOLoop.instance().start() # blocks here
def _shutdown(self):
tornado.ioloop.IOLoop.instance().stop()
if __name__ == '__main__':
server = WebServer(LISTEN_PORT, "www")
t = threading.Thread(target=server.run)
t.start()
time.sleep(1)
while True:
try:
raw_input("Press Enter to quit.\n")
break
except KeyboardInterrupt:
pass
server.stop()
print "Shutting down..."
t.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment