2
|
1 |
|
|
2 |
import os.path
|
|
3 |
|
|
4 |
def get_site_url (script_name) :
|
|
5 |
"""
|
|
6 |
Get the URL that points to the site root (i.e. where style.css is) using the given value of SCRIPT_NAME
|
|
7 |
|
|
8 |
/foo/bar/quux.py -> /foo
|
|
9 |
/~terom/qmsk.net/site/index.py -> /~terom/qmsk.net
|
|
10 |
None -> /
|
|
11 |
"""
|
|
12 |
|
|
13 |
if script_name :
|
|
14 |
return os.path.dirname(os.path.dirname(script_name))
|
|
15 |
else :
|
|
16 |
return "/"
|
|
17 |
|
|
18 |
def get_page_path (path_info, default) :
|
|
19 |
"""
|
|
20 |
Get the path of the page that was requested, or the given default is empty/invalid.
|
|
21 |
The path will never begin with an /.
|
|
22 |
|
|
23 |
/quux -> quux
|
|
24 |
/ -> <default>
|
|
25 |
None -> <default>
|
|
26 |
"""
|
|
27 |
|
|
28 |
if path_info :
|
|
29 |
# remove prefixed slashes
|
|
30 |
path_info = path_info.lstrip('/')
|
|
31 |
|
|
32 |
if path_info :
|
|
33 |
return path_info
|
|
34 |
else :
|
|
35 |
return default
|
|
36 |
|
|
37 |
|
|
38 |
class Request (object) :
|
|
39 |
# The name of the site itself, this can be used to reference e.g. style.css
|
|
40 |
site_url = None
|
|
41 |
|
|
42 |
# The page root url, for links to pages
|
|
43 |
page_root = None
|
|
44 |
|
|
45 |
# The full path to the requested page
|
|
46 |
page_path = None
|
|
47 |
|
|
48 |
def __init__ (self, environ, default_page='main') :
|
|
49 |
self.site_url = get_site_url(environ.get("SCRIPT_NAME"))
|
|
50 |
self.page_root = environ.get("SCRIPT_NAME")
|
|
51 |
self.page_path = get_page_path(environ.get("PATH_INFO"), default_page)
|
|
52 |
|
|
53 |
def page_name_parts (self) :
|
|
54 |
"""
|
|
55 |
Returns a list of page name components
|
|
56 |
"""
|
|
57 |
|
|
58 |
return self.page_path.split('/')
|
|
59 |
|
|
60 |
def page_name_prefixes (self) :
|
|
61 |
"""
|
|
62 |
Iterate over the components of the page name, yielding (prefix, suffix) pairs
|
|
63 |
"""
|
|
64 |
|
|
65 |
prefix = self.page_name_parts()
|
|
66 |
suffix = []
|
|
67 |
|
|
68 |
while prefix :
|
|
69 |
yield ('/'.join(prefix), '/'.join(suffix))
|
|
70 |
|
|
71 |
suffix.insert(0, prefix.pop(-1))
|
|
72 |
|