else:
print('Usage: ftptools.py ["download" | "upload"] [localdir]')
In fact, this last mutation combines uploads and downloads into a single file, because
they are so closely related. As before, common code is factored into methods to avoid
redundancy. New here, the instance object itself becomes a natural namespace for
storing configuration options (they become self attributes). Study this example’s code
for more details of the restructuring applied.
Again, this revision runs the same as our original site download and upload scripts; see
its self-test code at the end for usage details, and pass in a command-line argument to
specify “download” or “upload.” We haven’t changed what it does, we’ve refactored
it for maintainability and reuse:
C:\...\PP4E\Internet\Ftp\Mirror> ftptools.py download test
Clean target dir first?
Password for lutz on home.rmi.net:
connecting...
downloading 2004-longmont-classes.html to test\2004-longmont-classes.html as text
...lines omitted...
downloading relo-feb010-index.html to test\relo-feb010-index.html as text
Done: 297 files downloaded.
C:\...\PP4E\Internet\Ftp\Mirror> ftptools.py upload test
Clean target dir first?
Password for lutz on learning-python.com:
connecting...
uploading test\2004-longmont-classes.html to 2004-longmont-classes.html as text
...lines omitted...
uploading test\zopeoutline.htm to zopeoutline.htm as text
Done: 297 files uploaded.
Although this file can still be run as a command-line script like this, its class is really
now a package of FTP tools that can be mixed into other programs and reused. By
wrapping its code in a class, it can be easily customized by redefining its methods—its
configuration calls, such as getlocaldir, for example, may be redefined in subclasses
for custom scenarios.
Perhaps most importantly, using classes optimizes code reusability. Clients of this file
can both upload and download directories by simply subclassing or embedding an
instance of this class and calling its methods. To see one example of how, let’s move
on to the next section.
Transferring Directory Trees with ftplib
Perhaps the biggest limitation of the website download and upload scripts we just met
is that they assume the site directory is flat (hence their names). That is, the preceding
scripts transfer simple files only, and none of them handle nested subdirectories within
the web directory to be transferred.
892 | Chapter 13: Client-Side Scripting