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

(yzsuai) #1

usually translated to + characters as well. We can often get away without manually
translating most non-ASCII characters when sending paths explicitly (in typed URLs).
But as we saw earlier, we sometimes need to be careful to escape characters (e.g., &)
that have special meaning within URL strings with urllib.parse tools.


Handling client path formats


In the end, the putfile.py script stores the uploaded file on the server within a hardcoded
uploaddir directory, under the filename at the end of the file’s path on the client (i.e.,
less its client-side directory path). Notice, though, that the splitpath function in this
script needs to do extra work to extract the base name of the file on the right. Some
browsers may send up the filename in the directory path format used on the client
machine; this path format may not be the same as that used on the server where the
CGI script runs. This can vary per browser, but it should be addressed for portability.


The standard way to split up paths, os.path.split, knows how to extract the base
name, but only recognizes path separator characters used on the platform on which it
is running. That is, if we run this CGI script on a Unix machine, os.path.split chops
up paths around a / separator. If a user uploads from a DOS or Windows machine,
however, the separator in the passed filename is \, not /. Browsers running on some
Macintosh platforms may send a path that is more different still.


To handle client paths generically, this script imports platform-specific path-processing
modules from the Python library for each client it wishes to support, and tries to split
the path with each until a filename on the right is found. For instance, posixpath handles
paths sent from Unix-style platforms, and ntpath recognizes DOS and Windows client
paths. We usually don’t import these modules directly since os.path.split is auto-
matically loaded with the correct one for the underlying platform, but in this case, we


Figure 15-36. Verifying putfile with getfile—response


1224 | Chapter 15: Server-Side Scripting

Free download pdf