2012-04-15 109 views
28

我想這一點:使用Tornado,我如何提供靜態文件並從靜態路徑以外的其他目錄提供favicon.ico?

favicon_path = '/path/to/favicon.ico' 

settings = {'debug': True, 
      'static_path': os.path.join(PATH, 'static')} 

handlers = [(r'/', WebHandler), 
      (r'/favicon.ico', tornado.web.StaticFileHandler, {'path': favicon_path})] 

application = tornado.web.Application(handlers, **settings) 
application.listen(port) 
tornado.ioloop.IOLoop.instance().start() 

但它一直服務於我在我的static_path的favicon.ico的(我有兩個不同的favicon.ico在兩個獨立的路徑,如上文所述,但我想成爲能夠覆蓋static_path中的那個)。

回答

46

從應用程序設置中刪除static_path

handlers = [ 
      (r'/(favicon\.ico)', tornado.web.StaticFileHandler, {'path': favicon_path_dir}), 
      (r'/static/(.*)', tornado.web.StaticFileHandler, {'path': static_path_dir}), 
      (r'/', WebHandler) 
] 
+0

好吧,我通過將其更改爲r'/(favicon \ .ico)'來獲得此工作。爲什麼這樣做? (我從文檔中的類似示例複製了它)。 – shino 2012-04-16 01:04:37

+5

好像在應用設置中設置static_path對於favicon和robots.txt有一個特殊情況。從文檔:'我們將服務/favicon.ico和/robots.txt從相同的[static_path]目錄' – 2012-04-16 07:05:59

+8

@shino它工作,因爲r'/ favicon.ico'是一個正則表達式,你正確地逃脫了'。' – SK9 2013-07-23 13:28:48

4

你需要用的favicon.ico用括號和轉義在正則表達式的時期:

然後像設置你的處理程序。您的代碼將變爲

favicon_path = '/path/to/favicon.ico' # Actually the directory containing the favicon.ico file 

settings = { 
    'debug': True, 
    'static_path': os.path.join(PATH, 'static')} 

handlers = [ 
    (r'/', WebHandler), 
    (r'/(favicon\.ico)', tornado.web.StaticFileHandler, {'path': favicon_path})] 

application = tornado.web.Application(handlers, **settings) 
application.listen(port) 
tornado.ioloop.IOLoop.instance().start()