<p>使用@hasanatkazmi(在一个扭曲的应用程序中使用)的答案,我得到了如下信息:</p>
<pre><code>#!/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')
</code></pre>
<p>请注意,该文件并非总是由<strong>cgi</strong>模块创建的。根据这些<code>cgi.py</code>行,只有当内容超过1000字节时才会创建:</p>
<pre><code>if self.__file.tell() + len(line) > 1000:
self.file = self.make_file('')
</code></pre>
<p>因此,您必须检查文件是否是通过查询自定义类“<code>path</code>字段创建的,如下所示:</p>
<pre><code>if file_field.path:
# Using an already created file...
else:
# Creating a temporary named file to store the content.
import tempfile
with tempfile.NamedTemporaryFile("w+b", delete=False) as f:
f.write(file_field.value)
# You can save the 'f.name' field for later usage.
</code></pre>
<p>如果还为字段设置了<code>Content-Length</code>,那么该文件也应该由<strong>cgi</strong>创建。</p>
<p>就这样。这样,您就可以预测地存储文件,从而减少应用程序的内存使用量。</p>