Redis后端无法正常工作?

时间:2017-07-23 17:40:44

标签: python django redis celery

我在django项目中使用带有redis的Celery。我试图从我的celery_app延迟10秒调用expire函数。每当函数执行时,页面只是说localhost没有响应。我认为是因为我的后端无法正常工作?有人可以帮忙吗? 附:如果我用结果

删除2行,则get方法有效

celery_app.py

from __future__ import absolute_import
import os
from celery import Celery

from django.conf import settings
from celery.schedules import crontab

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'IrisOnline.settings')

app = Celery('IrisOnline', broker='redis://localhost:6379/0',backend="redis://localhost:6379/0",include=[
    "IrisOnline.tasks",
    "order_management.tasks"
])

app.conf.update(
    task_serializer='json',
    accept_content=['json'],
    result_serializer='json',
    timezone='Asia/Manila',
)
app.conf.beat_schedule = {
    'add-every-30-seconds': {
        'task': 'IrisOnline.tasks.printthis',
        'schedule':(crontab(hour=13,minute=33)),
    },
}

app.config_from_object('django.conf:settings')

app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

@app.task(name="expire")
def expire():
    print("object expired")

views.py

def get(request):

    if "approved_cart" not in request.session or not request.session["approved_cart"]:
        return redirect("/checkout/cart/")

    cart = request.session["cart"]
    customer = Customer.objects.get(user=request.user)
    order = Order.objects.create(customer=customer)

    result = expire.apply_async(countdown=40) #these causes the errors
    result.get()


    for product_id, quantity in cart.items():
        # Deduct from inventory
        product = Product.objects.get(id=product_id)
        product.quantity -= quantity
        product.save()

        # Add quantity to order
        OrderLineItems.objects.create(
            product=Product.objects.get(id=product_id),
            quantity=quantity,
            parent_order=order
        )

    request.session["cart"] = {}  # Empty cart
    request.session["approved_cart"] = False
    request.session.modified = True
    context = make_context(request)
    context["total_price"] = order.total_price

    return render(request, 'purchase.html', context)

1 个答案:

答案 0 :(得分:0)

当您致电result.get()时,实际上等待任务完成 - 请参阅Celery documentation

因此,在您的情况下,这将最多等待40秒,因为您设置了countdown=40。我认为大多数浏览器等待时间超过40秒,因此这可能不是您的问题。

但是你应该问自己:如果你要在启动该任务的代码中等待它的结果,你为什么要运行一个单独的任务呢?

回到您的问题 - 错误表明您的单独任务未运行。调试此方法的一种方法是在您的设置中设置CELERY_ALWAYS_EAGER = True。这使得任务在调用过程中立即运行。如果代码在这些条件下工作,则问题可能是您的芹菜工人没有运行。