Problem
You want to be able to refer to an image (or other kind of) static file in your generated HTML files.
Solution
Expose a single file with the following steps:
Declare a variable as an instance of class StaticFile.
Export the variable in _q_exports.
Here is an example:
1 _q_exports = ["my_image_file", ...]
2
3 from quixote.util import StaticFile
4
5 my_image_file = StaticFile("/Quixote/myapp/images/pyfav.gif", mime_type="application/gif")
6
Now you can generate HTML code that looks like the following:
<img src="my_image_file" alt="bad icon"/>
Which tells Quixote to look for the file pyfav.gif in the directory /Quixote/myapp/images/.
The StaticFile constructor also responds to the following keyword arguments:
cache_time -- cache_time indicates the number of seconds a response is considered to be valid, and will be used to set the Expires header in the response. If the value is None, then the Expires header will not be set.
follow_symlinks -- If follow_symlinks is true, symbolic links will be followed.
mime_type -- mime_type specifies the MIME type. If omitted, the MIME type will be guessed. The default is text/plain.
encoding -- encoding specifies the encoding.
Discussion
StaticFile exposes a single file. To expose all the files in a directory, use StaticDirectory instead.
Files with Extensions
One common problem is trying to serve files with file extensions. Python looks for the extension in a module named after the filename, which doesn't exist.
_q_exports can explicitly provide an external name that's different from the internal name:
1 _q_exports = [("favicon.ico", "favicon_ico")]
2 # ^^ external ^^ internal name
3
4 path = os.path.join("/path/to/files", "favicon.ico")
5 favicon_ico = StaticFile(path, mime_type="image/x-icon")
6