celery任务中的transaction.atomic()

时间:2017-06-30 08:15:35

标签: django postgresql celery

以下代码有时会出现InternalError(' SAVEPOINT只能用于事务块\ n',)。我知道在transaction.atomic中我们不能调用celery任务,但是无法找到在celery任务中使用原子请求是否可以(我需要芹菜任务中的原子性)。

@celery.task(default_retry_delay=2 * 60, max_retries=2)  # retry in 2 minutes
def update_matching(company_id=None, shop_id=None):
    """
    creates active matchings between shops & companies
    """
    from customers.models import Shop, Matching
    from sellers.models import SellRegion, Company
    from products.models import Item
    from utils.procedures import update_items_timestamp_query
    logger.info(u"company_id: %s shop_id: %s" % (company_id, shop_id))
    company = Company.objects.filter(id=company_id).first()
    shop = Shop.objects.filter(id=shop_id).first()
    try:
        shops = [shop] if shop else Shop.objects.all()
        sell_regions = SellRegion.objects.filter(company=company, is_active=True).select_related("district") if company else SellRegion.objects.filter(is_active=True)
        for shop in shops:
            # here was transaction.atomic()
            logger.info(u"shop: %s " % shop)
            Matching.objects.filter(shop=shop, company__in=[x.company for x in sell_regions]).update(is_active=False)
            shop_category_ids = [x.category.id for x in shop.categories.filter(active=True)]
            for sell_region in sell_regions.filter(district=shop.district).select_related("company"):
                # check district & if category is active in this district
                if getattr(sell_region, SellRegion.get_category_name(shop.category)):
                # check whether categories match
                    if sell_region.company.categories.filter(category__id__in=shop_category_ids, active=True).exists():
                        logger.info(u"shop: %s company: %s" % (shop, sell_region.company))
                        Matching.objects.register(shop=shop, company=sell_region.company)
                        update_items_timestamp_query(sell_region.company.id)
    except Exception, exc:
        logger.error(exc)
        raise update_matching.retry(exc=exc)

这是完整的查询:     问题已经解决了,但正如你所见,查询没有得到优化,而且这个芹菜任务经常被调用。还有postgres存储函数(update_items_timestamp_query)。

0 个答案:

没有答案