-->

如何从不同的目录比静态路径提供静态文件吗?如何从不同的目录比静态路径提供静态文件吗?(How to

2019-05-13 12:36发布

我想这一点:

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()

但它一直服务于favicon.ico ,我有我的static_path(我有两个不同favicon.ico的两个独立的路径,如上面所指出的,但是我希望能够覆盖一个在static_path )。

Answer 1:

删除static_path从应用程序设置。

然后设置您的处理程序,如:

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


Answer 2:

你需要用的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()


Answer 3:

有两种方法可以做到这一点。

1.使用static_url_prefix的设置。

settings = dict(
    static_path=os.path.join(os.path.dirname(__file__), 'static'),
    static_url_prefix="/adtrpt/static/",
)

2.使用自定义处理程序

并附上自定义处理程序处理程序

handlers.append((r"/adtrpt/static/(.*)", MyStaticFileHandler, {"path": os.path.join(os.path.dirname(__file__), 'static')}))

然后implemente您的自定义方法。

class StaticHandler(BaseHandler):
    def get(self):
        path = self.request.path
        print(path)
        self.redirect(BASE_URI + path)


文章来源: How to serve static files from a different directory than the static path?