Scan uploaded file for viruses with clamav

A clean_&lt;fieldname&gt;() method in a form subclass as described here. Scans the field named file for viruses.

My version of python-clamav does not support scanning of buffers. That is why I go through the hassle of saving the file to a temporary one.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

defclean_file(self):file=self.cleaned_data.get('file','')#check a file in form for virusesiffile:fromtempfileimportmkstempimportpyclamavimportostmpfile=mkstemp()[1]f=open(tmpfile,'wb')f.write(file.content)f.close()isvirus,name=pyclamav.scanfile(tmpfile)os.unlink(tmpfile)ifisvirus:raiseforms.ValidationError( \
"WARNING! Virus \"%s\" was detected in this file. \ Check your system."%name)returnfile