Search code examples
pythonweb-applicationscherrypyhttpserver

CherryPy static content from different paths


I have read some Q&A like load-static-content-with-cherrypy

However, I am unable to figure out how to do it to be shared by different paths.

I have the following Class:

class Root(Base):
    @cherrypy.expose
    def index(self):
        return self.html_head()+self.header()+"Root"+self.footer()+self.html_end()

    @cherrypy.expose
    def help(self):
        return self.html_head()+self.header()+"HELP"+self.footer()+self.html_end()

And the config file is:

[global]
server.socket_host = "127.0.0.1"
server.socket_port = 8080
server.thread_pool = 10

[/]
tools.staticfile.root = "/path/to/app/"

[/css/style201306.css]
tools.staticfile.on = True
tools.staticfile.filename = "css/style201306.css"

When accesing the css from /help I got a 404 error. Must I add a [path] entry for every method in my class where I want to serve the css file? Or must I use the [global] tag instead, though maybe I don't want to use it from other apps? What is the difference between an app config and a path config entry? Until know I was considering this as one App with 2 paths ("/" and "/help")

I am passing configuration like:

# Configuration
import os.path
tutconf = os.path.join(os.path.dirname(__file__), 'myconf.conf')
cherrypy.quickstart(root, config=tutconf)

Both webpages load the CSS the same way (actually, is the same code):

css/style201306.css

Solution

  • The problem is in your html itself use an absolute URL, there is no reason to use a relative url when is the same content, instead of:

    <link rel="stylesheet" type="text/css"  href="css/style201306.css" />
    

    use

    <link rel="stylesheet" type="text/css"  href="/css/style201306.css" />
    

    otherwise the browser will append the current URL, for example if the current URL is /help, then it will try to fetch:

    /help/css/style201306.css