用于群发邮件的简单Python脚本optu

2024-05-23 13:52:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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."

大约有10000封电子邮件被淘汰。但是,每当它发现一封与已删除帐户关联的电子邮件时,它会说:

django.contrib.auth.models.DoesNotExist: User matching query does not exist.

如果用户配置文件不存在,我想让它说“跳过”(就像打印完成一样)。在

我试着加上“else print”跳过了,但没用。我是Python新手,任何帮助我都将不胜感激。在


Tags: 用户脚本comforexample电子邮件emailprofile
1条回答
网友
1楼 · 发布于 2024-05-23 13:52:57

您可以捕获异常并使用^{}跳过记录。通过对模型对象本身使用异常,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."

或者显式导入基异常,^{}

^{pr2}$

相关问题 更多 >