views:

323

answers:

4

Hi

I have a website which fetches information from RSS feeds periodically (well, currently manually, and this is my problem). This is currently implemented as a normal Django view, which isn't very nice in my opinion. I'd like to have a Python program which is run using a cronjob instead of manually visiting the correct URL to update the information.

What is the easiest way to make a Python program have access to my particular Django application and the Django ORM?

+5  A: 
from django.core.management import setup_environ
from django.core.mail import EmailMultiAlternatives, send_mail
from django.contrib.auth.models import User

import settings
from my.app.models import *

setup_environ(settings)

This was how I did it for a cron that emailed parties daily updates. The .py lived in the root of my django app, so the import settings would reflect that accordingly.

Joel Hooks
This was very helpful. Thanks.
Paolo Bergantino
A: 

You want something like this in your crontab:

PYTHONPATH=/path/to/your/project DJANGO_SETTINGS_MODULE=settings myscript.py

And then your python script should start with this:

#!/usr/bin/env python

from django.conf import settings

From there, you should be able to import your models / views / forms / whatever else, and have an environment pretty much just like a ./manage.py shell

Note: Depending on how you do your imports inside your project, this may not work exactly as shown. If you are always doing something like "from myproject.myapp.models import *", then you will want to set cron line to look more like this:

PYTHONPATH=/path/to/1_level_before_your_project DJANGO_SETTINGS_MODULE=myproject.settings myscript.py
Ian Clelland
A: 

I'd like to have a Python program which is run using a cronjob instead of manually visiting the correct URL to update the information.

A simplistic alternative: write a cronjob to automatically "visit the correct URL to update the information" -- could be as simple as a curl or wget, after all. This doesn't answer the question in the title, but given the way you explain your real underlying problem it just might be the simplest and most immediate approach to solve it.

Alex Martelli
+5  A: 

An alternative to all the approaches given here is to write your cron job as a custom ./manage.py command. This is very easy to do, and gives you the ability to do ./manage.py yourcommand either on the command line or in your crontab.

The documentation on this is very sparse, but it does tell you to look at the code for the existing commands, which you can use as a template for your own.

Daniel Roseman
This works flawlessly; just as an additional note, bear in mind that cron and apache are owned by different users, and therefore you may have issues with environment (like proxy, permissions, etc).
Roberto Liffredo
You can probably have the cron job run as the apache user.
Matthew Schinckel