【问题标题】:Problems serving static files in CherryPy 3.1在 CherryPy 3.1 中提供静态文件的问题
【发布时间】:2010-03-22 23:20:34
【问题描述】:

我在提供静态 XML 样式表以伴随来自 CherryPy Web 应用程序的一些动态生成的输出时遇到了一些麻烦。甚至我提供静态文本文件的测试用例也失败了。

静态文件blah.txt 位于我的应用程序根目录的/static 目录中。

在我的主站点文件中(conesearch.py​​ 包含 CherryPy ConeSearch 页面处理程序类):

import conesearch
cherrypy.config.update('site.config')
cherrypy.tree.mount(conesearch.ConeSearch(), "/ucac3", 'ucac3.config')
...

site.config 我有以下选择:

[/]
tools.staticdir.root: conesearch.current_dir

[/static]
tools.staticdir.on: True
tools.staticdir.dir: 'static'

current_dir = os.path.dirname(os.path.abspath(__file__))conesearch.py 中的位置

但是,我的简单测试页面(直接取自 http://www.cherrypy.org/wiki/StaticContent)失败并显示 404:

def test(self):
        return """
        <html> 
        <head>
        <title>CherryPy static tutorial</title>
        </head>
        <body>
        <a href="/static/blah.txt">Link</a>
        </body>
        </html>"""
test.exposed = True

它正在尝试访问 127.0.0.1:8080/static/blah.txt,我认为应该是 AOK。有什么想法或建议吗?

干杯,

西蒙

【问题讨论】:

    标签: python cherrypy


    【解决方案1】:

    cherrypy.config.update 应该只接收一个单级字典(主要是 server.* 条目),但是你传递给它一个真正应该是每个应用程序的多级设置字典(因此传递给tree.mount )。

    [/][/static] 部分从您的site.config 文件移动到您的ucac3.config 文件,它应该可以正常工作。

    【讨论】:

    • 哦,将&lt;a href="/static/blah.txt"&gt;Link&lt;/a&gt; 更改为&lt;a href="/ucac3/static/blah.txt"&gt;Link&lt;/a&gt;。 ;)
    【解决方案2】:

    我提供这样的静态文件:

    config = {'/static':
                    {'tools.staticdir.on': True,
                     'tools.staticdir.dir': PATH_TO_STATIC_FILES,
                    }
            }
    
    cherrypy.tree.mount(MyApp(), '/', config=config)
    

    【讨论】:

    • 不,恐怕还是没有快乐。不过谢谢。仍然在blah.txt 上收到 404。如果我正确理解 CherryPy 配置字典/文件,这应该与我在上面设置的配置文件完全相同?
    【解决方案3】:

    我有类似的设置。假设我希望我的网站的根目录位于 http://mysite.com/site,并且我的网站/应用程序的根目录位于 /path/to/www

    我的 server.cfg 中有以下配置设置,并且可以毫无问题地找到我的静态文件:

    [global]
    ...
    app.mount_point = '/site'
    tools.staticdir.root = '/path/to/www/'
    [/static]
    tools.staticdir.on = True
    tools.staticdir.dir = 'static'
    

    我正在从静态目录中毫无问题地提供 dojo 文件等,以及 css。我还使用 genshi 进行模板化,并使用 cherrypy.url() 调用来确保我的其他 URL 设置正确。这允许我更改 app.mount_point 并更新我的链接。

    【讨论】: