mod_python Project Configuration Files
In my last post I brought up how to get around mod_python’s default inability to handle relative paths for imported modules. The next night after writing that, I faced a very similar issue with configuration files.
It is a sin to duplicate data in a project (except when caching), so most sane desktop applications will have a central store that contains the configuration parameters for the application (usually packaged as a resource with the application, or in the registry for Windows users). Mod_python can’t do this because, as was discussed in my last post, it views the current working directory of whatever script it is executing as the root directory of the filesystem (”/”). So where do you put the configuration file for your mod_python based project if you can’t refer to it relatively, don’t want to hardcode an absolute path, and want to distribute the configuration with the project?
The solution hit me like a bucket of cold water. Give up on the property or ini format file, and make your configuration a python dict object that you can directly import:
# config.py
#
# This is the project's configuration. Import it when a class needs to access
# project configuration variables.
#
_config = {
# The name of my app so pathHack knows what string to look for
'rootname': 'sampleWebApp',
# Database options
'db_host': 'localhost',
'db_dbname': 'sampleWebApp',
'db_user': 'sampleWebAppUser',
'db_password': 's0m3p455w0rd',
# Debug logfile path
'debug_logfile': '/tmp/lostafollower.log'
};
This file needs to live in your project’s root directory as far as mod_python is concerned. For more information, read my last post. If you’ve already read it, then you’ll understand when I say that config.py lives in the same folder as pathHack.py.
Once you can import it from your main source files, use it like this:
<%
# sample usage of config
from config import _config as _c
req.write(_c['rootname'])
%>
Tada! Extraordinarily simple configuration file that is easily accessible and can be distributed with your mod_python application. I’m pretty happy about it :)