views:

43

answers:

2

I want to run automatic newsletter function in my crontab, but no matter what I try - I cannot make it work. What is the proper method for doing this ? This is my crontab entry :

0 */2 * * * PYTHONPATH=/home/muntu/rails python2.6 /home/muntu/rails/project/newsletter.py

And the newsletter.py file, which is located in the top folder of my django project :

#! /usr/bin/env python
import sys
import os

os.environ["DJANGO_SETTINGS_MODULE"] = "project.settings"
from django.core.management import setup_environ
from project import settings
setup_environ(settings)

from django.template.loader import get_template, render_to_string
from django.template import Context
from django.core.mail import EmailMultiAlternatives
from django.utils.translation import ugettext_lazy as _
from django.core.mail import send_mail
from django.conf import settings
from project.utilsFD.models import *
from django.http import HttpResponse, HttpResponseRedirect, Http404

def main(argv=None):
    if argv is None:
        argv = sys.argv

    template_html = 'static/newsletter.html'
    template_text = 'static/newsletter.txt'
    newsletters = Newsletter.objects.filter(sent=False)
    adr = NewsletterEmails.objects.all()
    for a in adr:
        for n in newsletters:
            to = a.email          
            from_email = settings.DEFAULT_FROM_EMAIL           
            subject = _(u"Newsletter - Method #1")

            text_content = render_to_string(template_text, {"title": n.title,"text": n.text, 'date': n.data, 'email': to})
            html_content = render_to_string(template_html, {"title": n.title,"text": n.text, 'date': n.data, 'email': to})

            msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
            msg.attach_alternative(html_content, "text/html")
            msg.content_subtype = "html"
            msg.send()
            n.sent = True
            n.save()

if __name__ == '__main__':
    main()

What am I doing wrong ? The function itself was working without any problems when run as django app, but when I was trying to run it from console, it gave me :

Traceback (most recent call last):
  File "newsletter.py", line 7, in <module>
    from project import settings
ImportError: No module named project

And it does not work from cron at all.

A: 

do you have a __init__.py file in the project folder?

Thr4wn
sure I do. I guess there's no way any django project would run without it :)
muntu
+1  A: 

Try changing your cron entry to:

0 */2 * * * cd /home/muntu/rails && python2.6 /home/muntu/rails/project/newsletter.py

This will ensure that the "rails" directory is in python's path. If you want to set the PYTHONPATH, then create a shell script:

#!/bin/sh
export PYTHONPATH=/home/muntu/rails
python2.6 /home/muntu/rails/project/newsletter.py

and put the shell script in the cron entry.

ars