Skip to main content
 首页 » 编程设计

python之使用 JSON 序列化程序配置 Celery(Python + node.js)

2025年02月15日8exmyth

我正在使用 celery module 在 Python 中运行一个 Celery worker v3.1.25,以及带有 node-celery npm package 的 node.js 中的 Celery 客户端v0.2.7 (不是最新的)。

Python Celery worker 在使用 Python Celery 客户端发送作业时工作正常。

问题:当使用 node-celery 客户端向 Celery 后端发送任务时,我们在 JS 控制台中收到错误:

(STDERR) Celery should be configured with json serializer

Python Celery worker 配置为:

app = Celery('tasks',  
    broker='amqp://test:test@192.168.1.26:5672//', 
    backend='amqp://', 
    task_serializer='json', 
    include=['proj.tasks']) 

node-celery 客户端配置为:

var celery = require('node-celery') 
var client = celery.createClient({ 
    CELERY_BROKER_URL: 'amqp://test:test@192.168.1.26:5672//', 
    CELERY_RESULT_BACKEND: 'amqp', 
    CELERY_TASK_SERIALIZER: "json" 
}); 
 
client.on('connect', function() { 
    console.log('connected'); 
 
    client.call('proj.tasks.getPriceEstimates', [start_latitude, start_longitude], 
        function(result) { 
            console.log('result: ', result); 
            client.end(); 
        }) 
}); 

这是 Python Celery worker 上的配置问题吗?我们是否错过了一个可以将返回序列化格式更改为 json 的配置参数?


更新

按照 ChillarAnand 的建议更新了 result_serializers 和 accept_content 参数

from __future__ import absolute_import, unicode_literals 
from celery import Celery 
 
app = Celery('tasks',  
    broker='amqp://test:test@192.168.1.26:5672//', 
    backend='amqp://', 
    task_serializer='json', 
    result_serializer='json', 
    accept_content=['application/json'], 
    include=['proj.tasks']) 

但是 node.js Celery 客户端仍然认为它不在 json 中,抛出相同的错误消息。

它给出了那个错误,因为 results were in the form of 'application/x-python-serialize' .

检查是否是这种情况,因为 RabbitMQ 管理控制台显示结果为 content_type: application/x-python-serialize


This forum post says that这是因为任务是在加载配置之前创建的。

我的文件是这样的:

proj/celery.py

from __future__ import absolute_import, unicode_literals 
from celery import Celery 
 
app = Celery('tasks',  
    broker='amqp://test:test@192.168.1.26:5672//', 
    backend='amqp://', 
    task_serializer='json', 
    result_serializer='json', 
    accept_content=['application/json'], 
    include=['proj.tasks']) 

proj/tasks.py

from __future__ import absolute_import, unicode_literals 
from .celery import app 
 
@app.task 
def myTask(): 
    ... 
    return ... 

是否有更好的方法来构建代码以确保在任务之前加载配置?

请您参考如下方法:

配置序列化器时,还应指定内容类型、任务序列化器和结果序列化器。

app = Celery( 
    broker='amqp://guest@localhost//', 
    backend='amqp://', 
    include=['proj.tasks'], 
 
    task_serializer='json', 
    result_serializer='json', 
    accept_content = ['application/json'], 
)