Django将excel文件发送到Celery Task。 InMemoryUploadedFile错误

时间:2019-06-25 07:43:34

标签: django celery

我有后台进程-读取excel文件并从该文件保存数据。我需要在后台进程中读取文件。但是我有错误InMemoryUploadedFile。 我的代码

def create(self, validated_data):
   company = ''
   file_type = ''
   email = ''
   file = validated_data['file']

            import_data.delay(file=file,
                                       company=company,
                                       file_type=file_type,
                                       email=email)

我的方法看起来像

@app.task
def import_data(
        file,
        company,
        file_type,
        email):
// some code

但是我有错误InMemoryUploadedFile

我如何将文件正确无误地发送到地下室?

2 个答案:

答案 0 :(得分:2)

当您延迟任务时,Celery将尝试序列化其中包含文件的参数。

文件,尤其是内存中的文件无法序列化。

因此,要解决此问题,您必须保存文件并将文件路径传递给延迟的函数,然后在该位置读取文件并进行计算。

答案 1 :(得分:0)

Celery 不知道如何序列化文件对象等复杂对象。但是,这可以很容易地解决。我所做的是将文件编码/解码为其 Base64 字符串表示形式。这允许我直接通过 Celery 发送文件。

下面的例子展示了如何(我有意将每个转换分开放置,尽管这可以以更pythonic的方式排列):

import base64
import tempfile

# (Django, HTTP server)
file = request.FILES['files'].file
file_bytes = file.read()
file_bytes_base64 = base64.b64encode(file_bytes)
file_bytes_base64_str = file_bytes_base64.decode('utf-8') # this is a str

# (...send string through Celery...)

# (Celery worker task)
file_bytes_base64 = file_bytes_base64_str.encode('utf-8')
file_bytes = base64.b64decode(file_bytes_base64)

# Write the file to a temporary location, deletion is guaranteed
with tempfile.TemporaryDirectory() as tmp_dir:
    tmp_file = os.path.join(tmp_dir, 'something.zip')
    with open(tmp_file, 'wb') as f:
        f.write(file_bytes)
    # Process the file

这对于大文件来说可能效率低下,但对于中小型临时文件来说它变得非常方便。