Last active
January 20, 2016 06:42
-
-
Save courtarro/c1c8d083a8b2468d1812 to your computer and use it in GitHub Desktop.
Simple Tornado-based webserver for Python
This file contains 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 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