annotate pics2/pics_app.py @ 52:f5c2934a1e3f

add pics2
author paulo
date Tue, 14 May 2013 23:36:18 -0700
parents
children 0482bffd7d7f
rev   line source
paulo@52 1 import os
paulo@52 2 import re
paulo@52 3 import glob
paulo@52 4 import traceback
paulo@52 5
paulo@52 6 import html
paulo@52 7
paulo@52 8
paulo@52 9 _APPROOTPATH = "/pics"
paulo@52 10 _GET_PICSDIR_RE = re.compile(r"^.*" + _APPROOTPATH)
paulo@52 11
paulo@52 12 def _get_pics_dir(environ):
paulo@52 13 path_info = environ.get("PATH_INFO", '')
paulo@52 14 return _GET_PICSDIR_RE.sub('.', path_info)
paulo@52 15
paulo@52 16
paulo@52 17 def _get_pics_url(environ, dirpath):
paulo@52 18 script_name = environ.get("SCRIPT_NAME", '')
paulo@52 19 return os.path.normpath(os.path.join(os.path.dirname(script_name), dirpath))
paulo@52 20
paulo@52 21
paulo@52 22 def main(environ):
paulo@52 23 title = '(None)'
paulo@52 24 is_index = False
paulo@52 25
paulo@52 26 d = _get_pics_dir(environ)
paulo@52 27
paulo@52 28 if os.path.exists(os.path.join(d, "_picsroot")):
paulo@52 29 title = os.path.basename(d)
paulo@52 30 elif d == '/':
paulo@52 31 title = "pics index"
paulo@52 32 is_index = True
paulo@52 33 else:
paulo@52 34 raise IOError("_picsroot not found in directory: " + d)
paulo@52 35
paulo@52 36 html_root = html.HTML("html")
paulo@52 37
paulo@52 38 html_header = html_root.header
paulo@52 39 html_header.title(title)
paulo@52 40
paulo@52 41 html_body = html_root.body
paulo@52 42 html_body.h1(title)
paulo@52 43
paulo@52 44 if not is_index:
paulo@52 45 num_jpgs = len(glob.glob(os.path.join(d, "thumbs", "*.jpg")))
paulo@52 46 for i in range(num_jpgs):
paulo@52 47 thumbnail_path = os.path.join(d, "thumbs", "%d.jpg" % i)
paulo@52 48 thumbnail_url = _get_pics_url(environ, thumbnail_path)
paulo@52 49 html_body.img(src=thumbnail_url)
paulo@52 50
paulo@52 51 return unicode(html_root).encode("utf-8")
paulo@52 52
paulo@52 53
paulo@52 54 def app(environ, start_response):
paulo@52 55 response_code = "500 Internal Server Error"
paulo@52 56 response_type = "text/plain; charset=UTF-8"
paulo@52 57
paulo@52 58 try:
paulo@52 59 response_body = main(environ)
paulo@52 60 response_code = "200 OK"
paulo@52 61 response_type = "text/html; charset=UTF-8"
paulo@52 62 except:
paulo@52 63 response_body = traceback.format_exc()
paulo@52 64
paulo@52 65 response_headers = [
paulo@52 66 ("Content-Type", response_type),
paulo@52 67 ("Content-Length", str(len(response_body))),
paulo@52 68 ]
paulo@52 69
paulo@52 70 start_response(response_code, response_headers)
paulo@52 71
paulo@52 72 return [response_body]