Django(音频)文件验证 [英] Django (audio) File Validation

查看:199
本文介绍了Django(音频)文件验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试一个允许用户上传音频文件的网站。我已阅读每一个文档,我可以得到我的手,但找不到很多关于验证文件

I'm experimenting with a site that will allow users to upload audio files. I've read every doc that I can get my hands on but can't find much about validating files.

完成以前任何类型的任何文件验证),并试图弄清楚。有人可以握住我的手,告诉我需要知道什么?

Total newb here (never done any file validation of any kind before) and trying to figure this out. Can someone hold my hand and tell me what I need to know?

一如既往,谢谢你提前。

As always, thank you in advance.

推荐答案

您要在将文件写入磁盘之前验证文件。上传文件时,表单得到验证,然后将上传的文件传递给处理器/方法,该处理程序/方法处理实际写入服务器上的磁盘。因此,在这两个操作之间,您需要执行一些自定义验证,以确保它是一个有效的音频文件。

You want to validate the file before it gets written to disk. When you upload a file, the form gets validated then the uploaded file gets passed to a handler/method that deals with the actual writing to the disk on your server. So in between these two operations, you want to perform some custom validation to make sure it's a valid audio file

您可以:


  • 检查文件是否小于一定大小(良好做法)

  • 然后检查提交的文件是否具有某种内容类型即一个音频文件)

    • 这是非常无用的,因为有人可以轻易地欺骗它


    • 这样也很无用

    (我还没有测试过这个代码)

    (I haven't tested this code)

    models.py

    class UserSong(models.Model):
        title = models.CharField(max_length=100)
        audio_file = models.FileField()
    

    forms.py

    class UserSongForm(forms.ModelForm):
         # Add some custom validation to our file field
         def clean_audio_file(self):
             file = self.cleaned_data.get('audio_file',False):
             if file:
                 if file._size > 4*1024*1024:
                       raise ValidationError("Audio file too large ( > 4mb )")
                 if not file.content-type in ["audio/mpeg","audio/..."]:
                       raise ValidationError("Content-Type is not mpeg")
                 if not os.path.splitext(file.name)[1] in [".mp3",".wav" ...]:
                       raise ValidationError("Doesn't have proper extension")
                 # Here we need to now to read the file and see if it's actually 
                 # a valid audio file. I don't know what the best library is to 
                 # to do this
                 if not some_lib.is_audio(file.content):
                       raise ValidationError("Not a valid audio file")
                 return file
             else:
                 raise ValidationError("Couldn't read uploaded file")
    

    views.py
    from utils import handle_uploaded_file

    views.py from utils import handle_uploaded_file

    def upload_file(request):
        if request.method == 'POST':
            form = UserSongForm(request.POST, request.FILES)
            if form.is_valid():
                # If we are here, the above file validation has completed
                # so we can now write the file to disk
                handle_uploaded_file(request.FILES['file'])
                return HttpResponseRedirect('/success/url/')
        else:
            form = UploadFileForm()
        return render_to_response('upload.html', {'form': form})
    

    utils.py

    # from django's docs
    def handle_uploaded_file(f):
        ext = os.path.splitext(f.name)[1]
        destination = open('some/file/name%s'%(ext), 'wb+')
        for chunk in f.chunks():
            destination.write(chunk)
        destination.close()
    

    https://docs.djangoproject.com/en/dev/topics/http/file-uploads/#file-uploads
    https://docs.djangoproject.com/en/dev/ref/forms/fields/#filefield
    https://docs.djangoproject.com/en/dev/ref/files/file/#django.core.files.File

    这篇关于Django(音频)文件验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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