0

I need to execute some code when devserver is started.

At the moment I just place the code into models.py inside one of my applications.

This solution has a side effect: the code is executed when other managements commands are used, and I'd like to avoid it.

Updated: This will be a part of distributable application. I don't want users (developers actually) to run any additional commands. They should be able to use the runserver command only. I also don't want to override runserver command with my own implementation.

Updated: My models.py looks like this:

from django.conf import settings

if settings.DEBUG: # I actually use another setting here, but it does not matter
    run_my_code_in_a_daemon_thread()

I don't have any actual models in this file. So, my code is executed only once: when Django scans all applications from INSTALLED_APPS and imports their models.py.

2 Answers 2

2

Custom bash (python) launcher will be fine. Or you can write your own management command.

Sign up to request clarification or add additional context in comments.

8 Comments

I don't want to use another command or script. I need the code to run automatically when devserver is started.
@AndreyFedoseev Your code needs to be launched somehow, so you should write a launcher. Alternatively you can check if you are in dev mode (I do it with platform.node() but there are plenty of options).
I already have my code launched, see my question. I just need to ensure it's executed only by devserver only.
@AndreyFedoseev Your code is launched every time. That's why you need a special launcher. Three options: special launcher, checking for dev mode and dark magic. The last one isn't very reliable though. :-)
What do you mean by "every time"? It is launched only when models.py is imported. In my models.py I don't have any actual models, just a bit of code which I need to execute. So it's launched only once, when Django starts, scans all applications from INSTALLED_APPS and imports their models.py.
|
1

You can simply update your local manage.py? Check for the parameter that gets passed (you're interested in runserver, and if it does, execute the code you want from there. Something like this:

if __name__ == "__main__":
    if sys.argv[1] == 'runserver':
        # Your custom code
    execute_manager(settings)

2 Comments

Doesn't work for me. I use zc.buildout and djangorecipe, it generates manage.py script for me. So all my changes will be lost when I rebuild Django instance.
In that case, DrTyrsa's answer applies: just create a (bootloader like) script that does the stuff you want to be done before the launch, and then let it run python manage.py runserver.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.