2005-07-21 12:08:54 +08:00
|
|
|
# Autoreloading launcher.
|
|
|
|
# Borrowed from Peter Hunt and the CherryPy project (http://www.cherrypy.org).
|
|
|
|
# Some taken from Ian Bicking's Paste (http://pythonpaste.org/).
|
2005-07-21 12:10:47 +08:00
|
|
|
#
|
|
|
|
# Portions copyright (c) 2004, CherryPy Team (team@cherrypy.org)
|
|
|
|
# All rights reserved.
|
|
|
|
#
|
|
|
|
# Redistribution and use in source and binary forms, with or without modification,
|
|
|
|
# are permitted provided that the following conditions are met:
|
|
|
|
#
|
|
|
|
# * Redistributions of source code must retain the above copyright notice,
|
|
|
|
# this list of conditions and the following disclaimer.
|
|
|
|
# * Redistributions in binary form must reproduce the above copyright notice,
|
|
|
|
# this list of conditions and the following disclaimer in the documentation
|
|
|
|
# and/or other materials provided with the distribution.
|
|
|
|
# * Neither the name of the CherryPy Team nor the names of its contributors
|
|
|
|
# may be used to endorse or promote products derived from this software
|
|
|
|
# without specific prior written permission.
|
|
|
|
#
|
|
|
|
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
|
|
|
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
|
|
|
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
|
|
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
|
|
|
|
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
|
|
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
|
|
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
|
|
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
|
|
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
|
|
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
2005-07-21 12:08:54 +08:00
|
|
|
|
2013-10-11 19:25:14 +08:00
|
|
|
import os
|
|
|
|
import signal
|
2016-12-28 21:04:09 +08:00
|
|
|
import subprocess
|
2013-10-11 19:25:14 +08:00
|
|
|
import sys
|
|
|
|
import time
|
|
|
|
import traceback
|
2006-05-31 22:53:23 +08:00
|
|
|
|
2017-01-07 19:11:46 +08:00
|
|
|
import _thread
|
|
|
|
|
2013-12-24 19:25:17 +08:00
|
|
|
from django.apps import apps
|
2013-11-02 17:28:22 +08:00
|
|
|
from django.conf import settings
|
2013-10-14 13:33:45 +08:00
|
|
|
from django.core.signals import request_finished
|
2005-07-21 12:08:54 +08:00
|
|
|
|
2006-07-29 06:13:34 +08:00
|
|
|
# This import does nothing, but it's necessary to avoid some race conditions
|
|
|
|
# in the threading module. See http://code.djangoproject.com/ticket/2330 .
|
2017-09-07 20:16:21 +08:00
|
|
|
try:
|
2013-10-18 19:25:30 +08:00
|
|
|
import threading # NOQA
|
2017-09-07 20:16:21 +08:00
|
|
|
except ImportError:
|
|
|
|
pass
|
2006-07-29 06:13:34 +08:00
|
|
|
|
2011-03-20 06:09:38 +08:00
|
|
|
try:
|
|
|
|
import termios
|
|
|
|
except ImportError:
|
|
|
|
termios = None
|
2006-07-29 06:13:34 +08:00
|
|
|
|
2013-10-14 13:33:45 +08:00
|
|
|
USE_INOTIFY = False
|
2017-09-07 20:16:21 +08:00
|
|
|
try:
|
2013-10-14 13:33:45 +08:00
|
|
|
# Test whether inotify is enabled and likely to work
|
|
|
|
import pyinotify
|
|
|
|
|
|
|
|
fd = pyinotify.INotifyWrapper.create().inotify_init()
|
|
|
|
if fd >= 0:
|
|
|
|
USE_INOTIFY = True
|
|
|
|
os.close(fd)
|
2017-09-07 20:16:21 +08:00
|
|
|
except ImportError:
|
|
|
|
pass
|
2013-10-14 13:33:45 +08:00
|
|
|
|
2005-07-21 12:08:54 +08:00
|
|
|
RUN_RELOADER = True
|
|
|
|
|
2014-06-21 17:40:36 +08:00
|
|
|
FILE_MODIFIED = 1
|
|
|
|
I18N_MODIFIED = 2
|
|
|
|
|
2008-08-09 01:54:35 +08:00
|
|
|
_mtimes = {}
|
|
|
|
_win = (sys.platform == "win32")
|
|
|
|
|
2015-08-05 17:07:36 +08:00
|
|
|
_exception = None
|
2012-12-12 11:33:03 +08:00
|
|
|
_error_files = []
|
2014-07-05 20:43:12 +08:00
|
|
|
_cached_modules = set()
|
|
|
|
_cached_filenames = []
|
2012-12-12 11:33:03 +08:00
|
|
|
|
2014-07-08 07:12:39 +08:00
|
|
|
|
2014-07-05 20:43:12 +08:00
|
|
|
def gen_filenames(only_new=False):
|
2013-10-14 13:33:45 +08:00
|
|
|
"""
|
2017-01-25 04:32:33 +08:00
|
|
|
Return a list of filenames referenced in sys.modules and translation files.
|
2013-10-14 13:33:45 +08:00
|
|
|
"""
|
2014-04-03 00:47:18 +08:00
|
|
|
# N.B. ``list(...)`` is needed, because this runs in parallel with
|
|
|
|
# application code which might be mutating ``sys.modules``, and this will
|
|
|
|
# fail with RuntimeError: cannot mutate dictionary while iterating
|
2014-07-05 20:43:12 +08:00
|
|
|
global _cached_modules, _cached_filenames
|
|
|
|
module_values = set(sys.modules.values())
|
2014-07-25 21:32:14 +08:00
|
|
|
_cached_filenames = clean_files(_cached_filenames)
|
2014-07-05 20:43:12 +08:00
|
|
|
if _cached_modules == module_values:
|
|
|
|
# No changes in module list, short-circuit the function
|
|
|
|
if only_new:
|
|
|
|
return []
|
|
|
|
else:
|
2015-08-05 17:06:26 +08:00
|
|
|
return _cached_filenames + clean_files(_error_files)
|
2014-07-05 20:43:12 +08:00
|
|
|
|
|
|
|
new_modules = module_values - _cached_modules
|
2014-07-15 03:40:55 +08:00
|
|
|
new_filenames = clean_files(
|
|
|
|
[filename.__file__ for filename in new_modules
|
|
|
|
if hasattr(filename, '__file__')])
|
2014-07-05 20:43:12 +08:00
|
|
|
|
|
|
|
if not _cached_filenames and settings.USE_I18N:
|
2013-11-05 21:30:31 +08:00
|
|
|
# Add the names of the .mo files that can be generated
|
|
|
|
# by compilemessages management command to the list of files watched.
|
|
|
|
basedirs = [os.path.join(os.path.dirname(os.path.dirname(__file__)),
|
|
|
|
'conf', 'locale'),
|
|
|
|
'locale']
|
2013-12-24 19:25:17 +08:00
|
|
|
for app_config in reversed(list(apps.get_app_configs())):
|
2017-01-20 21:01:02 +08:00
|
|
|
basedirs.append(os.path.join(app_config.path, 'locale'))
|
2013-11-05 21:30:31 +08:00
|
|
|
basedirs.extend(settings.LOCALE_PATHS)
|
|
|
|
basedirs = [os.path.abspath(basedir) for basedir in basedirs
|
|
|
|
if os.path.isdir(basedir)]
|
|
|
|
for basedir in basedirs:
|
|
|
|
for dirpath, dirnames, locale_filenames in os.walk(basedir):
|
|
|
|
for filename in locale_filenames:
|
|
|
|
if filename.endswith('.mo'):
|
2014-07-05 20:43:12 +08:00
|
|
|
new_filenames.append(os.path.join(dirpath, filename))
|
|
|
|
|
2014-07-15 03:40:55 +08:00
|
|
|
_cached_modules = _cached_modules.union(new_modules)
|
|
|
|
_cached_filenames += new_filenames
|
2014-07-05 20:43:12 +08:00
|
|
|
if only_new:
|
2015-08-05 17:06:26 +08:00
|
|
|
return new_filenames + clean_files(_error_files)
|
2014-07-05 20:43:12 +08:00
|
|
|
else:
|
2014-07-15 03:40:55 +08:00
|
|
|
return _cached_filenames + clean_files(_error_files)
|
|
|
|
|
|
|
|
|
|
|
|
def clean_files(filelist):
|
2014-07-05 20:43:12 +08:00
|
|
|
filenames = []
|
|
|
|
for filename in filelist:
|
2012-12-26 09:37:39 +08:00
|
|
|
if not filename:
|
|
|
|
continue
|
2008-08-09 01:54:35 +08:00
|
|
|
if filename.endswith(".pyc") or filename.endswith(".pyo"):
|
|
|
|
filename = filename[:-1]
|
2011-08-15 16:29:08 +08:00
|
|
|
if filename.endswith("$py.class"):
|
|
|
|
filename = filename[:-9] + ".py"
|
2013-10-14 13:33:45 +08:00
|
|
|
if os.path.exists(filename):
|
2014-07-05 20:43:12 +08:00
|
|
|
filenames.append(filename)
|
|
|
|
return filenames
|
2013-10-14 13:33:45 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2014-06-21 17:40:36 +08:00
|
|
|
def reset_translations():
|
|
|
|
import gettext
|
|
|
|
from django.utils.translation import trans_real
|
|
|
|
gettext._translations = {}
|
|
|
|
trans_real._translations = {}
|
|
|
|
trans_real._default = None
|
|
|
|
trans_real._active = threading.local()
|
|
|
|
|
|
|
|
|
2013-10-14 13:33:45 +08:00
|
|
|
def inotify_code_changed():
|
|
|
|
"""
|
2017-01-25 04:32:33 +08:00
|
|
|
Check for changed code using inotify. After being called
|
2013-10-14 13:33:45 +08:00
|
|
|
it blocks until a change event has been fired.
|
|
|
|
"""
|
2014-06-21 17:40:36 +08:00
|
|
|
class EventHandler(pyinotify.ProcessEvent):
|
|
|
|
modified_code = None
|
2014-06-27 03:16:23 +08:00
|
|
|
|
2014-06-21 17:40:36 +08:00
|
|
|
def process_default(self, event):
|
|
|
|
if event.path.endswith('.mo'):
|
|
|
|
EventHandler.modified_code = I18N_MODIFIED
|
|
|
|
else:
|
|
|
|
EventHandler.modified_code = FILE_MODIFIED
|
|
|
|
|
2013-10-14 13:33:45 +08:00
|
|
|
wm = pyinotify.WatchManager()
|
2014-06-21 17:40:36 +08:00
|
|
|
notifier = pyinotify.Notifier(wm, EventHandler())
|
2013-10-14 13:33:45 +08:00
|
|
|
|
|
|
|
def update_watch(sender=None, **kwargs):
|
2014-07-05 20:43:12 +08:00
|
|
|
if sender and getattr(sender, 'handles_files', False):
|
|
|
|
# No need to update watches when request serves files.
|
|
|
|
# (sender is supposed to be a django.core.handlers.BaseHandler subclass)
|
|
|
|
return
|
2013-10-14 13:33:45 +08:00
|
|
|
mask = (
|
|
|
|
pyinotify.IN_MODIFY |
|
|
|
|
pyinotify.IN_DELETE |
|
|
|
|
pyinotify.IN_ATTRIB |
|
|
|
|
pyinotify.IN_MOVED_FROM |
|
|
|
|
pyinotify.IN_MOVED_TO |
|
2015-05-29 23:32:57 +08:00
|
|
|
pyinotify.IN_CREATE |
|
|
|
|
pyinotify.IN_DELETE_SELF |
|
|
|
|
pyinotify.IN_MOVE_SELF
|
2013-10-14 13:33:45 +08:00
|
|
|
)
|
2014-07-05 20:43:12 +08:00
|
|
|
for path in gen_filenames(only_new=True):
|
2013-10-14 13:33:45 +08:00
|
|
|
wm.add_watch(path, mask)
|
|
|
|
|
2013-11-05 04:55:52 +08:00
|
|
|
# New modules may get imported when a request is processed.
|
2013-10-14 13:33:45 +08:00
|
|
|
request_finished.connect(update_watch)
|
|
|
|
|
2013-11-05 04:55:52 +08:00
|
|
|
# Block until an event happens.
|
|
|
|
update_watch()
|
2013-10-14 13:33:45 +08:00
|
|
|
notifier.check_events(timeout=None)
|
2014-06-21 17:40:36 +08:00
|
|
|
notifier.read_events()
|
|
|
|
notifier.process_events()
|
2013-10-14 13:33:45 +08:00
|
|
|
notifier.stop()
|
|
|
|
|
|
|
|
# If we are here the code must have changed.
|
2014-06-21 17:40:36 +08:00
|
|
|
return EventHandler.modified_code
|
2013-10-14 13:33:45 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2013-10-14 13:33:45 +08:00
|
|
|
def code_changed():
|
|
|
|
global _mtimes, _win
|
|
|
|
for filename in gen_filenames():
|
2008-08-09 01:54:35 +08:00
|
|
|
stat = os.stat(filename)
|
|
|
|
mtime = stat.st_mtime
|
|
|
|
if _win:
|
|
|
|
mtime -= stat.st_ctime
|
|
|
|
if filename not in _mtimes:
|
|
|
|
_mtimes[filename] = mtime
|
|
|
|
continue
|
|
|
|
if mtime != _mtimes[filename]:
|
|
|
|
_mtimes = {}
|
2017-09-07 20:16:21 +08:00
|
|
|
try:
|
2012-12-12 11:33:03 +08:00
|
|
|
del _error_files[_error_files.index(filename)]
|
2017-09-07 20:16:21 +08:00
|
|
|
except ValueError:
|
|
|
|
pass
|
2014-06-21 17:40:36 +08:00
|
|
|
return I18N_MODIFIED if filename.endswith('.mo') else FILE_MODIFIED
|
2008-08-09 01:54:35 +08:00
|
|
|
return False
|
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2012-12-12 11:33:03 +08:00
|
|
|
def check_errors(fn):
|
|
|
|
def wrapper(*args, **kwargs):
|
2015-08-05 17:07:36 +08:00
|
|
|
global _exception
|
2012-12-12 11:33:03 +08:00
|
|
|
try:
|
|
|
|
fn(*args, **kwargs)
|
2015-08-29 19:26:00 +08:00
|
|
|
except Exception:
|
2015-08-05 17:07:36 +08:00
|
|
|
_exception = sys.exc_info()
|
|
|
|
|
|
|
|
et, ev, tb = _exception
|
2012-12-12 11:33:03 +08:00
|
|
|
|
|
|
|
if getattr(ev, 'filename', None) is None:
|
|
|
|
# get the filename from the last item in the stack
|
|
|
|
filename = traceback.extract_tb(tb)[-1][0]
|
|
|
|
else:
|
|
|
|
filename = ev.filename
|
|
|
|
|
|
|
|
if filename not in _error_files:
|
|
|
|
_error_files.append(filename)
|
|
|
|
|
|
|
|
raise
|
|
|
|
|
|
|
|
return wrapper
|
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2015-08-05 17:07:36 +08:00
|
|
|
def raise_last_exception():
|
|
|
|
global _exception
|
|
|
|
if _exception is not None:
|
2017-11-24 00:18:03 +08:00
|
|
|
raise _exception[1]
|
2015-08-05 17:07:36 +08:00
|
|
|
|
|
|
|
|
2011-03-20 06:09:38 +08:00
|
|
|
def ensure_echo_on():
|
|
|
|
if termios:
|
2011-03-24 20:36:33 +08:00
|
|
|
fd = sys.stdin
|
|
|
|
if fd.isatty():
|
|
|
|
attr_list = termios.tcgetattr(fd)
|
|
|
|
if not attr_list[3] & termios.ECHO:
|
|
|
|
attr_list[3] |= termios.ECHO
|
2011-06-04 23:29:11 +08:00
|
|
|
if hasattr(signal, 'SIGTTOU'):
|
|
|
|
old_handler = signal.signal(signal.SIGTTOU, signal.SIG_IGN)
|
|
|
|
else:
|
|
|
|
old_handler = None
|
2011-03-24 20:36:33 +08:00
|
|
|
termios.tcsetattr(fd, termios.TCSANOW, attr_list)
|
2011-06-04 23:29:11 +08:00
|
|
|
if old_handler is not None:
|
|
|
|
signal.signal(signal.SIGTTOU, old_handler)
|
2011-03-20 06:09:38 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2005-07-21 12:08:54 +08:00
|
|
|
def reloader_thread():
|
2011-03-20 06:09:38 +08:00
|
|
|
ensure_echo_on()
|
2013-10-14 13:33:45 +08:00
|
|
|
if USE_INOTIFY:
|
|
|
|
fn = inotify_code_changed
|
|
|
|
else:
|
|
|
|
fn = code_changed
|
2005-07-21 12:08:54 +08:00
|
|
|
while RUN_RELOADER:
|
2014-06-21 17:40:36 +08:00
|
|
|
change = fn()
|
|
|
|
if change == FILE_MODIFIED:
|
2013-11-03 03:27:47 +08:00
|
|
|
sys.exit(3) # force reload
|
2014-06-21 17:40:36 +08:00
|
|
|
elif change == I18N_MODIFIED:
|
|
|
|
reset_translations()
|
2005-07-21 12:08:54 +08:00
|
|
|
time.sleep(1)
|
|
|
|
|
2013-10-14 13:33:45 +08:00
|
|
|
|
2005-07-21 12:08:54 +08:00
|
|
|
def restart_with_reloader():
|
2017-10-25 15:29:05 +08:00
|
|
|
import django.__main__
|
2005-07-21 12:08:54 +08:00
|
|
|
while True:
|
2017-10-25 15:29:05 +08:00
|
|
|
args = [sys.executable] + ['-W%s' % o for o in sys.warnoptions]
|
|
|
|
if sys.argv[0] == django.__main__.__file__:
|
|
|
|
# The server was started with `python -m django runserver`.
|
|
|
|
args += ['-m', 'django']
|
|
|
|
args += sys.argv[1:]
|
|
|
|
else:
|
|
|
|
args += sys.argv
|
2018-02-27 01:23:31 +08:00
|
|
|
new_environ = {**os.environ, 'RUN_MAIN': 'true'}
|
2016-12-28 21:04:09 +08:00
|
|
|
exit_code = subprocess.call(args, env=new_environ)
|
2005-07-21 12:08:54 +08:00
|
|
|
if exit_code != 3:
|
|
|
|
return exit_code
|
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2008-08-09 01:54:35 +08:00
|
|
|
def python_reloader(main_func, args, kwargs):
|
2005-07-21 12:08:54 +08:00
|
|
|
if os.environ.get("RUN_MAIN") == "true":
|
2017-01-07 19:11:46 +08:00
|
|
|
_thread.start_new_thread(main_func, args, kwargs)
|
2017-09-07 20:16:21 +08:00
|
|
|
try:
|
2005-07-21 12:08:54 +08:00
|
|
|
reloader_thread()
|
2017-09-07 20:16:21 +08:00
|
|
|
except KeyboardInterrupt:
|
|
|
|
pass
|
2005-07-21 12:08:54 +08:00
|
|
|
else:
|
2017-09-07 20:16:21 +08:00
|
|
|
try:
|
2011-12-30 22:12:31 +08:00
|
|
|
exit_code = restart_with_reloader()
|
|
|
|
if exit_code < 0:
|
|
|
|
os.kill(os.getpid(), -exit_code)
|
|
|
|
else:
|
|
|
|
sys.exit(exit_code)
|
2017-09-07 20:16:21 +08:00
|
|
|
except KeyboardInterrupt:
|
|
|
|
pass
|
2008-08-09 01:54:35 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2008-08-09 01:54:35 +08:00
|
|
|
def main(main_func, args=None, kwargs=None):
|
|
|
|
if args is None:
|
|
|
|
args = ()
|
|
|
|
if kwargs is None:
|
|
|
|
kwargs = {}
|
2012-12-12 11:33:03 +08:00
|
|
|
|
|
|
|
wrapped_main_func = check_errors(main_func)
|
2017-12-21 23:31:59 +08:00
|
|
|
python_reloader(wrapped_main_func, args, kwargs)
|