view pics2/pics_app.py @ 55:0fbe37b56e84

update index_app to use _indexroot files
author paulo
date Thu, 22 Aug 2013 23:53:56 -0700
parents 0482bffd7d7f
children 0249782e231e
line source
1 import os
2 import re
3 import glob
4 import traceback
5 import datetime
6 import random
7 import urlparse
9 import html
11 import logging
12 logging.basicConfig(
13 level=logging.DEBUG,
14 filename="_LOG",
15 format="%(asctime)s %(levelname)-8s %(message)s",
16 )
20 def _is_pics_dir(dirpath):
21 return os.path.exists(os.path.join(dirpath, "_picsroot"))
24 def _get_dir_dt(dirpath):
25 if _is_pics_dir(dirpath):
26 dirpath = os.path.join(dirpath, "_picsroot")
28 return datetime.datetime.fromtimestamp(os.stat(dirpath).st_mtime)
31 def _format_dt(dt):
32 return dt.strftime("%Y-%m-%d")
35 def _parse_path_info(path_info):
36 ppi = path_info.split(os.sep)
37 if len(ppi) > 1 and ppi[-1] == '':
38 del ppi[-1]
40 return ppi
43 def _numeric_pad_basename(path, maxdigits=20):
44 return os.path.basename(path).zfill(maxdigits)
47 def _get_images(d):
48 thumb_fns = glob.glob(os.path.join(d, "thumbs", "*.jpg"))
49 thumb_fns = sorted(thumb_fns, key=_numeric_pad_basename)
50 logging.debug("thumb_fns = %s" % thumb_fns)
52 browse_fns = [os.path.join(d, "browse", os.path.basename(i)) for i in thumb_fns]
53 logging.debug("browse_fns = %s" % browse_fns)
55 return zip(thumb_fns, browse_fns)
58 class Main:
59 def _get_pics_url(self, dirpath):
60 script_name = self._environ.get("SCRIPT_NAME", '')
61 return os.path.normpath(os.path.join(os.path.dirname(script_name), dirpath))
64 def _get_app_url(self, dirpath):
65 script_name = self._environ.get("SCRIPT_NAME", '')
66 return os.path.normpath(os.path.join(script_name, dirpath))
69 def _get_standard_html_doc(self, title):
70 root = html.HTML("html")
72 header = root.header
73 header.link(rel="stylesheet", type="text/css", href=self._get_pics_url("index.css"))
74 header.title(title)
76 body = root.body
77 body.h1(title)
79 return (root, header, body)
82 def _go_thumbnail_links_to_browse_imgs_html_body(self, body, t, b, selclass=None):
83 thumb_img_url = self._get_pics_url(t)
84 browse_url = self._get_app_url(b)
86 a = body.a(href=browse_url)
88 if selclass is not None:
89 a.img(src=thumb_img_url, klass=selclass)
90 else:
91 a.img(src=thumb_img_url)
93 body.text(' ')
96 def __init__(self, environ):
97 self._environ = environ
98 self._page_func = None
100 #logging.debug("environ = %s" % (sorted(self._environ.items(), key=lambda x: x[0]),))
101 logging.debug("environ['PATH_INFO'] = %s" % self._environ["PATH_INFO"])
102 logging.debug("environ['SCRIPT_NAME'] = %s" % self._environ["SCRIPT_NAME"])
103 logging.debug("environ['QUERY_STRING'] = %s" % self._environ["QUERY_STRING"])
105 pi = self._environ["PATH_INFO"]
106 ppi = _parse_path_info(pi)
107 logging.debug("ppi = %s" % ppi)
109 if len(ppi) < 1 or ppi[0] != '':
110 raise AssertionError("Parsed path length must start empty: " + pi)
112 if len(ppi) >= 2 and _is_pics_dir(ppi[1]):
113 if len(ppi) == 2:
114 self._page_func = self.page_thumbs
115 elif len(ppi) >= 4 and ppi[2] == "browse" and os.path.exists(os.path.join(*ppi)):
116 self._page_func = self.page_browse
117 elif len(ppi) == 1:
118 self._page_func = self.page_index
120 if self._page_func is None:
121 raise RuntimeError("Cannot find path: " + pi)
124 def page(self):
125 return unicode(self._page_func()).encode("utf-8")
128 def page_index(self):
129 n = 5 # number of thumbnails to display
131 (html_root, html_header, html_body) = self._get_standard_html_doc("Pictures")
133 pics_dirs = []
134 for i in os.listdir('.'):
135 if _is_pics_dir(i):
136 pics_dirs.append((i, _get_dir_dt(i)))
138 pics_dirs.sort(key=lambda x: x[1], reverse=True)
140 for (d, dt) in pics_dirs:
141 html_body.h2.a(d, href=self._get_app_url(d))
142 html_body.h3(_format_dt(dt))
144 imgs = _get_images(d)
145 imgs_idx = [(i, img) for (i, img) in enumerate(imgs)]
147 sampled_imgs_idx = random.sample(imgs_idx, min(len(imgs_idx), n))
148 sampled_imgs_idx.sort(key=lambda x: x[0])
150 html_p = html_body.p
151 for (i, (t, b)) in sampled_imgs_idx:
152 self._go_thumbnail_links_to_browse_imgs_html_body(html_p, t, b)
154 return html_root
157 def page_thumbs(self):
158 ppi = _parse_path_info(self._environ["PATH_INFO"])
159 d = os.path.join(*ppi)
160 (html_root, html_header, html_body) = self._get_standard_html_doc(d)
162 qs = urlparse.parse_qs(self._environ["QUERY_STRING"])
163 from_img = None
164 if "from" in qs:
165 from_img = qs["from"][0]
167 html_p = html_body.p
168 for (t, b) in _get_images(d):
169 if from_img is not None and b == from_img:
170 self._go_thumbnail_links_to_browse_imgs_html_body(html_p, t, b, "sel2")
171 else:
172 self._go_thumbnail_links_to_browse_imgs_html_body(html_p, t, b)
174 html_body.a("(Other pictures)", href=self._get_app_url(''))
175 return html_root
178 def page_browse(self):
179 ppi = _parse_path_info(self._environ["PATH_INFO"])
180 d = os.path.join(*ppi[:2])
181 imgs = _get_images(d)
182 img = os.path.join(*ppi)
184 # thumbnail preview ribbon
185 w = 7 # must be odd
186 v = w/2
187 imgs_circ = [None] * w
188 x = None
189 n = len(imgs)
190 for (i, (t, b)) in enumerate(imgs):
191 if b == img:
192 x = i + 1
193 imgs_circ[v] = (t, b)
194 for j in range(1, v + 1):
195 if (i + j) < n: imgs_circ[v + j] = imgs[i + j]
196 if (i - j) >= 0: imgs_circ[v - j] = imgs[i - j]
198 break
200 if x is None:
201 raise AssertionError
203 (html_root, html_header, html_body) = self._get_standard_html_doc(u"%s \u2014 %s of %s" % (d, x, len(imgs)))
205 browse_img_url = self._get_pics_url(img)
206 html_body.p.img(src=browse_img_url)
208 logging.debug("imgs_circ = %s" % imgs_circ)
210 html_p = html_body.p
211 for i in imgs_circ:
212 if i is not None:
213 (t, b) = i
214 if b == img:
215 self._go_thumbnail_links_to_browse_imgs_html_body(html_p, t, d + "?from=" + img, "sel")
216 else:
217 self._go_thumbnail_links_to_browse_imgs_html_body(html_p, t, b)
219 return html_root
222 def app(environ, start_response):
223 response_code = "500 Internal Server Error"
224 response_type = "text/plain; charset=UTF-8"
226 try:
227 response_body = Main(environ).page()
228 response_code = "200 OK"
229 response_type = "text/html; charset=UTF-8"
230 except:
231 response_body = traceback.format_exc()
233 response_headers = [
234 ("Content-Type", response_type),
235 ("Content-Length", str(len(response_body))),
236 ]
238 start_response(response_code, response_headers)
240 return [response_body]