gpt4 book ai didi

python - 用于批量电子邮件选择退出的简单 Python 脚本

转载 作者:行者123 更新时间:2023-12-01 05:07:19 26 4
gpt4 key购买 nike

我有一个 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: User matching query does not exist.

如果用户配置文件不存在,我希望它显示“已跳过”(就像打印完成一样)。

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

最佳答案

您可以使用 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."

关于python - 用于批量电子邮件选择退出的简单 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24762475/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com