IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    Web.py Cookbook 简体中文版 - 如何流传输大文件

    justjavac (justjavac@gmail.com)发表于 2012-04-19 00:00:00
    love 0

    问题

    如何流传输大文件?

    解法

    要流传输大文件,需要添加传输译码(Transfer-Encoding)区块头,这样才能一边下载一边显示。否则,浏览器将缓冲所有数据直到下载完毕才显示。

    如果这样写:直接修改基础字符串(例中就是j),然后用Yield返回--是没有效果的。如果要使用Yield,就要向对所有内容使用yield。因为这个函式此时是一个产生器。(注:请处请详看Yield文档,在此不做过多论述。)

    例子

    # Simple streaming server demonstration
    # Uses time.sleep to emulate a large file read
    import web
    import time
    
    urls = (
        "/",    "count_holder",
        "/(.*)",  "count_down",
        )
    app = web.application(urls, globals())
    
    
    class count_down:
        def GET(self,count):
            # These headers make it work in browsers
            web.header('Content-type','text/html')
            web.header('Transfer-Encoding','chunked')        
            yield '

    Prepare for Launch!

    ' j = '
  • Liftoff in %s...
  • ' yield '
      ' count = int(count) for i in range(count,0,-1): out = j % i time.sleep(1) yield out yield '
    ' time.sleep(1) yield '

    Lift off

    ' class count_holder: def GET(self): web.header('Content-type','text/html') web.header('Transfer-Encoding','chunked') boxes = 4 delay = 3 countdown = 10 for i in range(boxes): output = '' % (countdown - i) yield output time.sleep(delay) if __name__ == "__main__": app.run()


沪ICP备19023445号-2号
友情链接