我最近在我的一个应用程序中集成了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.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
序列化程序序列化二进制文件?