Last active
February 8, 2017 16:06
-
-
Save toast254/d75fd719f761b525f8e84664cc5fe9e0 to your computer and use it in GitHub Desktop.
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 | |
# -*- coding: utf-8 -*- | |
import logging | |
from tornado import httpserver, ioloop, netutil, process, web, options | |
# app's title | |
__title__ = 'Example' | |
options.define('port', default=8080, help='run on the given port', type=int) | |
options.define('logfile', default='./python-tornado-webserver.log', help='file to write log', type=str) | |
options.define('verbosity', default='INFO', help='log verbosity : CRITICAL, ERROR, WARNING, INFO, DEBUG', type=str) | |
options.parse_command_line(final=False) | |
logging.basicConfig(filename=options.options.logfile, level=options.options.verbosity) | |
logger = logging.getLogger(__name__) | |
def start_http(app: web.Application, http_port: int): | |
http_socket = netutil.bind_sockets(http_port) # HTTP socket | |
try: # try to create threads | |
process.fork_processes(0) # fork | |
except KeyboardInterrupt: # except KeyboardInterrupt to "properly" exit | |
ioloop.IOLoop.current().stop() | |
except AttributeError: # OS without fork() support ... | |
logging.warning('Can\' fork, continuing with only one (the main) thread ...') | |
pass # do nothing and continue without multi-threading | |
# bind http port | |
logger.info('Start an HTTP request handler on port : ' + str(http_port)) | |
httpserver.HTTPServer(app).add_sockets(http_socket) | |
try: | |
ioloop.IOLoop.current().start() # loop forever to satisfy user's requests | |
except KeyboardInterrupt: # except KeyboardInterrupt to "properly" exit | |
ioloop.IOLoop.current().stop() | |
def main(): | |
# create an app instance | |
application = web.Application([ | |
(r'/()', web.StaticFileHandler, {'path': './index.html'}), # serve 'index.html' file from current directory at root URI | |
(r'/(.*)', web.StaticFileHandler, {'path': './'}), # serve a file from current directory at defined URI | |
]) | |
start_http(application, options.options.port) # launch it in a new http server | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment