scott_list at mischko.com
Mon Feb 27 04:58:01 EST 2006
Scott Chapman wrote: > Hi all! > > I want to make a funky handler for static files. It should return the > requested static file if it's in the directory requested. If it's not > there, it should move up a directory and try there. Well, Here's what I came up with in the code and it works great. It doesn't handle logging issues but it's step #1. It looks first in the site specific directory then in the shared directory. I had the spec "backwards" above. > '''This little handler receives requests for files that would normally be sent statically. > If the file requested is in /images, and the sites internal name is "mischko" then it will look in: > /images/mischko for the file. If it's not there, it will look in /images for it. > > This allows a site to have custom versions of things and if it doesn't, use the shared versions. > It also allows the site to have a template that is happily ignorant of the situation.''' > > from mod_python import apache > import os > import psycopg2 > > def parse_uri(uri): > uri_list = uri.split('/') > uri_list.insert(0,'') > uri_list=uri_list[-3:] > return uri_list > > def _getInternalName(alias): > _conn = psycopg2.connect("user=foo dbname=bar host=127.0.0.1 password=barfoo") > _cursor = _conn.cursor() > query = "SELECT hostname FROM host_aliases WHERE external_name = %s" > parms = [alias] > _cursor.execute(query, parms) > rval = _cursor.fetchone() > if rval: > rval = rval > _conn.rollback() > _conn.close() > return (rval) > > def handler(req): > def _log(message): > req.log_error(message) > > debug = True > > (subsite, moduleName, methodName)= parse_uri(req.uri) > internalName = _getInternalName(req.hostname) > if subsite: > internalName = _getInternalName(subsite) > > if not internalName: > if debug: _log('static_handler - illegal host name') > raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND > > orig_path = req.filename > > (path, filename) = os.path.split(req.filename) > new_path = os.path.normpath(path + '/' + internalName + '/' + filename) > > if os.path.exists(new_path): > use_path = new_path > elif os.path.exists(orig_path): > use_path = orig_path > else: > raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND > > if debug: _log('static_handler - used path: %s' % use_path) > > req.sendfile(use_path) > return apache.OK -- q: Why do so many people take an instant dislike to MySQL and PHP? a: It saves time. ps: Use PostgreSQL and Python instead.