我编写了一个自定义文件字段AudioFileField。为此,我创建了一个检查文件是否真的是一个有效的audiofile。为了能够做到这一点,我使用sox命令行工具,所以我必须首先在磁盘上创建一个文件。由于sox依赖于后缀来进行验证,我需要使用原始后缀(而不是.upload)编写自己的TemporaryUploadedAudioFile:
class TemporaryUploadedAudioFile(TemporaryUploadedFile):
"""
A file uploaded to a temporary location (i.e. stream-to-disk).
"""
def __init__(self, name, content_type, size, charset, suffix='.upload'):
"""
The init method overrides the name creation to allow passing
an extension, so that sox is able to test the file
"""
if settings.FILE_UPLOAD_TEMP_DIR:
file = tempfile.NamedTemporaryFile(suffix=suffix,
dir=settings.FILE_UPLOAD_TEMP_DIR)
else:
file = tempfile.NamedTemporaryFile(suffix=suffix)
super(TemporaryUploadedFile, self).__init__(file, name, content_type, size, charset)
我用这个文件在AudioFileForm to_python方法中进行音频验证:
def to_python(self, data):
"""
checks that the file-upload field data contains a valid audio file.
"""
f = super(AudioFileForm, self).to_python(data)
if f is None:
return None
# get the file suffix, sox needs this to be able to test the file
suffix = os.path.splitext(data.name)[1]
# We need to get a temporary file for sox. Even if we allready have a temporary
# file, we have to create a new one ending with the correct suffix
file = TemporaryUploadedAudioFile(data.name, data.content_type, 0, data.charset,suffix = suffix)
with open(file.temporary_file_path(), 'w') as f:
f.write(data.read())
# Do the validation of the audiofile.
filetype=subprocess.Popen([sox,'--i','-t','%s'%file.temporary_file_path()], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
filetype=filetype.communicate()[0]
filetype=filetype.replace('\n','')
if not filetype in ['wav','aiff','flac']:
raise forms.ValidationError('Not a valid audiofile (valid are: aif, flac & wav | 16 or 24 bit | 44.1 or 48 kHz)')
return data
现在发生了奇怪的事情:这就像开发服务器上的魅力一样,但是当我切换到apache2 / mod_wsgi时它就会停止工作。 sox返回一个错误,告诉我文件丢失了。
我已经检查了权限,生产服务器上的tmp-location是/ tmp,所有权限都在那里被授予(777)。还有什么可以在这里发生?
答案 0 :(得分:0)
已知mod-wsgi在标准输出方面存在问题,而且这个子进程与django有关。在stackoverflow.com中已经有很多问题得到解答。
快速Google搜索可以为您提供帮助!