views:

396

answers:

2

Hello, I would like to compute some information in my Django application on regular basis. I need to select and insert data each second and want to use Django ORM.

How can I do this?

+1  A: 

In a shell script, set the DJANGO_SETTINGS_MODULE variable and call a python script

export DJANGO_SETTINGS_MODULE=yourapp.settings
python compute_some_info.py

In compute_some_info.py, set up django and import your modules (look at how the manage.py script sets up to run Django)

#!/usr/bin/env python
import sys
try:
    import settings # Assumed to be in the same directory.
except ImportError:
    sys.stderr.write("Error: Can't find the file 'settings.py'")
    sys.exit(1)

sys.path = sys.path + ['/yourapphome']
from yourapp.models import YourModel

YourModel.compute_some_info()

Then call your shell script in a cron job.

Alternatively -- you can just keep running and sleeping (better if it's every second) -- you would still want to be outside of the webserver and in your own process that is set up this way.

Lou Franco
+1, yes make it a separate process independent of the webserver.
celopes
A: 

One way to do it would be to create a custom command, and invoke python manage.py your_custom_command from cron or windows scheduler.

http://docs.djangoproject.com/en/dev/howto/custom-management-commands/

For example, create myapp/management/commands/myapp_task.py which reads:

from django.core.management.base import NoArgsCommand

class Command(NoArgsCommand):
    def handle_noargs(self, **options):
        print 'Doing task...'
        # invoke the functions you need to run on your project here
        print 'Done'

Then you can run it from cron like this:

export DJANGO_SETTINGS_MODULE=myproject.settings; export PYTHONPATH=/path/to/project_parent; python manage.py myapp_task

dar