使用 CherryPy 提供图标时出现错误 500

Error 500 while serving favicon with CherryPy

我的 CherryPy 应用程序在提供网站图标时开始抛出错误 500(请参阅下面的回溯)。起初只有几台电脑有问题,现在所有的电脑都出错了。我认为我没有对 Python 应用程序进行任何更改,可能是计算机配置发生了某些更改。

我无法调试错误,因为它不会在我的开发计算机上重现。在我的电脑上,它甚至没有到达它在生产服务器上崩溃的那一行。

配置如下(其他参数由其他模块添加,这是处理favicon的起始配置):

config = {'global': {'server.socket_host':  '0.0.0.0',
                     'server.socket_port':  80,
                     'log.error_file':      'log\web.log',
                     'log.access_file':     'log\access.log'},
          '/favicon.ico': {'tools.staticfile.on':       True,
                           'tools.staticfile.filename': os.path.dirname(__file__) + '\favicon.ico'}}

这是回溯:

[08/Jan/2016:13:55:14] HTTP
Request Headers:
  ACCEPT-LANGUAGE: en-US,en;q=0.8
  COOKIE: DocFinder_Id=2dde47f7-c679-4c12-a5c5-0a8a214c47d6
  CONNECTION: keep-alive
  REFERER: http://intelliweb.universecorp.com/doc/tmp/808184425.pdf
  ACCEPT-ENCODING: gzip, deflate
  USER-AGENT: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36
  Remote-Addr: 192.1.1.120
  ACCEPT: */*
  HOST: intelliweb.universecorp.com
[08/Jan/2016:13:55:14] HTTP Traceback (most recent call last):
  File "C:\Python34\lib\site-packages\cherrypy\_cprequest.py", line 670, in respond
    response.body = self.handler()
  File "C:\Python34\lib\site-packages\cherrypy\lib\encoding.py", line 212, in __call__
    self.body = self.oldhandler(*args, **kwargs)
  File "C:\Python34\lib\site-packages\cherrypy\_cpdispatch.py", line 61, in __call__
    return self.callable(*self.args, **self.kwargs)
  File "C:\Python34\lib\site-packages\cherrypy\_cptools.py", line 175, in handle_func
    handled = self.callable(*args, **self._merged_args(kwargs))
TypeError: staticfile() got multiple values for argument 'filename'

192.1.1.120 - - [08/Jan/2016:13:55:14] "GET /favicon.ico HTTP/1.1" 500 1468 "http://intelliweb.universecorp.com/doc/tmp/808184425.pdf" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"

尝试更改此行:

'tools.staticfile.filename': os.path.dirname(__file__) + '\favicon.ico'

'tools.staticfile.filename': os.path.join(os.path.dirname(__file__), 'favicon.ico')

另一种方法是从您的 html(在 header 部分)提供您的网站图标:

<link href="yourpath/favicon.ico" rel="icon" type="image/x-icon" />

misakm 的回答不正确,但帮助我调试:问题是 __file__ 在开发计算机上是绝对的,而在生产计算机上是相对的。我找到了原因 here:

If you load a module in the current directory, and the current directory isn't in sys.path, you'll get an absolute path.

If you load a module in the current directory, and the current directory is in sys.path, you'll get a relative path.

解决方案是像这样添加 abspath

os.path.join(os.path.dirname(os.path.abspath(__file__)), 'favicon.ico')

罪魁祸首是几周前在 Windows 环境中执行的一些维护,它改变了 PATH。