You need to enable JavaScript to run this app. Celery任务传入函数参数触发Pickle编码错误的修复咨询
优惠活动
大模型
产品
解决方案
定价
更多

Celery任务传入函数参数触发Pickle编码错误的修复咨询

复现场景与报错描述

开发了一款应用,希望基于Celery实现多进程处理能力,每次运行相关逻辑都会触发报错,因此搭建了最简复现场景验证任务执行流程。

各模块代码

Celery配置 celery_module/my_celery.py

from celery import Celery

app1 = Celery('cel_tasks',
              broker='redis://localhost:6379/0',
              backend='redis://localhost',
              include=['celery_module.tasks.my_tasks'],
              )

app1.conf.update(
    task_serializer='pickle',
    accept_content=['pickle', 'json']
)

任务定义 celery_module/tasks/my_tasks.py

from celery_module.my_celery import *

@app1.task
def do_simple(func):
    return func()*10

任务触发封装 src/celery_launch.py

import celery_module.tasks.my_tasks
from src.func_serialization import deserialize_function

def start_simple(des_func):
    des_func = deserialize_function(des_func)
    new_func = celery_module.tasks.my_tasks.do_simple.delay(des_func)
    return new_func

函数序列化/反序列化逻辑 src/func_serialization.py

import marshal
import types

def serialize_function(function):
    serialized_func = marshal.dumps(function.__code__)
    return serialized_func

def deserialize_function(function_obj):
    func_repr = marshal.loads(function_obj)
    deserialized_function = types.FunctionType(func_repr, globals())
    return deserialized_function

业务入口 src/app.py

from src.celery_launch import start_simple
from src.func_serialization import serialize_function

@staticmethod
def simple_func():
    x = 5
    return x*10

def some_function(self):
    # 应用原有业务测试入口,可直接从UI调用
    start_simple(serialize_function(self.simple_func))

调用链路与报错信息

完整调用流程:

  • 从app.py调用some_function,将需要传入任务的simple_func通过marshal序列化得到字节串
  • 传入start_simple,在start_simple内部反序列化得到simple_func实例
  • 将反序列化后的函数作为参数传入Celery任务do_simple执行

运行时抛出报错:

kombu.exceptions.EncodeError: Can't pickle <function simple_func at 0x7f3066806d30>: attribute lookup simple_func on src.func_serialization failed

根因分析

Celery当前配置使用pickle序列化任务参数,而pickle序列化函数对象的逻辑并非编码函数本身的代码,仅会记录函数的模块路径+函数名标识,反序列化时会直接到对应模块的全局命名空间查找该函数。

当前流程中,deserialize_function用types.FunctionType创建的动态函数,__module__默认是src.func_serialization(因为用了当前模块的globals()),但该模块的全局命名空间里根本不存在名为simple_func的属性,pickle打包参数时找不到对应引用,直接报错。

另外流程本身存在冗余:本地反序列化函数再传给Celery没有意义,反而引入了序列化问题。


修复方案(改动最小,适配现有逻辑)

直接跳过本地反序列化的步骤,将marshal序列化后的字节串直接传给Celery任务,在任务内部完成反序列化:

改动1:修改任务定义 celery_module/tasks/my_tasks.py

from celery_module.my_celery import *
from src.func_serialization import deserialize_function

@app1.task
def do_simple(serialized_func):
    # 任务内部完成函数反序列化
    func = deserialize_function(serialized_func)
    return func()*10

改动2:修改任务触发封装 src/celery_launch.py

移除本地反序列化的逻辑,直接传递原始序列化字节串:

import celery_module.tasks.my_tasks

def start_simple(serialized_func):
    # 不再本地反序列化,直接传字节串给任务
    new_func = celery_module.tasks.my_tasks.do_simple.delay(serialized_func)
    return new_func

注意1:字节串是pickle原生支持的序列化类型,不会触发函数序列化的查找逻辑。
注意2:marshal序列化的函数代码仅支持相同Python版本的运行时,需要保证调用端和Celery worker的Python版本完全一致。


备选方案(如果必须在本地反序列化函数)

如果业务流程要求必须在调用端反序列化函数,需要手动把动态生成的函数注册到对应模块的全局命名空间,并给函数设置正确的标识:

修改src/func_serialization.py的deserialize_function:

import marshal
import types
import sys

def deserialize_function(function_obj, func_name="dynamic_func", module_name=None):
    func_repr = marshal.loads(function_obj)
    # 默认注册到当前模块
    module_name = module_name or __name__
    target_module = sys.modules[module_name]
    # 手动设置函数的属性,符合pickle的查找要求
    deserialized_function = types.FunctionType(func_repr, target_module.__dict__, name=func_name)
    # 把函数注册到目标模块的全局命名空间,供pickle查找
    setattr(target_module, func_name, deserialized_function)
    return deserialized_function

该方案需要管控动态函数的命名,避免冲突,维护成本更高,优先推荐第一种方案。


内容的提问来源于stack exchange,提问作者Slobjo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.07 10:06:04