我目前正在使用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控制台上做了一个测试,看看我的语法是否有问题,但一切都按照我的计划进行。那么什么可能导致这个错误?
的更新 的
我认为过期是评估hmset(activity_key,mapping)的结果。这很奇怪! expire是一种管道方法。
第二次更新
我暂时找到了解决方法。看来这只发生在芹菜中。原生Django视图和python控制台不会表现出这种行为。它似乎在评估它之前的表达式的结果。如果你们中的任何一个遇到这个问题,这是一个解决方法。
pipe.hmset(activity_key, mapping)
pipe.lpush('mylist', 1)
pipe.expire('mylist', 300)
pipe.execute()
这应该有用,不会给你任何问题。快乐的编码!
答案 0 :(得分:2)
pipe.hmset()
不返回管道;你不能在这里链接电话。相反,返回一个布尔值(可能表示hmset()
调用是否成功)。
分别调用.expire()
和.execute()
方法:
pipe.hmset(activity_key, mapping)
pipe.expire(activity_key, seconds)
pipe.execute()
我怀疑你需要在Celery任务中创建一个管道,而不是在这里重新使用全局。将pipe = r_server.pipeline()
移至活动中。