master
Tomek Dubrownik 2013-02-21 02:21:49 +01:00
commit 48567e9432
3 changed files with 98 additions and 0 deletions

7
gallery.cfg.dist Normal file
View File

@ -0,0 +1,7 @@
CHARSET = 'utf-8'
DIRECTORY = ''
MIME = r'image/.*'
THUMB_DIR = './thumb'
THUMB_SIZE = (100,100)

67
gallery.py Normal file
View File

@ -0,0 +1,67 @@
import os
import re
import mimetypes
from os.path import isdir, abspath, exists, split
from flask import Flask, render_template, abort, send_file, safe_join
from PIL import Image
from jinja2 import contextfilter
app = Flask('gallery')
app.config.from_pyfile('gallery.cfg')
picmime = re.compile(app.config['MIME'])
base = app.config['DIRECTORY']
thumb = app.config['THUMB_DIR']
thsize = app.config['THUMB_SIZE']
def is_image(path):
return picmime.match(mimetypes.guess_type(path)[0] or 'NOPE')
@app.template_filter('relurl')
@contextfilter
def relurl(ctx, tgt):
return safe_join(ctx['path'], tgt)
@app.route('/pictures/<path:tgt>')
def send_pic(tgt):
return send_file(safe_join(base, tgt))
def ensure_dir(path):
try:
os.makedirs(split(path)[0])
except OSError as e:
if e.errno == 17:
pass
else:
raise
@app.route('/thumb/<path:tgt>')
def send_thumb(tgt):
orig_path = safe_join(base, tgt)
thumb_path = safe_join(thumb, tgt)
if not exists(thumb_path) or \
os.stat(thumb_path).st_mtime < os.stat(orig_path).st_mtime:
ensure_dir(thumb_path)
image = Image.open(orig_path)
sz = image.size
scale = min(float(b) / a for a,b in zip(sz, thsize))
scale = min(scale, 1)
image.resize(map(int, (scale * sz[0], scale * sz[1])), Image.ANTIALIAS).save(thumb_path)
return send_file(thumb_path)
@app.route('/<path:tgt>')
def view(tgt):
try:
path = abspath(safe_join(base, tgt))
names = map(lambda s: s.decode(app.config['CHARSET']), os.listdir(path))
dirs = filter(lambda f: isdir(safe_join(path,f)), names)
pics = filter(is_image, names)
return render_template('main.html', dirs=dirs, pics=pics, path=tgt)
except OSError as e:
if e.errno == 2:
abort(404)
app.route('/')(lambda: view(''))
if __name__ == '__main__':
app.run('::', 8080, debug=True)

24
templates/main.html Normal file
View File

@ -0,0 +1,24 @@
<!doctype html>
<html>
<head>
</head>
<body>
<h2>Subgalleries</h2>
<ul>
{% for d in dirs %}
<li><a href="{{d | relurl}}">{{d}}</a></li>
{% endfor %}
</ul>
<h2>Pictures</h2>
<ul>
{% for p in pics %}
<li>
<a href="/pictures/{{p | relurl}}">
<img src="/thumb/{{p | relurl}}"></img>
{{p}}
</a>
</li>
{% endfor %}
</ul>
</body>
</html>