【问题标题】:How to use validators on FileField content如何在 FileField 内容上使用验证器
【发布时间】:2017-10-01 21:12:31
【问题描述】:

在我的模型中,我想使用验证器来分析文件的内容,我想不通的是如何访问文件的内容来解析它,因为文件尚未保存(这很好)当验证器运行时。

我不明白如何将传递给验证器的value 中的数据放入一个文件中(我假设我应该使用tempfile),以便我可以打开它并评估数据。

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

在 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()])

感谢您的帮助!

【问题讨论】:

    标签: django django-models django-validation


    【解决方案1】:

    看看ImageField 的实现是如何做到的:

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

    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
    

    【讨论】:

      【解决方案2】:

      不需要tempfile:

      传递给FileField 验证器的valueFieldFile 的一个实例,正如OP 已经提到的那样。

      在底层,FieldFile 实例可能已经使用了tempfile.NamedTemporaryFile (source),或者它可能包装了in-memory file,但您不必担心:

      要“评估数据”,您可以简单地将 FieldFile 实例视为任何 Python file object

      例如,您可以对其进行迭代:

      def my_filefield_validator(value):
          # note that value is a FieldFile instance
          for line in value:
              ... # do something with line
      

      documentation 说:

      除了继承自File 的API(如read()write())之外,FieldFile 还包括几个可用于与底层文件交互的方法:...

      FieldFile 类提供

      ...Storage.open() 方法结果的包装器,它可能是 File 对象,也可能是 File API 的自定义存储实现。

      这种底层文件实现的一个例子是InMemoryUploadedFiledocs/source

      同样来自docs

      File 类是 Python 文件对象的薄包装器,并添加了一些特定于 Django 的附加功能

      另请注意:class-based validators vs function-based validators

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-02-05
        • 1970-01-01
        • 2016-11-30
        • 2014-12-07
        • 2012-01-23
        • 2017-01-03
        • 1970-01-01
        相关资源
        最近更新 更多