[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

os.chmod(srvrname, 0o666) # make writable: owned by 'nobody'
return filetext, srvrname


def main():
if not 'clientfile' in form:
print(html % 'Error: no file was received')
elif not form['clientfile'].filename:
print(html % 'Error: filename is missing')
else:
fileinfo = form['clientfile']
try:
filetext, srvrname = saveonserver(fileinfo)
except:
errmsg = '

Error

%s

%s' % tuple(sys.exc_info()[:2])
print(html % errmsg)
else:
print(goodhtml % (cgi.escape(fileinfo.filename),
cgi.escape(srvrname),
cgi.escape(filetext)))
main()


Within this script, the Python-specific interfaces for handling uploaded files are em-
ployed. They aren’t very new, really; the file comes into the script as an entry in the
parsed form object returned by cgi.FieldStorage, as usual; its key is clientfile, the
input control’s name in the HTML page’s code.


This time, though, the entry has additional attributes for the file’s name on the client.
Moreover, accessing the value attribute of an uploaded file input object will automat-
ically read the file’s contents all at once into a string on the server. For very large files,
we can instead read line by line (or in chunks of bytes) to avoid overflowing memory
space. Internally, Python’s cgi module stores uploaded files in temporary files auto-
matically; reading them in our script simply reads from that temporary file. If they are
very large, though, they may be too long to store as a single string in memory all at once.


For illustration purposes, the script implements either scheme: based on the setting of
the loadtextauto global variable, it either asks for the file contents as a string or reads
it line by line. In general, the CGI module gives us back objects with the following
attributes for file upload controls:


filename
The name of the file as specified on the client


file
A file object from which the uploaded file’s contents can be read


value
The contents of the uploaded file (read from the file on attribute access)


Additional attributes are not used by our script. Files represent a third input field object;
as we’ve also seen, the value attribute is a string for simple input fields, and we may
receive a list of objects for multiple-selection controls.


Transferring Files to Clients and Servers | 1221
Free download pdf