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

(yzsuai) #1

loadtextauto = False # True=read file at once
uploaddir = './uploads' # dir to store files


sys.stderr = sys.stdout # show error msgs
form = cgi.FieldStorage() # parse form data
print("Content-type: text/html\n") # with blank line
if debugmode: cgi.print_form(form) # print form fields


html templates


html = """


Putfile response page

Putfile response page


%s
"""

goodhtml = html % """


Your file, '%s', has been saved on the server as '%s'.

An echo of the file's contents received and saved appears below.



%s



"""

process form data


def splitpath(origpath): # get file at end
for pathmodule in [posixpath, ntpath, macpath]: # try all clients
basename = pathmodule.split(origpath)[1] # may be any server
if basename != origpath:
return basename # lets spaces pass
return origpath # failed or no dirs


def saveonserver(fileinfo): # use file input form data
basename = splitpath(fileinfo.filename) # name without dir path
srvrname = os.path.join(uploaddir, basename) # store in a dir if set
srvrfile = open(srvrname, 'wb') # always write bytes here
if loadtextauto:
filetext = fileinfo.value # reads text into string
if isinstance(filetext, str): # Python 3.1 hack
filedata = filetext.encode()
srvrfile.write(filedata) # save in server file
else: # else read line by line
numlines, filetext = 0, '' # e.g., for huge files
while True: # content always str here
line = fileinfo.file.readline() # or for loop and iterator
if not line: break
if isinstance(line, str): # Python 3.1 hack
line = line.encode()
srvrfile.write(line)
filetext += line.decode() # ditto
numlines += 1
filetext = ('[Lines=%d]\n' % numlines) + filetext
srvrfile.close()


1220 | Chapter 15: Server-Side Scripting

Free download pdf