2

I have a Django project and other python script which is a ZMQ socket which continuously listens for message to perform some operation, ZMQ server script is an independent script which for now runs as python zmq_server.py in a terminal or cmd.

What I am trying to do is start the ZMQ server script when python manage.py runserver is called to start the django server.

I did some digging but found nothing related to this, is it possible to do something like this?

4
  • 1
    You could try putting import zmq_server in your settings or views and see if that does it Commented Jan 5, 2020 at 23:57
  • It is executing when I put it in settings.py, but I have to create a seperate thread or async process to execute that zmq_server script. will it be any issue if it is a seperate thread? Commented Jan 6, 2020 at 0:45
  • I think it should be fine Commented Jan 6, 2020 at 0:50
  • It works. It looks fine as it is working as expected. Thanks rob. Commented Jan 6, 2020 at 0:51

1 Answer 1

2

You can run any script when your Django server starts by importing it in your settings.py at the top like this:

import zmq_server

Normally that's what you'd do for a script you're going to use in your project, but if you just want it to get executed you can do it like that as well.

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

4 Comments

You are technically correct but settings.py gets executed twice, so my zmq_server throws an error that address already in use because it tries to bind the socket twice. Is there any other way to execute my server only once?
@VatsalChavda could you use sys.modules to get a list of already imported modules?
@VatsalChavda Have you tried putting the import statement in your views?
@VatsalChavda In my project the settings.py only gets loaded once, but I have seen it get loaded twice. It may be that you are importing your settings.py somewhere else in your project

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.