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