python - twisted.protocols.ftp.FTPClient 和 Deferreds

标签 python ftp twisted deferred

像大多数人一样,我花了一段时间才习惯使用 Deferreds,但我正在慢慢地做到这一点。但是,我不清楚如何在使用 Twisted 的 FTP 模块时处理响应,然后使用处理后的响应调用另一个 FTP 命令。我正在使用 example FTP code作为我的出发点。

我想连接到 FTP 服务器,获取所有顶级目录,然后输入每个目录并下载所有文件。

首先我连接:

creator = ClientCreator(reactor, FTPClient, config.opts['username'], config.opts['password'], passive=config.opts['passive'])
creator.connectTCP(config.opts['host'], config.opts['port']).addCallback(connectionMade).addErrback(connectionFailed)
reactor.run()

它连接成功,因此我的 connectionMade 函数被调用:

def connectionMade(ftpClient):
    # Get a detailed listing of the current directory
    fileList = FTPFileListProtocol()
    d = ftpClient.list('.', fileList)
    d.addCallbacks(getSortedDirectories, fail, callbackArgs=(fileList,))
    d.addCallback(enterDirs)

如您所见,我排队 getSortedDirectories,然后 enterDirs

def getSortedDirectories(result, fileListProtocol):
    # Go through all directories from greatest to least
    dirs = [directory for directory in sorted(fileListProtocol.files, reverse=True) if directory['filetype'] == 'd']
    return dirs

我的问题是,如何浏览 enterDirs 中的目录?

def enterDirs(dirs):
    for directory in dirs:
        print "We'd be entering '%s' now." % directory

我是否应该将 ftpClient 传递给 enterDirs,就像将 fileList 传递给 getSortedDirectories 一样,然后发出下载请求?

d.addCallback(enterDirs, callbackArgs=(ftpClient,))

def enterDirs(dirs, ftpClient):
    for directory in dirs:
        fileList = FTPFileListProtocol()
        d = ftpClient.list(directory, fileList)
        d.addCallbacks(downloadFiles, fail, callbackArgs=(directory, fileList, ftpClient))

def downloadFiles(result, directory, fileListProtocol, ftpClient):
    for f in fileListProtocol.files if f.filetype == '-':
        fileConsumer = FileConsumer()
        ftpClient.retrieveFile(os.path.join(directory['filename'], file['filename']), fileConsumer)

这是最好的方法吗?

最佳答案

Should I be passing ftpClient to enterDirs like fileList is passed to getSortedDirectories and then make my download requests? ... Is this the best approach?

我确实认为将客户端对象作为参数显式传递确实是最好的方法——大多数情况下,它是备用且优雅的。主要的替代方案是编写一个类并将客户端对象存储到实例变量中,这似乎有点麻烦;在我看来,为此目的使用全局变量是最不理想的选择(全局变量越少越好!-)。

关于python - twisted.protocols.ftp.FTPClient 和 Deferreds,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3313663/

相关文章:

Java FTPClient listFiles返回带有unicode路径的空结果

javascript - 在 FTP 服务器上上传 NodeJS : Error

php - 无法使用 php 连接到外部 FTPS 服务器

python - 我应该如何使用 Twisted 构建批处理管道?

Python - 如何使用 Conch 创建虚拟 SSH 服务器

javascript - 动态生成表时,如何使用 Python BeautifulSoup 对表信息进行 scape?

python - 在 Python 中下载之前获取文件的大小

python - 使用 NLTK 查找事物列表(例如河流列表)

python - 已安装 libusb - 但未找到 pyUSB 后端

python - Python Twisted SSL 的证书生成