How to run django management custom commands with escalated privileges? - django

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.

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.

Related

Error: cannot import name RemovedInDjango110Warning in django 1.9.5

So this code has been running for like a week now, today it is throwing this error. And this is not happening at the URL level, which many places seem to say.
I am using celery, djcelery and Django 1.9.5. In my celery task, in one part where I am trying to connect to my DB, it is throwing this error. The strange part is when I run the code line by line in shell, it works.
All this code runs inside a virtualenv being used by two projects which have exactly same requirements. to confirm, I just checked the django version in pip. It is 1.9.5
Please let me know if any extra info is required.

GAE import endpoints "No module named endpoints"

I'm using pycharm to develop appengine. Now i'm trying to use endpoints and I've put
libraries:
- name: pycrypto
version: latest
- name: endpoints
version: 1.0
and then in main.py
import endpoints
But it gives me error
No module named endpoints
I can see the endpoints folder inside the GAE library. Anyone can help?
*EDIT: it is just a matter of IDE (pycharm) cant locate endpoints. The app runs fine and okay both in dev server or cloud server. There is a picture just to make it a bit clearer:
Thanks
You need to add {GAE_SDK}/lib/endpoints-1.0, not just the SDK itself. The reason you can import google is because it is directly under {GAE_SDK}. The libraries you specify in app.yaml are laid out differently due to supporting multiple versions. I believe you also need to add {GAE_SDK}/lib/protorpc-1.0/, it's just not showing because there's already an import error.
I'm using the new version of PyCharm Community and I got to config too. You need to set the Source option on each folder like endpoints in File - Setting - Project:
I've run across the following code somewhere which fixes it for me in a client script. I'm not able to say how much of it may be unnecessary. You'd need to edit the google_appengine path for your SDK installation:
sdk_path = os.path.expanduser('~/work/google-cloud-sdk/platform/google_appengine')
try:
import google
google.__path__.append("{0}/google".format(sdk_path))
except ImportError:
pass
try:
import protorpc
protorpc.__path__.append("{0}/lib/protorpc-1.0/protorpc".format(sdk_path))
except ImportError:
pass
sys.path.append("{0}/lib/endpoints-1.0".format(sdk_path))

Accessing Sentry models in my Django Project

I'm working on a system that has two django projects. A server and a client. The server is responsible for managing several client instances. This system relies on Sentry/Raven to process error logging.
My problem is that Sentry needs me to create and configure each client(sentry project) by hand. Since the number of client instances is large and I already have to do this by hand on my server project. I was trying to automatize the process, so that when I create a new client on the server, it creates a new Sentry project.
Much like in this question, I tried to access directly to the Sentry ORM on my project. But this revealed to be a dead end. So I wrote a python scrypt, to do this.
In said script, I import the DJANGO_SETTINGS_MODULE from sentry and work my way around with it until I have what I need.
sys.path.append("/sentry/")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", 'sentry_configuration_file')
from sentry.models import *
#Do my thing here
If I run the script on my shell, it works perfectly.
However, when I use subprocess to call it inside of my Django project
from subprocess import call
call("/sentry/venv/bin/python /sentry/my_script.py", shell=True)
The script generates the following error on the "from sentry.models import * line:
ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'configurations.settings' (Is it on sys.path?): No module named configurations.settings
You may have noticed that sentry is installed inside a virtualenv. However, I don't need it activated when I call this script on my bash, as long as I provide the correct path to the virtualenv's python.
I'm lost here. I see no reason in particular for the script to fail using subprocess.call when it runs fine using the shell.
Any pointers would be greatly apreciated.
Thanks.
If anyone ever comes across with this question, I managed to solve the issue by replacing subprocess.call by subprocess.Popen
The cool thing about Popen is that you can specify the environment of the process with the argument "env"
So
my_env = os.environ
my_env["DJANGO_SETTINGS_MODULE"] = "sentry_configuration_file"
result = Popen(command, shell=True, env=my_env)
Worked like a charm.

Django Caught an exception while rendering: No module named registration

I seem to have run into a bit of an issue.
I am busy creating an app, and over the last few weeks setup my server to use Git, mod_wsgi to host this app.
Since deploying it, everything seems to be running smoothly however, I had to go through all my files and insert the absolute url of the project to make sure it works fine.
on my local machine
from registration.models import UserRegistration
on server
from myapp.registration.models import UserRegistration
Am I doing something wrong?
And this has also caused an issue for me where I cannot access my django admin interface.
All i get is this: Caught an exception while rendering: No module named registration
Exception Value: Caught an exception while rendering: No module named registration
As far as I am concerned my app has all the relevant urls, but it does not seem to work.
Thank you in advance
The problem is occurring because somehow your local machine is adding the myapp directory to the PYTHONPATH, as well as its parent directory. The way to fix this is to modify your .wsgi script to add both these directories to sys.path:
import sys
sys.path.insert(0, '/path/to/parent')
sys.path.insert(0, '/path/to/parent/myapp')
Read and use improved WSGI script in:
http://blog.dscpl.com.au/2010/03/improved-wsgi-script-for-use-with.html
This will set up environment to better match Django built in development server and you shoud hopefully not see a difference between the two, especially in respect of how Python module search path is handled.

What is the correct configuration for %autoreload in a Django ipython shell?

Ipython has a plugin called autoreload that will presumably reload all your modules after every command, so you can change the source and not have to quit the shell and reenter all your commands. See http://dsnra.jpl.nasa.gov/software/Python/tips-ipython.html for example.
However, this seems flaky at best when using it with Django, e.g.
python manage.py shell
gives me an IPython shell with Django context, but the autoreloading does NOT seem to work reliably at all.
Here's what I have added to my ipy_user_conf.py file:
def main():
... # rest of the fn here
import ipy_autoreload
ip.magic('%autoreload 2')
The autoreloading works in limited cases, maybe 10-20% of the time.
Has anyone successfully configured this to work with Django?
This answer might also be applicable to your situation. Django keeps its own cache of all models, so if you want to reload everything, you have to clean this cache manually.