python-龙卷风不匹配“/favicon.ico”

python-tornado dont match "/favicon.ico"

问题here and here没有帮助:(

我正在尝试处理“/favicon.ico”,但它无法作为 expected.It 的有线...

我的处理程序看起来像:

handlers = [ 
    (r'^/$', RootHandler),    # this works fine
    (r'^/favicon\.ico$', IconHandler),
    # other handlers
]

我的 IconHandler 看起来像:

class IconHandler(tornado.web.RequestHandler):
    def get(self):
        self.set_header("Content-Type", "image/vnd.microsoft.icon")
        with open(icon_path, 'rb') as f:
            self.write(f.read())
        return self.flush()

但是 http://127.0.0.1:8000/favicon.ico 给我一个 404 错误:

Traceback (most recent call last):
  File "/home/tyler/.pyenv/versions/3.4.2/lib/python3.4/site-packages/tornado/web.py", line 1334, in _execute
    result = yield result
  File "/home/tyler/.pyenv/versions/3.4.2/lib/python3.4/site-packages/tornado/gen.py", line 628, in run
    value = future.result()
  File "/home/tyler/.pyenv/versions/3.4.2/lib/python3.4/site-packages/tornado/concurrent.py", line 109, in result
    raise_exc_info(self._exc_info)
  File "<string>", line 3, in raise_exc_info
  File "/home/tyler/.pyenv/versions/3.4.2/lib/python3.4/site-packages/tornado/gen.py", line 175, in wrapper
    yielded = next(result)
  File "/home/tyler/.pyenv/versions/3.4.2/lib/python3.4/site-packages/tornado/web.py", line 2110, in get
    self.root, absolute_path)
  File "/home/tyler/.pyenv/versions/3.4.2/lib/python3.4/site-packages/tornado/web.py", line 2286, in validate_absolute_path
    raise HTTPError(404)
tornado.web.HTTPError: HTTP 404: Not Found

所以我更改了 url 匹配模式并做了一些测试:

handler pattern        | url                                   | status
-----------------------|---------------------------------------|--------
r'^/favicon\.ico$'     | http://127.0.0.1:8000/favicon.ico     | 404Error
r'/favicon\.ico'       | http://127.0.0.1:8000/favicon.ico     | 404Error
r'/favicon.ico'        | http://127.0.0.1:8000/favicon.ico     | 404Error
r'^/sub/favicon\.ico$' | http://127.0.0.1:8000/sub/favicon.ico | Works!
r'/sub/favicon\.ico'   | http://127.0.0.1:8000/sub/favicon.ico | Works!
r'/sub/favicon.ico'    | http://127.0.0.1:8000/sub/favicon.ico | Works!

请帮忙。我无法理解:(

python: 3.4.2

龙卷风:4.0.2

Ubuntu: 14.10

我相信您的应用设置中有 static_path 字段。你的情况是这样的:

You can serve static files by sending the static_path setting as a keyword argument.

并且:

note that a StaticFileHandler can be installed automatically with the static_path setting

当您配置了 static_path 设置时,

Favicon 模式会自动插入 到处理程序模式列表中。那些自动静态模式比你自己的模式有更高的优先级。

你的追溯就是证明:

  File "/home/tyler/.pyenv/versions/3.4.2/lib/python3.4/site-packages/tornado/web.py", line 2286, in validate_absolute_path
    raise HTTPError(404)

因此,我建议您从您的应用设置中删除 static_path,并像这样添加您自己的 /static 模式

(r"/static/(.*)", web.StaticFileHandler, {"path": my_path}),