Package madrona :: Package common :: Package management :: Package commands :: Module runprofileserver
[hide private]

Source Code for Module madrona.common.management.commands.runprofileserver

  1  from django.core.management.base import BaseCommand, CommandError 
  2  from optparse import make_option 
  3  import os 
  4  import sys 
  5   
6 -class Command(BaseCommand):
7 option_list = BaseCommand.option_list + ( 8 make_option('--noreload', action='store_false', dest='use_reloader', default=True, 9 help='Tells Django to NOT use the auto-reloader.'), 10 make_option('--adminmedia', dest='admin_media_path', default='', 11 help='Specifies the directory from which to serve admin media.'), 12 ) 13 help = "Starts a lightweight Web server for development." 14 args = '[optional port number, or ipaddr:port]' 15 16 # Validation is called explicitly each time the server is reloaded. 17 requires_model_validation = False 18
19 - def handle(self, addrport='', *args, **options):
20 import django 21 from django.core.servers.basehttp import run, AdminMediaHandler, WSGIServerException 22 from django.core.handlers.wsgi import WSGIHandler 23 if args: 24 raise CommandError('Usage is runserver %s' % self.args) 25 if not addrport: 26 addr = '' 27 port = '8000' 28 else: 29 try: 30 addr, port = addrport.split(':') 31 except ValueError: 32 addr, port = '', addrport 33 if not addr: 34 addr = '127.0.0.1' 35 36 if not port.isdigit(): 37 raise CommandError("%r is not a valid port number." % port) 38 39 use_reloader = options.get('use_reloader', True) 40 admin_media_path = options.get('admin_media_path', '') 41 shutdown_message = options.get('shutdown_message', '') 42 quit_command = (sys.platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C' 43 44 def inner_run(): 45 from django.conf import settings 46 from django.utils import translation 47 print "Validating models..." 48 self.validate(display_num_errors=True) 49 print "\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE) 50 print "Development server is running at http://%s:%s/" % (addr, port) 51 print "Quit the server with %s." % quit_command 52 53 # django.core.management.base forces the locale to en-us. We should 54 # set it up correctly for the first request (particularly important 55 # in the "--noreload" case). 56 translation.activate(settings.LANGUAGE_CODE) 57 58 try: 59 # BEGIN profiling 60 import cProfile 61 import pstats 62 import time 63 import tempfile 64 65 profile_temp_dir = None 66 if profile_temp_dir is not None: 67 tempfile.tempdir = profile_temp_dir 68 69 def make_profiler_handler(inner_handler): 70 def handler(environ, start_response): 71 print "============= Starting response ====================" 72 path = environ['PATH_INFO'] 73 if path.startswith(settings.MEDIA_URL): 74 return inner_handler(environ, start_response) 75 path = path.strip('/').replace('/', '.') 76 if path: 77 prefix = 'p.%s.%3f' % (path, time.time()) 78 else: 79 prefix = 'p.%3f' % time.time() 80 fd, profname = tempfile.mkstemp('.prof', prefix) 81 os.close(fd) 82 prof = cProfile.Profile() 83 try: 84 return prof.runcall(inner_handler, environ, start_response) 85 finally: 86 prof.dump_stats(profname) 87 stats = pstats.Stats(profname) 88 stats.sort_stats('cumulative', 'time', 'calls') 89 stats.print_stats('madrona',20) 90 print " * Complete cProfile output at %s" % profname 91 print "============= Done ================================="
92 93 return handler
94 95 # END 96 #handler = AdminMediaHandler(WSGIHandler(), admin_media_path) 97 handler = make_profiler_handler(AdminMediaHandler(WSGIHandler(), admin_media_path)) 98 run(addr, int(port), handler) 99 except WSGIServerException, e: 100 # Use helpful error messages instead of ugly tracebacks. 101 ERRORS = { 102 13: "You don't have permission to access that port.", 103 98: "That port is already in use.", 104 99: "That IP address can't be assigned-to.", 105 } 106 try: 107 error_text = ERRORS[e.args[0].args[0]] 108 except (AttributeError, KeyError): 109 error_text = str(e) 110 sys.stderr.write(self.style.ERROR("Error: %s" % error_text) + '\n') 111 # Need to use an OS exit because sys.exit doesn't work in a thread 112 os._exit(1) 113 except KeyboardInterrupt: 114 if shutdown_message: 115 print shutdown_message 116 sys.exit(0) 117 118 if use_reloader: 119 from django.utils import autoreload 120 autoreload.main(inner_run) 121 else: 122 inner_run() 123