python – 芹菜:有没有办法编写自定义JSON编码器/解码器?

我有一些我想在我的应用程序中发送到芹菜任务的对象。那些对象显然不是json可以使用默认的json库来序列化。有没有办法使芹菜使用自定义JSON编码器/解码器序列化/解序列化这些对象?
在这里稍晚,但您应该能够通过在kombu序列化器注册表中注册来定义自定义编码器和解码器,如文档:http://docs.celeryproject.org/en/latest/userguide/calling.html#serializers

例如,以下是Django的自定义datetime serializer / deserializer(子类化python’s builtin json module):

myjson.py(把它放在你的settings.py文件的同一个文件夹中)

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'
http://stackoverflow.com/questions/21631878/celery-is-there-a-way-to-write-custom-json-encoder-decoder

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:python – 芹菜:有没有办法编写自定义JSON编码器/解码器?