我最近在我的一个应用程序中集成了 celery(更具体地说是django-celery)。我在应用程序中有一个如下所示的模型。
class UserUploadedFile(models.Model)
original_file = models.FileField(upload_to='/uploads/')
txt = models.FileField(upload_to='/uploads/')
pdf = models.FileField(upload_to='/uploads/')
doc = models.FileField(upload_to='/uploads/')
def convert_to_others(self):
# Code to convert the original file to other formats
现在,一旦用户上传文件,我想将原始文件转换为txt、pdf和doc格式。调用convert_to_others
方法是一个比较昂贵的过程,因此我计划使用celery异步处理它。因此,我编写了一个简单的celery任务,如下所示。
@celery.task(default_retry_delay=bdev.settings.TASK_RETRY_DELAY)
def convert_ufile(file, request):
"""
This task method would call a UserUploadedFile object's convert_to_others
method to do the file conversions.
The best way to call this task would be doing it asynchronously
using apply_async method.
"""
try:
file.convert_to_others()
except Exception, err:
# If the task fails log the exception and retry in 30 secs
log.LoggingMiddleware.log_exception(request, err)
convert_ufile.retry(exc=err)
return True
并且接下来按以下方式调用任务:
ufile = get_object_or_404(models.UserUploadedFiles, pk=id)
tasks.convert_ufile.apply_async(args=[ufile, request])
现在当调用apply_async
方法时,会引发以下异常:
PicklingError: Can't pickle <type 'cStringIO.StringO'>: attribute lookup cStringIO.StringO failed
我认为这是因为 celery(默认情况下)使用 pickle
库来序列化数据,而 pickle 无法序列化二进制文件。
问题
是否有其他的序列化器可以自行序列化二进制文件?如果没有,如何使用默认的 pickle
序列化器来序列化二进制文件?