flask + ftplib基本应用程序

时间:2012-12-14 23:01:18

标签: python flask

app = Flask(__name__)
@app.route("/")
def hello():
    address="someserver"
    global FTP
    ftp = FTP(address)
    ftp.login()
    return ftp.retrlines("LIST")

if __name__ == "__main__":
    app.run()

...这给了我以下输出:

226-Options: -l 226 1 matches total

问题是 - 为什么不打印后退的输出,我该怎么做?

1 个答案:

答案 0 :(得分:2)

ftplib.FTP类的文档说retrlines采用可选回调 - 如果没有提供回调“默认回调将该行打印到sys.stdout。”这意味着方法retrlines实际上不返回提供的数据 - 它只是在接收到每个行时将其传递给可传递给它的可调用对象。这为您提供了几个选项:

  1. 传入一个可以存储多次被调用结果的可调用对象:

    def fetchlines(line=None):
        if line is not None:
            # As long as we are called with a line
            # store the line in the array we added to this function
            fetchlines.lines.append(line)
        else:
            # When we are called without a line
            # we are retrieving the lines
            # Truncate the array after copying it
            # so we can re-use this function
            lines = fetchlines.lines[:]
            fetchlines.lines = []
            return lines
    
    fetchlines.lines = []
    
    @app.route("/")
    def hello():
        ftp = FTP("someaddress")
        ftp.login()
        ftp.dir(fetchlines)
        lines = fetchlines()
        return "<br>".join(lines)
    
  2. sys.stdout替换为类似文件的对象(例如,来自cStringIO)然后只需读取该文件:

    from cStringIO import StringIO
    from sys import stdout
    
    # Save a reference to stdout
    STANDARD_OUT = stdout
    
    @app.route("/")
    def hello():
        ftp = FTP("someaddress")
        ftp.login()
    
        # Change stdout to point to a file-like object rather than a terminal
        file_like = StringIO()
        stdout = file_like
    
        ftp.dir()
    
        # lines in this case will be a string, not a list
        lines = file_like.getvalue()
    
        stdout = STANDARD_OUT
        file_like.close()
    
        return lines
    
  3. 这些技术都不会在很多负载下保持良好状态 - 甚至在任何真正的并发下都不会。有办法解决这个问题,但我会留下另一天。