wiki:StaticFiles
Warning: Can't synchronize with repository "(default)" (Unsupported version control system "svn": No module named svn). Look in the Trac log for more information.

Version 4 (modified by anonymous, 13 years ago) (diff)

--

Serving Static Files

There are two ways to serve static files in TurboGears

TODO: Link/explain how to setup Apache to serve static files directly.

Use Static Filter

Edit project_name/config/app.cfg , You'll see there are several static filters exist on

[/static]
static_filter.on = True
static_filter.dir = "%(top_level_dir)s/static"

[/favicon.ico]
static_filter.on = True
static_filter.file = "%(top_level_dir)s/static/images/favicon.ico"

The string in square brackets[] denotes the prefered web url.

ex:

In first case, We can access static files in [/static] as  http://localhost:8080/static

static_filter.on = True

The second line "static_filter.on = True" is essential for all static filter statements.

static_filter.dir = "%(top_level_dir)s/static"

We can use "static_filter.file" or "static_filter.dir" to locate the dir or file. We can use regular expression by "static_filter.match", too.

The static_filter requires all path to be absolute. We can use "%(top_level_dir)s" to denote the "top level dir" of this project.

We can also specify what content-type to set depending on the extension of each file being served.

ex rss file in [/rss], atom files in [/atom]

[/rss]
static_filter.on = True 
static_filter.content_types = {'rss': 'application/rss+xml'} 
static_filter.dir = '/full/path/to/feed' 

[/rss]
static_filter.on = True 
static_filter.content_types = {'atom': 'application/atom+xml'} 
static_filter.dir = '/full/path/to/feed' 

Use serve_file() function

We might want to have a particular way to serve static content that cannot be achieved via the static_filter. In such case, use the serve_file() function instead.

from cherrypy.lib import cptools
cptools.serve_file("filepath")

"cptools.serve_file()" let us have more flexibility to control the access of files.

This article refer the cherrypy  serving-static-content document