import os.path
def get_site_url (script_name) :
"""
Get the URL that points to the site root (i.e. where style.css is) using the given value of SCRIPT_NAME
/foo/bar/quux.py -> /foo
/~terom/qmsk.net/site/index.py -> /~terom/qmsk.net
/ -> ""
None -> ""
"""
if script_name :
return os.path.dirname(os.path.dirname(script_name)).rstrip("/")
else :
return ""
def get_page_path (path_info, default) :
"""
Get the path of the page that was requested, or the given default is empty/invalid.
The path will never begin with an /.
/quux -> quux
/ -> <default>
None -> <default>
"""
if path_info :
# remove prefixed slashes
path_info = path_info.lstrip('/')
if path_info :
return path_info
else :
return default
class Request (object) :
# The name of the site itself, this can be used to reference e.g. style.css
site_url = None
# The page root url, for links to pages
page_root = None
# The full path to the requested page
page_path = None
def __init__ (self, environ, default_page='main') :
self.site_url = get_site_url(environ.get("SCRIPT_NAME"))
self.page_root = environ.get("SCRIPT_NAME")
self.page_path = get_page_path(environ.get("PATH_INFO"), default_page)
def page_name_parts (self) :
"""
Returns a list of page name components
"""
return self.page_path.split('/')
def page_name_prefixes (self) :
"""
Iterate over the components of the page name, yielding (prefix, suffix) pairs
"""
prefix = self.page_name_parts()
suffix = []
while prefix :
yield ('/'.join(prefix), '/'.join(suffix))
suffix.insert(0, prefix.pop(-1))