How can I tell whether my Django application is running on development server or not?

后端 未结 13 1605
别跟我提以往
别跟我提以往 2020-12-05 03:37

How can I be certain that my application is running on development server or not? I suppose I could check value of settings.DEBUG and assume if DEBUG

13条回答
  •  臣服心动
    2020-12-05 04:34

    I came across this problem just now, and ended up writing a solution similar to Aryeh Leib Taurog's. My main difference is that I want to differentiate between a production and dev environments when running the server, but also when running some one-off scripts for my app (which I run like DJANGO_SETTINGS_MODULE=settings python [the script] ). In this case, simply looking at whether argv[1] == runserver isn't enough. So what I came up with is to pass an extra command-line argument when I run the devserver, and also when I run my scripts, and just look for that argument in settings.py. So the code looks like this:

    if '--in-development' in sys.argv:
        ## YES! we're in dev
        pass
    else:
        ## Nope, this is prod
        pass
    

    then, running the django server becomes

    python manage.py runserver [whatever options you want] --in-development

    and running my scripts is as easy as

    DJANGO_SETTINGS_MODULE=settings python [myscript] --in-development

    Just make sure the extra argument you pass along doens't conflict with anything django (in reality I use my app's name as part of the argument). I think this is pretty decent, as it lets me control exactly when my server and scripts will behave as prod or dev, and I'm not relying on anyone else's conventions, other than my own.

    EDIT: manage.py complains if you pass unrecognized options, so you need to change the code in settings.py to be something like

    if sys.argv[0] == 'manage.py' or '--in-development' in sys.argv:
        # ...
        pass
    

    Although this works, I recognize it's not the most elegant of solutions...

提交回复
热议问题