Delaying declaring static files/folders with CherryPy
I have a single CherryPy application serving two websites, each having their static files stored in respective sub-folders of my app folder (each subfolder is named after the respective domain). In my main top-level program (Main.py), the site is launched with
cherrypy.quickstart(Root(), '/',config='cherrypy.cfg')
. So far so good...
The problem I am having is with static declarations in config.cfg, which usually starts with
[/]
tools.staticdir.root = '/domain name/root/static/folder'
tools.staticdir.on = True
tools.staticdir.dir = ''
[/css]
tools.staticdir.on = True
tools.staticdir.dir = 'css'
However, at the time the app. is launched, I don't know the value of the tools.staticdir.root folder until I get a request, then I can evaulate the domain name (via. cherrypy.request.base) then set the default subfolder path and root folder accordingly.
So the question is, can I 'hold-off' declaring my static files/folders until my Index() method is called (if so, how?), or can they only be decl开发者_开发知识库ared when cherrypy.quickstart() is run?
TIA, Alan
All Tools are just callables with some configuration sugar, so you can hold off until your index method via:
def index(self, ...):
root = my_domain_map[cherrypy.request.headers['Host']]
cherrypy.lib.staticdir(section='', dir='', root=root)
# And then this funky hack...
return cherrypy.response.body
index.exposed = True
...or just by calling cherrypy.lib.static.serve_file, which is even lower level...
...but there's a more integrated way. Set the root
argument before you get to the index method, and indeed before the staticdir Tool is invoked. It is invoked in a before_handler
hook (priority 50; lower numbers run first). So, you want to inspect your Host header somewhere just before that; let's pick priority 30:
def staticroot(debug=False):
root = my_domain_map[cherrypy.request.headers['Host']]
cherrypy.request.toolmaps['tools']['staticdir']['root'] = root
cherrypy.tools.staticroot = cherrypy.Tool(
staticroot, point='before_handler', priority=30)
Then, turn on your new tool in config:
[/]
tools.staticroot.on = True
...and give it a whirl.
精彩评论