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

(yzsuai) #1

conn = connectFtp(cf)
cleanRemotes(cf, conn)
uploadAll(cf, conn)


Not only is the upload script simpler now because it reuses common code, but it will
also inherit any changes made in the download module. For instance, the isTextKind
function was later augmented with code that adds the .pyw extension to mimetypes
tables (this file type is not recognized by default); because it is a shared function, the
change is automatically picked up in the upload program, too.


This script and the one it imports achieve the same goals as the originals, but changing
them for easier code maintenance is a big deal in the real world of software development.
The following, for example, downloads the site from one server and uploads to another:


C:\...\PP4E\Internet\Ftp\Mirror> python downloadflat_modular.py test
Clean target directory 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> python uploadflat_modular.py test
Clean target directory 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.

Refactoring with classes


The function-based approach of the last two examples addresses the redundancy issue,
but they are perhaps clumsier than they need to be. For instance, their cf configuration
options object provides a namespace that replaces global variables and breaks cross-
file dependencies. Once we start making objects to model namespaces, though, Py-
thon’s OOP support tends to be a more natural structure for our code. As one last twist,
Example 13-14 refactors the FTP code one more time in order to leverage Python’s class
feature.


Example 13-14. PP4E\Internet\Ftp\Mirror\ftptools.py


#!/bin/env python
"""
##############################################################################
use FTP to download or upload all files in a single directory from/to a
remote site and directory; this version has been refactored to use classes
and OOP for namespace and a natural structure; we could also structure this
as a download superclass, and an upload subclass which redefines the clean
and transfer methods, but then there is no easy way for another client to


888 | Chapter 13: Client-Side Scripting

Free download pdf