Forums

can't launch task with virtualenv and variables

Hi! I have successfully followed the topics to launch simple tasks and tasks with virtualenvs.

However, launching a task with virtualenv and variables fails...

source virtualenvwrapper.sh && workon env_td_mine && python3.5 /home/my_username/dev/td_mine/mine_production/reusableminer/launch/hello_dropbox_task.py

Error:

Traceback... (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting DROPBOX_TOKEN, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. The script uses Dropbox token as a variable. When I use workon env_td_mine and then python manage.py shell to play with script in bash with virtualenv loaded, everything is OK.

Seems like I can't properly launch task with virtualenv variables. How to do it correctly?

The problem isn't the virtualenv -- it's because your code uses Django stuff, and you need to configure its settings so that it can run. So while it does work if you do

$ workon env_td_mine
$ python manage.py shell
...
In [1]: %run /home/my_username/dev/td_mine/mine_production/reusableminer/launch/hello_dropbox_task.py

...if you were to run it from Bash directly (with python /home/my_username/dev/td_mine/mine_production/reusableminer/launch/hello_dropbox_task.py), you'd get the same error as you're getting in the task.

IMO the best way to structure your script to make it work would be to change it so that it works as a custom Django management command -- see the link for documentation on how to create one. When you do that, you have a way to run your code using

python manage.py mycustomcommand

...which you can easily schedule (along with the source and the workon).

However, a quick-and-dirty hack that would get your code running quickly would be to manually initialize the Django settings at the top of the script, as per this bit of the Django docs:

import django
from django.conf import settings
from myapp import myapp_defaults

settings.configure(default_settings=myapp_defaults, DEBUG=True)
django.setup()

replacing the

from myapp import myapp_defaults

with code to actually import your settings module, and of course changing the myapp_defaults in the call to configure to refer to your actual settings.

Thanks a lot for such a detailed help! Rebuilt the app to use custom commands with and without arguments, it works.

Excellent! Glad we could help :-)