【问题标题】:Can't serve static files from cherrypy无法从cherrypy提供静态文件
【发布时间】:2011-07-22 14:36:07
【问题描述】:

我开始学习cherrypy,但遇到了障碍。我无法获取静态文件来挽救我的生命。我收到了 404。The path '/static' was not found. 我已经用谷歌搜索过,但还没有找到解决方案。我想做的就是在http://localhost:8080/static提供文件

建议?

import os
import cherrypy

class Root(object):
    @cherrypy.expose
    def index(self):
        pass

config = {
    '/static':{
    'tools.staticdir.on': True,
    'tools.staticdir.dir': os.path.join(os.path.dirname(__file__), 'static')
    }
}

cherrypy.tree.mount(Root(), '/', config = config)
cherrypy.engine.start()

【问题讨论】:

    标签: cherrypy


    【解决方案1】:

    一些想法:

    1. 在 CherryPy 3.2+ 中,尝试tools.staticdir.debug = True,结合log.screen = True 或其他更受欢迎的日志记录设置。这将比我在这个答案中猜到的任何事情都更有帮助。
    2. 试试tools.staticdir.dir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'static'));它需要是绝对的(或者,如果 .dir 不是绝对的,则 tools.staticdir.root 需要是)。
    3. 在 CherryPy 3.1 及以上版本中,通常需要在 engine.start() 之后调用 engine.block()。

    【讨论】:

    • 我添加了调试和日志行,它的检查路径是绝对的。这是消息:`Checking File: e:\\python\\cherrypyapp\\static\\` 我仔细检查了该路径及其正确,但我仍然得到 404
    • 您实际上是在浏览http://localhost:8080/static,就好像您想在浏览器中获取目录列表一样? staticdir 工具不为其服务的文件提供索引页——您必须请求单个文件,而不是目录。
    • 是 engine.block() 做到了。谢谢!
    【解决方案2】:

    试试这个

    web_config = {'/': {
        'tools.staticdir.on': True,
        'tools.staticdir.root' : os.path.abspath(os.path.join(os.path.dirname(__file__))),
        'tools.staticdir.dir' : os.path.abspath(os.path.join(os.path.dirname(__file__), 'static'))
    },
    
        "/favicon.ico": {
            'tools.staticfile.on': True,
            'tools.staticfile.filename': "favicon.ico",
            'tools.staticdir.on': True,
            'tools.staticdir.dir': "images",
        },
        '/robots.txt': {
            'tools.staticfile.on': True,
            'tools.staticfile.filename': "robots.txt",
            'tools.staticdir.on': True,
            'tools.staticdir.dir': "", },
    
        '/images': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': "images",
        },
    
        '/css': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': "css",
        },
    
        '/js': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': "js",
        }
    }
    

    开始于

    if __name__ == "__main__":
    
        cherrypy.config.update(server_config)
        cherrypy.tree.mount(WebSpid(), config=web_config)
    
        if hasattr(cherrypy.engine, 'block'):
            # 3.1 syntax
            cherrypy.engine.start()
            cherrypy.engine.block() 
    

    【讨论】:

      最近更新 更多