我正在使用 celery 任务队列,它使用 Redis 作为消息代理来运行一些后台任务,将结果保存到 Redis。
我想从已完成的任务结果中清除 Redis,因为我不再需要它们,所以如果出现大幅峰值,我不应该担心。
我发现CELERY_RESULT_EXPIRES这表明任务结果将在 X 秒后自动清理。
from celery import Celery
CONFIG = {
'BROKER_URL': 'redis://localhost:6379/0',
'CELERY_RESULT_BACKEND': 'redis://localhost:6379/0',
'CELERY_RESULT_EXPIRES': 15, # 15 secs
'BROKER_POOL_LIMIT': 0, # redis connection get closed once task is done..
}
celery = Celery('tasks', config_source=CONFIG)
@celery.task(name='tasks.say_hello')
def say_hello():
return "Helloooooo i just came out from the background!"
if __name__ == '__main__':
say_hello.delay().get()
Run Code Online (Sandbox Code Playgroud)
当运行上面的代码并且celery beat -A tasks -l info也运行时,然后在一段时间(超过 5 分钟)后检查 Redis,我看到了这个:
127.0.0.1:6379> KEYS *
1) "_kombu.binding.celery"
2) …Run Code Online (Sandbox Code Playgroud) 我试图了解一些使用下面这个类的代码结构:
class Base(object):
def __init__(self, **kwargs):
self.client = kwargs.get('client')
self.request = kwargs.get('request')
...
def to_dict(self):
data = dict()
for key in iter(self.__dict__): # <------------------------ this
if key in ('client', 'request'):
continue
value = self.__dict__[key]
if value is not None:
if hasattr(value, 'to_dict'):
data[key] = value.to_dict()
else:
data[key] = value
return data
Run Code Online (Sandbox Code Playgroud)
好的,所以我知道它获取传递给 Base 类的键值参数,例如Base(client="foo", request="bar").
我的困惑是为什么它使用self.__dict__which 将变量内部__init__转换为 dict (例如{"client": "foo", "request": "bar"})而不是仅通过self.client&self.request在其他方法中调用它们,我做错了什么吗?何时以及为什么我应该使用它self.__dict__?
请问我在哪里可以找到使用/理解这些 dunder 方法的可靠指南?
先感谢您。