How to serve static files from a different directory than the static path?

牧云@^-^@ 提交于 2019-11-26 13:06:01

问题


I am trying this:

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

But it keeps serving the favicon.ico that I have in my static_path (I have two different favicon.ico\'s in two separate paths, as indicated above, but I want to be able to override the one in the static_path).


回答1:


Delete static_path from the app settings.

Then set your handler like:

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



回答2:


You need to wrap favicon.ico with parenthesis and escape the period in the regular expression. Your code will become

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



回答3:


There are two ways to do it.

1. use static_url_prefix in settings.

e.g.

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

2. use custom handler

Append custom handler to handlers

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

Then implemente your custom methods.

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


来源:https://stackoverflow.com/questions/10165665/how-to-serve-static-files-from-a-different-directory-than-the-static-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!