用于群发电子邮件的简单Python脚本退出

时间:2014-07-15 15:40:41

标签: python django

我有一个Python脚本可以选择用户退出电子邮件。

optouts = [
"user1@example.com",
"user2@example.com",
"user3@example.com",
]

for email in optouts:
    user = User.objects.get(email=email)
    profile = user
    profile.allow_mass_mails = False
    profile.save()
    print email, "opted out."


print "done."

大约有10,000封电子邮件被选中。但是,只要发现与已删除帐户绑定的电子邮件,就会显示:

  

django.contrib.auth.models.DoesNotExist:用户匹配查询不存在。

如果用户个人资料不存在,我希望它说“跳过”(就像打印完成一样)。

我尝试添加“else print”跳过“但这不起作用。我是Python新手,感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

您可以使用continue捕获异常并跳过记录。通过在模型对象本身上使用异常,User.DoesNotExist

for email in optouts:
    try:
        user = User.objects.get(email=email)
    except User.DoesNotExist:
        print email, "skipped."
        continue
    profile = user
    profile.allow_mass_mails = False
    profile.save()
    print email, "opted out."

或者通过显式导入基本异常django.core.exceptions.ObjectDoesNotExist

from django.core.exceptions import ObjectDoesNotExist

for email in optouts:
    try:
        user = User.objects.get(email=email)
    except ObjectDoesNotExist:
        print email, "skipped."
        continue
    profile = user
    profile.allow_mass_mails = False
    profile.save()
    print email, "opted out."