如何动态关闭和打开电子邮件发送?

How to dynamically turn off and on email sending?

我有一个预订模型,它在创建时向用户发送电子邮件。

出于测试目的,我想不时地用数百个 Reservations 填充数据库。

它可以产生数千封电子邮件,所以我想关闭电子邮件发送,或者如果可能的话动态更改电子邮件后端。

我无法进行批量创建,因为我需要为每个 Reservation 模型执行 save 方法。

我唯一想到的是暂时更改 settings.py 但也许有更好的方法来做到这一点(我可能忘记更改设置)。

def create_random_reservations(count=10, user='futilestudio'):
    users = User.objects.all()
    airports = Location.objects.filter(is_airport=True)
    cities = Location.objects.filter(is_airport=False)

    for n in range(count / 2):
        dt = datetime(year=2017, month=9, day=random.choice(range(15, 20)), hour=random.choice(range(12, 22)),
                      minute=random.choice(range(60)))
        r = Reservation.objects.create(customer_first_name=get_random_string(10),
                                       customer_last_name=get_random_string(10), flight_number=get_random_string(5),
                                       destination_from=random.choice(airports), destination_to=random.choice(cities),
                                       date_arrival=dt.date(), time_arrival=dt.time(), customer=random.choice(users))
        r.confirm(save=True)

您应该至少有两个不同的设置文件 - 一个用于生产,一个用于开发。只需将开发环境的开发设置 EMAIL_BACKEND 设置为 something that does not effectively send mails