Using @hasanatkazmi's answer (used in the Twisted app), I got something like:
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # -*- indent: 4 spc -*- import sys import cgi import tempfile class PredictableStorage(cgi.FieldStorage): def __init__(self, *args, **kwargs): self.path = kwargs.pop('path', None) cgi.FieldStorage.__init__(self, *args, **kwargs) def make_file(self, binary=None): if not self.path: file = tempfile.NamedTemporaryFile("w+b", delete=False) self.path = file.name return file return open(self.path, 'w+b')
It should be warned that the file is not always created by the cgi module. According to these cgi.py lines cgi.py it will be created only if the content exceeds 1000 bytes:
if self.__file.tell() + len(line) > 1000: self.file = self.make_file('')
So, you should check if the file was really created with the request in the field of the user class path , for example:
if file_field.path:
If the Content-Length parameter is also set for a field that seems rare, the file must also be created using cgi .
What is it. This way you can save the file predictably by reducing the memory usage of your application.
Vladius
source share