繁体   English   中英

celery中的自定义json序列化

[英]Custom json serialization in celery

我正在尝试将 celery 与已实现自定义序列化程序的自定义对象一起使用,但 celery 工作人员尝试使用酸洗。

芹菜配置文件

broker_url = 'redis://localhost'
result_backend = 'redis://localhost'
imports = ('tasks',)
accept_content = ['application/x-json']
task_serializer = 'custom_json'
result_serializer = 'custom_json'

应用程序.py

from celery import Celery
from . import serializers
from . import celeryconfig

from kombu import serialization
serialization.register(
    'custom_json',
    serializers.dumps,
    serializers.loads,
    content_type='application/x-json',
    content_encoding='utf-8',
)

app = Celery()
app.config_from_object(celeryconfig)

if __name__ == '__main__':
    app.start()

主文件

from .tasks import my_task
my_obj = CustomClass()
my_task.delay(my_obj)

如果我的 class 在 python 中定义,则此代码可以正常工作:

class CustomClass:
    def __init__(self):
        ...

但我的CustomClass实际上来自 Boost.Python 绑定,我从 an.so 文件导入,然后我从工作人员那里得到以下错误:

[2020-04-11 16:25:08,102: INFO/MainProcess] Received task: my_task[f73a3119-65d7-4a04-9e0d-2bc25ad19dde]  
...
RuntimeError: Pickling of "CustomClass" instances is not enabled (http://www.boost.org/libs/python/doc/v2/pickle.html)

我知道错误消息建议深入研究他们的泡菜的具体情况。 但是使用自定义 json 序列化器的全部意义在于不要在这条路上使用 go。

所以我的问题是:为什么 celery 甚至尝试使用酸洗?

编辑:作为一个虚拟示例,以下不可腌制的 class (无升压)将产生以下错误:

 Unrecoverable error: TypeError("can't pickle generator objects",)

class NonPicklableClass:

    def __init__(self, arg):
        self.gen = (i for i in arg)


class CustomEncoder(json.JSONEncoder):

    def default(self, o):
        if isinstance(o, NonPicklableClass):
            return {
                '__type__': 'custom',
                'raw': list(o.gen),
            }
        return o

def hook(o):
    dtype = o.get('__type__')
    if dtype == 'custom':
        return NonPicklableClass(o['raw'])

def dumps(o):
    return json.dumps(o, cls=CustomEncoder)

def loads(s):
    return json.loads(s, object_hook=hook)

我显然一定是误会了什么

我想我明白了,作业是使用自定义序列化程序发送给工作人员的。

然而,在每个工作人员中,数据使用常规的 python 酸洗通过每个进程。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM