如何在FileField内容上使用验证器 [英] How to use validators on FileField content

查看:46
本文介绍了如何在FileField内容上使用验证器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的模型中,我想使用验证器来分析文件的内容,我无法弄清楚的是如何访问文件的内容以通过文件进行解析,因为文件尚未保存(验证程序正在运行时,这很好.

In my model, I want to use a validator to analyze the content of a file, the thing I can not figure out is how to access the content of the file to parse through it as the file has not yet been saved (which is good) when the validators are running.

我不了解如何将传递给验证器的 value 中的数据获取到文件中(我假设我应该使用 tempfile ),因此我可以打开并评估数据.

I'm not understanding how to get the data from the value passed to the validator into a file (I assume I should use tempfile) so I can then open it and evaluate the data.

这是一个简化的示例,在我的真实代码中,我想打开文件并使用csv对其进行评估.

Here's a simplified example, in my real code, I want to open the file and evaluate it with csv.

在Models.py

in Models.py

class ValidateFile(object):
    ....
    def __call__(self, value):
        # value is the fieldfile object but its not saved
        # I believe I need to do something like:
        temp_file = tempfile.TemporaryFile()
        temp_file.write(value.read())
        # Check the data in temp_file
    ....

class MyItems(models.Model):
    data = models.FileField(upload_to=get_upload_path,
                            validators=[FileExtensionValidator(allowed_extensions=['cv']),
                            ValidateFile()])

感谢您的帮助!

推荐答案

所以您的 ValidateFile 类可能是这样的:

So your ValidateFile class may be something like this:

from io import BytesIO

class ValidateFile(object):

    def __call__(self, value):
        if value is None:
            #do something when None
            return None

        if hasattr(value, 'temporary_file_path'):
            file = value.temporary_file_path()
        else:
            if hasattr(value, 'read'):
                file = BytesIO(value.read())
            else:
                file = BytesIO(value['content'])

        #Now validate your file

这篇关于如何在FileField内容上使用验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆