Skip to content

Instantly share code, notes, and snippets.

@jtanx
Last active November 25, 2018 08:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jtanx/3427e1f5c507c8af5e54c98bf95bd49e to your computer and use it in GitHub Desktop.
Save jtanx/3427e1f5c507c8af5e54c98bf95bd49e to your computer and use it in GitHub Desktop.
Simple image viewer
from flask import Flask, redirect, url_for, render_template_string, send_from_directory, make_response, Response
from functools import wraps, update_wrapper
from datetime import datetime
from zipfile import ZipFile
import os
import sys
app = Flask(__name__)
arch = None
imgs = [x for x in sorted(os.listdir('.')) if x.endswith('.jpg') or x.endswith('.png')]
def nocache(view):
@wraps(view)
def no_cache(*args, **kwargs):
response = make_response(view(*args, **kwargs))
response.headers['Last-Modified'] = datetime.now()
response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '-1'
return response
return update_wrapper(no_cache, view)
@app.route('/img/<int:id>')
@nocache
def img(id):
id = min(max(id, 0), len(imgs) - 1)
if arch is None:
return send_from_directory('.', imgs[id])
with arch.open(imgs[id]) as fp:
return Response(fp.read(), mimetype='image/jpeg' if imgs[id].endswith('.jpg') else 'image/png')
@app.route('/view/<int:id>')
@nocache
def view(id):
id = max(id, 0)
mid = len(imgs) - 1
if id > mid:
return redirect(url_for('view', id=mid), code=302)
return render_template_string(
'''
<html>
<body>
<h1>{{id}}/{{max}}</h1>
<img src="{{img}}" style="margin-left: auto; margin-right: auto; display:block; width:70%;" onclick="go(false)" />
</body>
<script>
'use strict';
function go(left) {
let id = parseInt(window.location.pathname.split('/')[2], 10);
if (left) {
--id;
if (id < 0) {
return;
}
} else {
++id;
}
window.location.href = '/view/' + id
}
document.addEventListener('keypress', (e) => {
if (e.keyCode == 37 || e.charCode == 97 || e.charCode == 65) { //left
go(true)
} else if (e.keyCode == 39 || e.charCode == 100 || e.charCode == 68) { //right
go(false)
}
console.log(e)
});
</script>
</html>
''',
id=id, max=mid,
img=url_for('img', id=id))
# fully sick subwoofa
@app.route('/')
@nocache
def index():
return redirect(url_for('view', id=0), code=302)
if __name__ == "__main__":
if len(sys.argv) > 1:
arch = ZipFile(sys.argv[1])
imgs = [img for img in arch.namelist() if (img.endswith('.jpg') or img.endswith('.png'))]
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment