Skip to content

Instantly share code, notes, and snippets.

@IvanAnishchuk
Created March 8, 2017 16:54
Show Gist options
  • Save IvanAnishchuk/3559c22aba5cbd50238b139bd892862b to your computer and use it in GitHub Desktop.
Save IvanAnishchuk/3559c22aba5cbd50238b139bd892862b to your computer and use it in GitHub Desktop.
Auto-coverage runserver alternative for Django, killable by request
#!/usr/bin/env python2
# Not py3-compatible in this form
from __future__ import print_function
import signal
import sys
import thread
import coverage
from django.conf import settings
from django.core.servers.basehttp import (WSGIRequestHandler, WSGIServer,
get_internal_wsgi_application)
from django.utils.six.moves import socketserver
def signal_handler(signal, frame):
print('Signal handler.', file=sys.stderr)
raise KeyboardInterrupt
class KillableHandler(WSGIRequestHandler):
def get_environ(self):
if 'X-Exit-Immediately' in self.headers:
print("Server is going down!")
def kill_the_server(server):
server.shutdown()
thread.start_new_thread(kill_the_server, (self.server,))
return super(KillableHandler, self).get_environ()
def run(addr, port, wsgi_handler, ipv6=False, threading=False):
server_address = (addr, port)
if threading:
httpd_cls = type(str('WSGIServer'), (socketserver.ThreadingMixIn, WSGIServer), {})
else:
httpd_cls = WSGIServer
httpd = httpd_cls(server_address, KillableHandler, ipv6=ipv6)
httpd.set_app(wsgi_handler)
httpd.serve_forever()
if __name__ == '__main__':
print('Starting customized web server.', file=sys.stderr)
signal.signal(signal.SIGABRT, signal_handler)
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
cov = coverage.Coverage(
data_suffix='web',
config_file='setup.cfg',
)
cov.start()
try:
settings.WSGI_APPLICATION = 'aim.wsgi_vanilla.application'
handler = get_internal_wsgi_application()
print('Started.', file=sys.stderr)
run('0.0.0.0', 8001, handler, ipv6=False, threading=True)
except KeyboardInterrupt:
print('Signal caught. Exiting.', file=sys.stderr)
finally:
cov.stop()
cov.save()
cov.xml_report(outfile="reports/coverage-web.xml", include="src/*")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment