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

(yzsuai) #1

For more urllib download examples, see the section on HTTP later in this chapter,
and the server-side examples in Chapter 15. As we’ll see in Chapter 15, in bigger terms,
tools like the urllib.request urlopen function allow scripts to both download remote
files and invoke programs that are located on a remote server machine, and so serves
as a useful tool for testing and using web sites in Python scripts. In Chapter 15, we’ll
also see that urllib.parse includes tools for formatting (escaping) URL strings for safe
transmission.


FTP get and put Utilities


When I present the ftplib interfaces in Python classes, students often ask why pro-
grammers need to supply the RETR string in the retrieval method. It’s a good
question—the RETR string is the name of the download command in the FTP protocol,
but ftplib is supposed to encapsulate that protocol. As we’ll see in a moment, we have
to supply an arguably odd STOR string for uploads as well. It’s boilerplate code that
you accept on faith once you see it, but that begs the question. You could propose a
patch to ftplib, but that’s not really a good answer for beginning Python students, and
it may break existing code (the interface is as it is for a reason).


Perhaps a better answer is that Python makes it easy to extend the standard library
modules with higher-level interfaces of our own—with just a few lines of reusable code,
we can make the FTP interface look any way we want in Python. For instance, we could,
once and for all, write utility modules that wrap the ftplib interfaces to hide the RETR
string. If we place these utility modules in a directory on PYTHONPATH, they become just
as accessible as ftplib itself, automatically reusable in any Python script we write in
the future. Besides removing the RETR string requirement, a wrapper module could
also make assumptions that simplify FTP operations into single function calls.


For instance, given a module that encapsulates and simplifies ftplib, our Python fetch-
and-play script could be further reduced to the script shown in Example 13-3—essen-
tially just two function calls plus a password prompt, but with a net effect exactly like
Example 13-1 when run.


Example 13-3. PP4E\Internet\Ftp\getone-modular.py


#!/usr/local/bin/python
"""
A Python script to download and play a media file by FTP.
Uses getfile.py, a utility module which encapsulates FTP step.
"""


import getfile
from getpass import getpass
filename = 'monkeys.jpg'


fetch with utility


getfile.getfile(file=filename,
site='ftp.rmi.net',


860 | Chapter 13: Client-Side Scripting

Free download pdf