【问题标题】:Django: AttributeError: 'bool' object has no attribute 'expire'Django:AttributeError:'bool'对象没有属性'expire'
【发布时间】:2014-03-23 00:11:45
【问题描述】:

我目前正在使用 Andy McCurdy 的 redis.py 模块与 Django 中的 Redis 进行交互

我使用 Celery 将某些任务卸载到后台。

这是我的任务之一:

import redis
pool = redis.ConnectionPool(host='XX.XXX.XXX.X', port=6379, db=0, password='password')
r_server = redis.Redis(connection_pool=pool)
pipe = r_server.pipeline()

# The number of seconds for two months
seconds = 5356800

@shared_task
def Activity(userID, object_id, timestamp):
        timestamp = int(timestamp)
        # Create Individual activity for each.
        activity_key = 'invite:activity:%s:%s' % (userID, timestamp)
        mapping = dict(
            user_id = userID,
            object_id = object_id)
        pipe.hmset(activity_key, mapping).expire(activity_key, seconds).execute()

每当调用此任务时,我都会收到以下错误:

AttributeError: 'bool' object has no attribute 'expire'

这可能是什么原因造成的?

我后来在 python 控制台中做了一个测试,看看我的语法是否有问题,但一切都按我的计划进行。那么什么可能导致这个错误呢?

更新

我认为 expire 正在评估 hmset(activity_key, mapping) 的结果。这很奇怪! expire 是一种管道方法。

第二次更新

我暂时找到了解决办法。似乎这只发生在 Celery 中。本机 Django 视图和 python 控制台不表现出这种行为。它似乎在评估它之前的表达式的结果。如果你们中的任何人遇到这个问题,这里有一个解决方法。

pipe.hmset(activity_key, mapping)
pipe.lpush('mylist', 1)
pipe.expire('mylist', 300)
pipe.execute()

这应该有效,不会给您带来任何问题。快乐编码!

【问题讨论】:

    标签: python django redis celery


    【解决方案1】:

    pipe.hmset()返回管道;你不能在这里链接电话。而是返回一个布尔值(可能指示hmset() 调用是否成功)。

    分别调用.expire().execute()方法:

    pipe.hmset(activity_key, mapping)
    pipe.expire(activity_key, seconds)
    pipe.execute()
    

    我怀疑您需要在 Celery 任务中创建一个管道,而不是在此处重新使用全局。将pipe = r_server.pipeline() 移动到活动中。

    【讨论】:

    • 当我更新我的问题以显示我对什么有效的发现时,您已经在准确的时间回答了!我会把你的答案标记为正确答案。
    • 另外,这种行为只发生在 Celery 中。我在控制台中试了一下,效果很好。
    • 是的;通常Pipeline 方法应该是可链接的,这让我有点想知道这里发生了什么。
    • 是的,这正是我正在做的。我有 pipe = r_server.pipeline() 作为全局变量,但为什么会导致问题?
    • 如果您有多个线程使用一个全局管道对象,则不会。 pipe.reset() 可以保证顺序访问。
    猜你喜欢
    • 1970-01-01
    • 2020-01-09
    • 2023-03-03
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-15
    • 2021-03-30
    相关资源
    最近更新 更多