FileResource - Serving Individual Files

The FileResource class provides a means to serve individual static files from the filesystem. Although a DirectoryResource object may serve files having specific filename extensions as particular types from a filesystem directory, we sometimes need to select individual files from special locations and serve their contents as part of a response.

WebStack API - FileResource Initialisation

The FileResource class (found in the WebStack.Resources.Static module) accepts the following parameters when being initialised:

filename
The full path to the particular static file being served.
content_type
A content type object (such as WebStack.Generic.ContentType) providing sufficient information for user agents to interpret the file's contents.

Combining MapResource with FileResource

One might combine MapResource with FileResource to provide a favicon.ico image for an application as follows:

from WebStack.Resources.ResourceMap import MapResource
from WebStack.Resources.Static import FileResource

# This is where the application's resources would be obtained.

app_resource = ...

# Here is where we combine MapResource and FileResource.
# Note that one would not necessarily hard-code directory paths into the application.

top_resource = MapResource({
"favicon.ico" : FileResource("/usr/share/apps/MyApp/images/py.ico"), ContentType("image/x-icon")),
"" : app_resource
})

In the above example, the favicon.ico file in the images directory is served as image/x-icon.