Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

python - Why is run called twice in the Django dev server?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...