为什么在Django dev服务器中运行两次? [英] Why is run called twice in the Django dev server?

查看:184
本文介绍了为什么在Django dev服务器中运行两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让Django开发服务器在开始运行之前做了一些事情。为此,我创建了一个新的应用程序,将其添加到 INSTALLED_APPS 的顶部,然后创建了一个 management / commands / runserver.py 文件在应用程序与以下代码:

 从django.contrib.staticfiles.management.commands.runserver导入命令作为RunserverCommand 
类命令(RunserverCommand):
def run(self,* args,** options):
self.stdout.write('关于开始运行'+ self .addr)
super(Command,self).run(* args,** options)

(我实际上想做的事情比写一行stdout更复杂,当然,这是演示问题的最简单的例子,我覆盖的原因是运行而不是 handle 或其他方法,是因为我需要 self.addr 代码运行。)



当我运行 ./ manage.py runserver ,行即将开始运行1 27.0.0.1不出现一次,但在服务器开始运行两次之前。为什么会发生这种情况,可以做些什么?

解决方案

自动重新加载程序的过程证明是罪魁祸首结果是autoreload进程获得相同的参数,并且通过与原始文件相同的初始化过程。解决方案是只有在没有运行在autoreloader产生的进程中才能执行服务器前代码,这可以通过环境变量来检测:

 从django.contrib.staticfiles.management.commands.runserver导入os 
导入命令作为RunserverCommand
类命令(RunserverCommand):
def run(self,* args ,** options):
如果os.environ.get('RUN_MAIN')!='true':
self.stdout.write('关于开始运行'+ self.addr)
super(Command,self).run(* args,** options)


I want to make the Django development server do something before it starts running. To do this, I created a new app, added it to the top of INSTALLED_APPS, and then created a management/commands/runserver.py file in the app with the following code:

from django.contrib.staticfiles.management.commands.runserver import Command as RunserverCommand
class Command(RunserverCommand):
    def run(self, *args, **options):
        self.stdout.write('About to start running on ' + self.addr)
        super(Command, self).run(*args, **options)

(The thing I actually want to do is more complicated than writing one line to stdout, of course, but this is the simplest example that demonstrates the problem. The reason I override run, rather than handle or some other method, is because I need self.addr to already be set when this code runs.)

When I run ./manage.py runserver, the line "About to start running on 127.0.0.1" appears not once, but twice before the server starts running. Why is this happening and what can be done about it?

解决方案

The auto-reloader process turned out to be the culprit; turns out the autoreload process gets the same arguments, and goes through the same initialization process, as the original. The solution was to have the pre-server code execute only if it's not running in the process spawned by the autoreloader, which can be detected through an environment variable:

import os
from django.contrib.staticfiles.management.commands.runserver import Command as RunserverCommand
class Command(RunserverCommand):
    def run(self, *args, **options):
        if os.environ.get('RUN_MAIN') != 'true':
            self.stdout.write('About to start running on ' + self.addr)
        super(Command, self).run(*args, **options)

这篇关于为什么在Django dev服务器中运行两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆