【问题标题】:cherrypy - serve static files and force content-typecherrypy - 提供静态文件并强制内容类型
【发布时间】:2014-08-07 08:24:54
【问题描述】:

我正在用cherrypy 构建一个小型网络应用程序。

在这个应用程序中,我需要以两种不同的方式提供文件:

  1. 使用正确的 mime 类型提供它,以将其嵌入网页中,
  2. 使用application/octet-stream mime 类型提供它,以强制下载。

目前,我向流文件添加了一个公开的方法,一个在 /document/xx,返回正确的 mime 类型,另一个在 /download/xx,使用八位字节流 mime 类型。

但我想避免自己编写代码。它只会带来错误和安全问题。

tl;dr:如何强制cherrypy的tools.staticdir强制下载?

在 github 上查看应用程序的完整代码:https://github.com/aspyct/docrepo(请注意,它仍然使用旧的 'config.ini' 文件,没有配置字典)。

【问题讨论】:

    标签: python http cherrypy


    【解决方案1】:

    您可以通过向工具提供 content_types 来强制执行此操作,该工具将文件扩展名映射到 MIME 类型。像这样。

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    
    import os
    
    import cherrypy
    
    
    path   = os.path.abspath(os.path.dirname(__file__))
    config = {
      'global' : {
        'server.socket_host' : '127.0.0.1',
        'server.socket_port' : 8080,
        'server.thread_pool' : 8
      },
      '/static' : {
        'tools.staticdir.on'            : True,
        'tools.staticdir.dir'           : os.path.join(path, 'static'),
        'tools.staticdir.content_types' : {'html': 'application/octet-stream'}
      }
    }
    
    
    if __name__ == '__main__':
      cherrypy.quickstart(config = config)
    

    如果您事先不知道扩展名,请查看该工具的source code。几乎没有两打有效的代码行。只需制作您自己的微调工具即可。

    【讨论】:

      猜你喜欢
      • 2011-07-22
      • 1970-01-01
      • 2014-02-22
      • 1970-01-01
      • 1970-01-01
      • 2016-11-07
      • 2012-03-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多