Celery:有没有办法编写自定义JSON编码器/解码器? [英] Celery: is there a way to write custom JSON Encoder/Decoder?

查看:260
本文介绍了Celery:有没有办法编写自定义JSON编码器/解码器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些要发送到我的应用程序中的芹菜任务的对象.这些对象显然无法使用默认的json库进行json序列化.有没有一种方法可以使celery使用自定义JSON Encoder/Decoder序列化/反序列化这些对象?

I have some objects I want to send to celery tasks on my application. Those objects are obviously not json serializable using the default json library. Is there a way to make celery serialize/de-serialize those objects with custom JSON Encoder/Decoder?

推荐答案

有点晚了,但是您应该能够通过在kombu序列化程序注册表中注册它们来定义自定义编码器和解码器,如docs中所示: http://docs.celeryproject.org/en/latest/userguide/calling.html #serializers .

A bit late here, but you should be able to define a custom encoder and decoder by registering them in the kombu serializer registry, as in the docs: http://docs.celeryproject.org/en/latest/userguide/calling.html#serializers.

例如,以下是自定义的日期时间序列化器/反序列化器(子类化为 python的内置json模块),用于Django:

For example, the following is a custom datetime serializer/deserializer (subclassing python's builtin json module) for Django:


myjson.py (将其放置在settings.py文件的同一文件夹中)


myjson.py (put it in the same folder of your settings.py file)

import json
from datetime import datetime
from time import mktime

class MyEncoder(json.JSONEncoder):   
    def default(self, obj):
        if isinstance(obj, datetime):
            return {
                '__type__': '__datetime__', 
                'epoch': int(mktime(obj.timetuple()))
            }
        else:
            return json.JSONEncoder.default(self, obj)

def my_decoder(obj):
    if '__type__' in obj:
        if obj['__type__'] == '__datetime__':
            return datetime.fromtimestamp(obj['epoch'])
    return obj

# Encoder function      
def my_dumps(obj):
    return json.dumps(obj, cls=MyEncoder)

# Decoder function
def my_loads(obj):
    return json.loads(obj, object_hook=my_decoder)


settings.py

# Register your new serializer methods into kombu
from kombu.serialization import register
from .myjson import my_dumps, my_loads

register('myjson', my_dumps, my_loads, 
    content_type='application/x-myjson',
    content_encoding='utf-8') 

# Tell celery to use your new serializer:
CELERY_ACCEPT_CONTENT = ['myjson']
CELERY_TASK_SERIALIZER = 'myjson'
CELERY_RESULT_SERIALIZER = 'myjson'

这篇关于Celery:有没有办法编写自定义JSON编码器/解码器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆