好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

django开发者模式中的autoreload是怎样实现的

在开发django应用的过程中,使用开发者模式启动服务是特别方便的一件事,只需要 python manage.py runserver 就可以运行服务,并且提供了非常人性化的autoreload机制,不需要手动重启程序就可以修改代码并看到反馈。刚接触的时候觉得这个功能比较人性化,也没觉得是什么特别高大上的技术。后来有空就想着如果是我来实现这个autoreload会怎么做,想了很久没想明白,总有些地方理不清楚,看来第一反应真是眼高手低了。于是就专门花了一些时间研究了django是怎样实现autoreload的,每一步都看源码说话,不允许有丝毫的想当然:

#django\contrib\staticfiles\management\commands\runserver.pyfrom django.core.management测试数据mands.runserver import Command as RunserverCommandclass Command(RunserverCommand):
  help = "Starts a lightweight Web server for development and also serves static files." 
#django\core\management\commands\runserver.pyclass Command(BaseCommand):
  def run(self, **options):
  """  Runs the server, using the autoreloader if needed
  """  use_reloader = options['use_reloader']

  if use_reloader:
    autoreload.main(self.inner_run, None, options)
  else:
    self.inner_run(None, **options) 
#django\utils\autoreload.py:def main(main_func, args=None, kwargs=None):
  if args is None:
    args = ()
  if kwargs is None:
    kwargs = {}
  if sys.platform.startswith('java'):
    reloader = jython_reloader
  else:
    reloader = python_reloader

  wrapped_main_func = check_errors(main_func)
  reloader(wrapped_main_func, args, kwargs) 
#django\utils\autoreload.py:def python_reloader(main_func, args, kwargs):
  if os.environ.get("RUN_MAIN") == "true":
    thread.start_new_thread(main_func, args, kwargs)
    try:
      reloader_thread()
    except KeyboardInterrupt:
      pass  else:
    try:
      exit_code = restart_with_reloader()
      if exit_code < 0:
        os.kill(os.getpid(), -exit_code)
      else:
        sys.exit(exit_code)
    except KeyboardInterrupt:
      pass 
#django\utils\autoreload.py:def restart_with_reloader():    while True:
      args = [sys.executable] + ['-W%s' % o for o in sys.warnoptions] + sys.argv
    if sys.platform == "win32":
      args = ['"%s"' % arg for arg in args]
    new_environ = os.environ.copy()
    new_environ["RUN_MAIN"] = 'true'    exit_code = os.spawnve(os.P_WAIT, sys.executable, args, new_environ)
    if exit_code != 3:
      return exit_code 
#django\utils\autoreload.py:def python_reloader(main_func, args, kwargs):
  if os.environ.get("RUN_MAIN") == "true":
    thread.start_new_thread(main_func, args, kwargs)
    try:
      reloader_thread()
    except KeyboardInterrupt:
      pass  else:
    try:
      exit_code = restart_with_reloader()
      if exit_code < 0:
        os.kill(os.getpid(), -exit_code)
      else:
        sys.exit(exit_code)
    except KeyboardInterrupt:
      pass 
[codeblock six]#django\utils\six.pyclass _SixMetaPathImporter(object):"""A meta path importer to import six.moves and its submodules.

This class implements a PEP302 finder and loader. It should be compatible
with Python 2.5 and all existing versions of Python3"""官网说明:# https://pythonhosted.org/six/Six: Python 2 and 3 Compatibility Library
Six provides simple utilities for wrapping over differences between Python 2 and Python 3. It is intended to support codebases that work on both Python 2 and 3 without modification. six consists of only one Python file, so it is painless to copy into a project. 

ensure_echo_on()其实还没看明白,貌似是针对类unix系统文件处理的,先略过;
USE_INOTIFY也是系统文件操作相关的变量,根据 inotify 是否可用选择检测文件变化的方法。
while循环,每隔1秒检测一下文件状态,如果是普通文件有变化,进程退出,退出码为3,主进程一看:退出码是3,就重启子进程。。。。这样就和上面连上了;如果不是普通文件变化,而是I18N_MODIFIED(.mo后缀的文件变化,二进制库文件之类的),那就 reset_translations ,大概意思是把已加载过的库缓存清理掉,下次重新加载。

  以上就是autoreload机制的流程。其中还是有些细节不是特别清楚,比如不同操作系统文件变化的检测,但都是很细节的东西了,不涉及主流程。看完这些,我又问了自己一遍,如果是让我设计autoreload机制会怎样搞。现在我的答案是:直接把 django\utils\autoreload.py 文件拿来用啊。其实这是很独立的一个模块,而且特别通用,完全可以作为通用的autoreload解决方案,我还自己写个毛啊。

以上就是django开发者模式中的autoreload是怎样实现的的详细内容,更多请关注Gxl网其它相关文章!

查看更多关于django开发者模式中的autoreload是怎样实现的的详细内容...

  阅读:38次