我想在我的 crontab 中运行自动通讯功能,但无论我尝试什么 - 我都无法让它工作。这样做的正确方法是什么?这是我的 crontab 条目:
0 */2 * * * PYTHONPATH=/home/muntu/rails python2.6 /home/muntu/rails/project/newsletter.py
还有 newsletter.py 文件,它位于我的 django 项目的顶部文件夹中:
#! /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()
我究竟做错了什么 ?当作为 django 应用程序运行时,该函数本身没有任何问题,但是当我尝试从控制台运行它时,它给了我:
Traceback (most recent call last):
File "newsletter.py", line 7, in <module>
from project import settings
ImportError: No module named project
而且它根本不适用于cron。