How to run django management custom commands with escalated privileges?

154 views Asked by At

I am trying to run a custom django management command from my views. I have the view ready to execute the command as shown below:

from django.core.management import call_command
import django

def send_queued_mails():
    # Run Django Setup
    django.setup()
    call_command('send_all_queued_mails')

But, when the command is executed on my windows machine, I get the following error:

    os.symlink(self.pid_filename, self.lock_filename)
    OSError: symbolic link privilege not held

I can tackle this manually by running the terminal as Administrator but I want to run the command through my views and with escalated privileges.

Any ideas or suggestions are appreciated.

PS: I also tried using OS level command as shown below:

from subprocess import call
call(["python", "manage.py", "send_all_queued_mails"])

But I am getting the same error as above.

1

There are 1 answers

0
Dhwanil shah On

I found a solution which works well for me and might work for others as well. I am using django-post_office for sending emails. I traced back to the line where the error originated, it was as follows:

    if hasattr(os, 'symlink'):
        os.symlink(self.pid_filename, self.lock_filename)
    else:
        # Windows platforms doesn't support symlinks, at least not through the os API
        self.lock_filename = self.pid_filename

The comments clearly stated that Windows does not support symlink, so, I modified the code a bit to avoid the error.

        if hasattr(os, 'symlink') and platform.system() != 'Windows':
        os.symlink(self.pid_filename, self.lock_filename)
    else:
        # Windows platforms doesn't support symlinks, at least not through the os API
        self.lock_filename = self.pid_filename

This is not the exact solution as it does not solve the problem of escalated privileges while running that command. But, if you are facing a similar error, you can directly assign the file you want to create the symlink for to the desired file.

If anyone knows a better way please do answer.