为什么django项目中的__init__模块加载了两次

时间:2010-01-21 15:45:33

标签: python django

我把

print 'Hello world!'

进入我的django项目中的__init__.py。当我现在运行./manage.py runserver时,我得到了

gruszczy@gruszczy-laptop:~/Programy/project$ ./manage.py runserver
Hello world!
Hello world!
Validating models...
0 errors found

为什么__init__.py会运行两次?它应该只加载一次。

3 个答案:

答案 0 :(得分:25)

应该只加载一次...... 每个进程。我猜测manage.py分叉,并启动了两个独立的进程。你能打印os.getpid()的结果吗?

答案 1 :(得分:0)

找出答案的一个简单方法是提出异常。也许在你的 init .py:

中就是这样的
import os
if os.path.isfile('/tmp/once.log'):
    raise Exception
open('/tmp/once.log','w').write('first time')

然后你可以检查回溯。

答案 2 :(得分:0)

从上述答案中了解了--noreload选项后,我发现两者都可以

% django-admin help runserver
% manage.py help runserver

映射到django / core / management / commands / runserver.py

中的以下代码
parser.add_argument(
    '--noreload', action='store_false', dest='use_reloader',
    help='Tells Django to NOT use the auto-reloader.',
)

django-admin.py和manage.py都调用

django.core.management.execute_from_command_line(sys.argv) 

然后,我开始跟踪Django代码,以更好地理解为什么未给出--noreload时为什么使用两个PID。

在下面,我们有

class BaseCommand defined in management/base.py and 
class Command(BaseCommand) defined in management/commands/runserver.py

    execute_from_command_line(sys.argv) ==>> utility.execute() ==>>
    self.fetch_command(subcommand).run_from_argv(self.argv) ==>>
    self.execute(*args, **cmd_options) in management/base.py ==>>
        super().execute(*args, **options) in commands/runserver.py ==>>
    output = self.handle(*args, **options) in base.py ==>>
        self.run(**options) in commands/runserver.py  ==>>
    if use_reloader:
        autoreload.run_with_reloader(self.inner_run, **options)
    else:
        self.inner_run(None, **options)  // --noreload


    ParentPID run_with_reloader() ==>> DJANGO_AUTORELOAD_ENV = None ==>> 
    restart_with_reloader() only runs the 1st time by PPID ==>>
    ==>> subprocess.call(DJANGO_AUTORELOAD_ENV = true) ==>> child process cPID
    cPID run_with_reloader() ==>> "Watching for file changes with StatReloader"
    ==>> start_django(StatReloader, Command.inner_run) ==>>
    django_main_thread = threading.Thread(target=inner_run) and
    StatReloader.run(django_main_thread)
    ==>> Performing system checks... Starting development server at
    http://127.0.0.1:8080/

    The StatReloader(BaseReloader) will check file changes once per second.
    If there is a a file write => notify_file_changed(timestamp delta) =>
    trigger_reload() and PPID will spawn a new cPID and the old cPID is gone 
    so that we don't have to restart the runserver whenever there is a code change.

使用--noreload选项,PPID直接执行inner_run()并跳过cPID子进程进行自动重新加载。如果您杀死PPID或cPID,则整个过程都会死亡。