django-事务、发送邮件
事务:有两个操作需要同时成功,有一个失败则回滚到之前的状态。django已经封装好,一条with语句即可实现
from django.db import transaction with transaction.atomic(): # 增加一条评论 new_comment = models.Comment.objects.create(user_id=user_id, article_id=article_id, content=content, parent_comment_id=pid) # 修改文章的评论数量 models.Article.objects.filter(pk=article_id).update(comment_count=F("comment_count") + 1)
发送邮件:
settings:
EMAIL_HOST = 'smtp.exmail.qq.com' # 如果是 163 改成 smtp.163.com EMAIL_PORT = 465 EMAIL_HOST_USER = '' # 帐号 EMAIL_HOST_PASSWORD = '' # 密码 # DEFAULT_FROM_EMAIL = EMAIL_HOST_USER EMAIL_USE_SSL = True
views:
from django.core.mail import send_mail from cnblog import settings # send_mail( # "您的文章%s新增了一条评论内容"%article_obj.title, # content, # settings.EMAIL_HOST_USER, # ["***@qq.com"] # ) import threading t = threading.Thread(target=send_mail, args=("您的文章%s新增了一条评论内容" % article_obj.title, content, settings.EMAIL_HOST_USER, ["***@qq.com"]) ) t.start()