在CherryPy 3.1中服务静态文件favicon.ico和robots.txt的问题

4 投票
2 回答
2368 浏览
提问于 2025-04-17 01:28

当我尝试访问favicon.ico这个文件时,我遇到了这个错误:

ValueError: Static tool requires an absolute filename (got 'favicon.ico')

我可以正常访问我的/images、/css和/js文件夹里的内容。那些都运行得很好。网站看起来和运行得都很不错。就是这两个文件出问题了。

这是我的root.conf文件。

[/]
tools.staticdir.on = True
tools.staticdir.root = "/projects/mysite/root"
tools.staticdir.dir = ""

[/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"

这是我的cherrypy.conf文件:

[global]
server.socket_port = 8888
server.thread_pool = 10
tools.sessions.on = True

这是我的"startweb.py"脚本:

import cherrypy
from root.roothandler import Root

cherrypy.config.update("cherrypy.conf")

cherrypy.tree.mount(Root(), "/", "root/root.conf")

if hasattr(cherrypy.engine, 'block'):
    # 3.1 syntax
    cherrypy.engine.start()
    cherrypy.engine.block()
else:
    # 3.0 syntax
    cherrypy.server.quickstart()
    cherrypy.engine.start()

2 个回答

0

我找到了一种可行的解决办法,但我不是很喜欢。这个方法需要在三个地方都写上完整的绝对路径。

下面是新的 root.conf 文件内容:

[/]
tools.staticdir.on = True
tools.staticdir.root = "/projects/mysite/trunk/root"
tools.staticdir.dir = ""

[/favicon.ico]
tools.staticfile.on = True
tools.staticfile.filename = "/projects/mysite/trunk/root/images/favicon.ico"

[/robots.txt]
tools.staticfile.on = True
tools.staticfile.filename = "/projects/mysite/trunk/root/robots.txt"

[/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"
5

当你为某个特定的URL开启CherryPy工具时,这个工具也会自动应用到所有在这个URL下面的“子”URL上。因此,像[/images][/css][/js]这些配置看起来就有点多余了。同样,[/robots.txt]部分也是如此。

至于[/favicon.ico],它也算多余,不过favicon.ico有点特别,因为CherryPy通常会为你设置一个(这个设置是作为你根对象的一个属性;可以查看_cptree.py)。所以,覆盖它是合适的:

[/]
tools.staticdir.on = True
tools.staticdir.root = "/projects/mysite/trunk/root"
tools.staticdir.dir = ""
tools.staticfile.root = "/projects/mysite/trunk/root"

[/favicon.ico]
tools.staticfile.on = True
tools.staticfile.filename = "images/favicon.ico"

撰写回答