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

(yzsuai) #1

Displaying Arbitrary Server Files on the Client


Almost immediately after writing the languages source code viewer script in the pre-
ceding example, it occurred to me that it wouldn’t be much more work, and would be
much more useful, to write a generic version—one that could use a passed-in filename
to display any file on the site. It’s a straightforward mutation on the server side; we
merely need to allow a filename to be passed in as an input. The getfile.py Python script
in Example 15-27 implements this generalization. It assumes the filename is either
typed into a web page form or appended to the end of the URL as a parameter. Re-
member that Python’s cgi module handles both cases transparently, so there is no code
in this script that notices any difference.


Example 15-27. PP4E\Internet\Web\cgi-bin\getfile.py


#!/usr/bin/python
"""
##################################################################################
Display any CGI (or other) server-side file without running it. The filename can
be passed in a URL param or form field (use "localhost" as the server if local):


http://servername/cgi-bin/getfile.py?filename=somefile.html
http://servername/cgi-bin/getfile.py?filename=cgi-bin\somefile.py
http://servername/cgi-bin/getfile.py?filename=cgi-bin%2Fsomefile.py


Users can cut-and-paste or "View Source" to save file locally. On IE, running the
text/plain version (formatted=False) sometimes pops up Notepad, but end-lines are
not always in DOS format; Netscape shows the text correctly in the browser page
instead. Sending the file in text/HTML mode works on both browsers--text is
displayed in the browser response page correctly. We also check the filename here
to try to avoid showing private files; this may or may not prevent access to such
files in general: don't install this script if you can't otherwise secure source!
##################################################################################
"""


import cgi, os, sys
formatted = True # True=wrap text in HTML
privates = ['PyMailCgi/cgi-bin/secret.py'] # don't show these


try:
samefile = os.path.samefile # checks device, inode numbers
except:
def samefile(path1, path2): # not available on Windows
apath1 = os.path.abspath(path1).lower() # do close approximation
apath2 = os.path.abspath(path2).lower() # normalizes path, same case
return apath1 == apath2


html = """


Getfile response

Source code for: '%s'




%s


"""
Transferring Files to Clients and Servers | 1211
Free download pdf