task.py
@task(name="send_mail_to_custormer")
def order_created(order_id):
order = Order.objects.get(id=order_id)
subject = 'Order nr. {}'.format(order.id)
message = 'Dear {} {},\n\nYou have successfully placed an order. Your order id is {}'.format(order.first_name,
order.last_name, order.id)
from_email = settings.EMAIL_HOST_USER
to_email = [order.email]
mail_sent = send_mail(
subject,
message,
from_email,
to_email,
fail_silently=False
)
return mail_sent
views.py
def order_create(request):
cart = Cart(request)
if request.method == 'POST':
form = OrderCreateForm(request.POST)
if form.is_valid():
order = form.save()
for item in cart:
try:
OrderItem.objects.create(order=order,
product=item['product'],
price=item['price'],
quantity=item['quantity'])
except:
pass
cart.clear()
order_created.delay(order.id)
return render(request,'orders/order_created.html', {'cart': cart, 'order': order})
else:
form = OrderCreateForm()
return render(request, 'orders/order_create.html', {'cart': cart, 'form': form})
cart.py
class Cart(object):
def __init__(self, request):
self.session = request.session
cart = self.session.get(settings.CART_SESSION_ID)
if not cart:
cart = self.session[settings.CART_SESSION_ID] = {}
self.cart = cart
def add(self, product, quantity=1, update_quantity=False):
product_id = str(product.id)
if product_id not in self.cart:
self.cart[product_id] = {'quantity': 0,
'price': str(product.price)}
if update_quantity:
self.cart[product_id]['quantity'] = quantity
else:
self.cart[product_id]['quantity'] += quantity
self.save()
def save(self):
self.session[settings.CART_SESSION_ID] = self.cart
self.session.modified = True
现在芹菜任务发送邮件和查看功能在从购物车和订单表格中取值后创建订单。如何更改创建订单的任务?这样做是一种好习惯。希望有人可以帮助我,谢谢。还可以使用django消息框架作为芹菜任务来做成功消息吗?
答案 0 :(得分:2)
我不会也不会(在我的公司中我们经营几家网店)以异步方式创建订单。当用户看到您的感谢页面时,您最好确保已创建订单。毕竟只有几个db操作,页面速度不会成为问题。但是,邮件发送是一项不应延长请求 - 响应周期的任务的典型示例。但有一件事:你可能想考虑给你的任务安全延迟几秒钟:
order_created.apply_async(args=[order.id], countdown=5)
刚刚创建了订单 - 特别是如果您为数据库设置了原子请求 - 任务工作者可以在订单创建事务提交之前查询订单,并且对工作人员可见。或者,您可以使用transaction.on_commit
挂钩来避免该竞争条件。