70 lines
1.7 KiB
Python
70 lines
1.7 KiB
Python
|
#!/usr/bin/python3
|
||
|
|
||
|
import os
|
||
|
import signal
|
||
|
import platform
|
||
|
import asyncio
|
||
|
|
||
|
import tornado.ioloop
|
||
|
import tornado.netutil
|
||
|
import tornado.httpserver
|
||
|
|
||
|
|
||
|
def load_env(key, default):
|
||
|
if key in os.environ:
|
||
|
return os.environ[key]
|
||
|
else:
|
||
|
return default
|
||
|
|
||
|
|
||
|
signal_received = False
|
||
|
|
||
|
|
||
|
def platform_setup():
|
||
|
"""Platform-specific setup, especially for asyncio."""
|
||
|
if platform.system() == 'Windows':
|
||
|
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
|
||
|
|
||
|
|
||
|
def run_tornado_server(app, server_port=8080):
|
||
|
platform_setup()
|
||
|
|
||
|
sockets = tornado.netutil.bind_sockets(server_port, '')
|
||
|
server = tornado.httpserver.HTTPServer(app)
|
||
|
server.add_sockets(sockets)
|
||
|
|
||
|
port = None
|
||
|
|
||
|
for s in sockets:
|
||
|
print('Listening on %s, port %d' % s.getsockname()[:2])
|
||
|
if port is None:
|
||
|
port = s.getsockname()[1]
|
||
|
|
||
|
ioloop = tornado.ioloop.IOLoop.instance()
|
||
|
|
||
|
def register_signal(sig, _frame):
|
||
|
# noinspection PyGlobalUndefined
|
||
|
global signal_received
|
||
|
print("%s received, stopping server" % sig)
|
||
|
server.stop() # no more requests are accepted
|
||
|
signal_received = True
|
||
|
|
||
|
def stop_on_signal():
|
||
|
# noinspection PyGlobalUndefined
|
||
|
global signal_received
|
||
|
if signal_received:
|
||
|
ioloop.stop()
|
||
|
print("IOLoop stopped")
|
||
|
|
||
|
tornado.ioloop.PeriodicCallback(stop_on_signal, 1000).start()
|
||
|
signal.signal(signal.SIGTERM, register_signal)
|
||
|
print("Starting server")
|
||
|
|
||
|
global signal_received
|
||
|
while not signal_received:
|
||
|
try:
|
||
|
ioloop.start()
|
||
|
except KeyboardInterrupt:
|
||
|
print("Keyboard interrupt")
|
||
|
register_signal(signal.SIGTERM, None)
|