By CherryPy Team

 

Web applications are usually also made of static content such as javascript, CSS files or images. CherryPy provides support to serve static content to end-users. 

 

Let’s assume, you want to associate a stylesheet with your application to display a blue background color (why not?). 

 

First, save the following stylesheet into a file named style.css and stored into a local directory public/css.

 

body {
  background-color: blue;
}

 

Now let’s update the HTML code so that we link to the stylesheet using the http://localhost:8080/static/css/style.css URL.

 

import os, os.path
import random
import string

import cherrypy


class StringGenerator(object):
    @cherrypy.expose
    def index(self):
        return """<html>
          <head>
            <link href="/static/css/style.css" rel="stylesheet">
          </head>
          <body>
            <form method="get" action="generate">
              <input type="text" value="8" name="length" />
              <button type="submit">Give it now!</button>
            </form>
          </body>
        </html>"""

    @cherrypy.expose
    def generate(self, length=8):
        some_string = ''.join(random.sample(string.hexdigits, int(length)))
        cherrypy.session['mystring'] = some_string
        return some_string

    @cherrypy.expose
    def display(self):
        return cherrypy.session['mystring']


if __name__ == '__main__':
    conf = {
        '/': {
            'tools.sessions.on': True,
            'tools.staticdir.root': os.path.abspath(os.getcwd())
        },
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': './public'
        }
    }
    cherrypy.quickstart(StringGenerator(), '/', conf)

 

Going to http://localhost:8080/, you should be greeted by a flashy blue color. 

 

CherryPy provides support to serve a single file or a complete directory structure. Most of the time, this is what you’ll end up doing so this is what the code above demonstrates. First, we indicate the root directory of all of our static content. This must be an absolute path for security reason. CherryPy will complain if you provide only relative paths when looking for a match to your URLs. 

 

Then we indicate that all URLs which path segment starts with /static will be served as static content. We map that URL to the public directory, a direct child of the root directory. The entire sub-tree of the public directory will be served as static content. CherryPy will map URLs to path within that directory. This is why /static/css/style.css is found in public/css/style.css.