Files
flask-fet-fotos/foto_gallery/__init__.py
2020-09-26 12:08:18 +00:00

171 lines
5.8 KiB
Python

"""
This module is based on flask_flatpages and creates a website structure based on a file structure.
By default the .md extension creates a html website
"""
import logging
import sys
from flask import Flask, Blueprint,render_template, send_from_directory,jsonify, url_for, abort
#from flask_flatpages import FlatPages, pygments_style_defs
import flatpages_index
from flatpages_index import FlatPagesIndex
from flask_frozen import Freezer
#from config import Config
import os
import re
from PIL import Image, ExifTags, ImageOps
from functools import partial
from flask_csp.csp import csp_header, csp_default
import slugify
import environ
env = environ.Env(
# set casting, default value
DEBUG=(bool, False),
pages_root=(str,'../data'),
static_root=(str,'static'),
default_template=(str, 'gallery.html'),
url_prefix =(str, "/fotos"),
FLATPAGES_EXTENSION = (str, ".md"),
FLATPAGES_AUTO_RELOAD = (bool, True)
)
# Initialize application
app = Flask(__name__)
#app.config.update(cfg)
app.config["pages_root"]=os.path.abspath(env('pages_root'))
app.config["static_root"]=env('static_root')
app.config["default_template"]=env('default_template')
app.config["FLATPAGES_DEFAULT_TEMPLATE"]=env('default_template')
app.config["url_prefix"]=env('url_prefix')
app.config["FLATPAGES_EXTENSION"]=env('FLATPAGES_EXTENSION')
app.config["FLATPAGES_AUTO_RELOAD"]=env('FLATPAGES_AUTO_RELOAD')
app.config["FLATPAGES_ROOT"]=os.path.abspath(env('pages_root'))
app.logger.setLevel(logging.DEBUG)
# Initialize FlatPages Index
flatpages = FlatPagesIndex(app)
flatpages_index.Links.thumb_url=lambda s,x: url_for("intern.thumb",size=128,name=x)
flatpages_index.Links.image_url=lambda s,x: url_for("intern.post",name=x)
flatpages_index.Page.page_defaults={"type":"gallery", "template":"gallery.html"}
flatpages.cfg("url", lambda s,x: url_for("intern.post",name=x))
flatpages.cfg("thumb_url", lambda s,x: url_for("intern.thumb",size=512,name=x))
flatpages.get('index')
app.logger.info('Initialize FET Foto Gallery App')
app.logger.info('flatpages loaded %d pages' % len(flatpages._pages))
app.logger.info("Data directory is: %s" % flatpages.root)
freezer = Freezer(app)
page_blueprint = Blueprint('intern', __name__)
api_blueprint = Blueprint('api', __name__)
@app.template_filter()
def thumbimage(post):
if post.thumb_url:
return post.thumb_url
elif len(post.images)>0:
return post.images[0]
@app.template_filter()
def slug(string):
return slugify.slugify(string)
@page_blueprint.route('/thumb<int:size>/<path:name>')
def thumb(size=64,name=''):
if not size in [32,64,128,256,512]:
abort(404)
file_name=os.path.join(app.config["FLATPAGES_ROOT"],name)
thumb_name=os.path.join("thumbs","thumbs_%i" % size, name)
thumb_path, thumb_fn=os.path.split(thumb_name)
if os.path.exists(file_name)and not os.path.exists(thumb_name):
print("creating thumb")
image= Image.open(file_name,'r')
s=size, size
if image._getexif() is not None:
for orientation in ExifTags.TAGS.keys():
if ExifTags.TAGS[orientation]=='Orientation':
break
exif=dict(image._getexif().items())
if exif[orientation] == 3:
image=image.rotate(180, expand=True)
elif exif[orientation] == 6:
image=image.rotate(270, expand=True)
elif exif[orientation] == 8:
image=image.rotate(90, expand=True)
thumb=ImageOps.fit(image,s,Image.ANTIALIAS)
print("writing %s"% thumb_name)
os.makedirs(thumb_path,exist_ok=True)
thumb.save(thumb_name)
image.close()
thumb.close()
print("sending from %s file %s" % ("thumbs/thumbs_%i/" % size,name))
if not os.path.exists(os.path.join(thumb_path,thumb_fn)):
print ("doesn't exist")
return send_from_directory(os.path.join("../thumbs","thumbs_%i" % size),name)
@page_blueprint.route('/<path:name>/',strict_slashes=False)
@page_blueprint.route('/')
def post(name=''):
app.logger.debug("post_name: %s" % name)
page = flatpages.get(name)
if not page is None:
page["has_img"]=True
page.links.endpoint='intern.post'
app.logger.debug(dict(page))
return render_template(page["template"], post=page,
pth=page["dirpath"])
if os.path.exists(os.path.join(app.config["FLATPAGES_ROOT"],name)):
app.logger.debug("sending static:%s" % name)
return send_from_directory(app.config["FLATPAGES_ROOT"],name)
elif os.path.exists(os.path.join('static',name)):
print("send from static dir %s" % name)
return send_from_directory(os.path.abspath('static'),name)
#elif os.path.exists(os.path.join(cfg["fet_assets"],name)):
# return send_from_directory(cfg["fet_assets"],name)
elif os.path.exists(os.path.join("blueimp",name)):
return send_from_directory(os.path.abspath('blueimp'),name)
else:
return abort(404)
@api_blueprint.route('/<path:name>.json',strict_slashes=False)
@api_blueprint.route('/.json',strict_slashes=False)
def postjson(name='index'):
print("Post: %s" % name)
page = flatpages.get(name)
if not page is None:
page["has_img"]=True # can be overwritten by file
page.links.endpoint='api.postjson'
return jsonify(page=dict(page))
if os.path.exists(u'{}/{}'.format(FLATPAGES_ROOT,path)):
return send_from_directory(FLATPAGES_ROOT,path)
else:
return send_from_directory('static',path)
app.register_blueprint(page_blueprint, url_prefix=app.config["url_prefix"],static_folder='static')
app.register_blueprint(api_blueprint, url_prefix="/api/"+app.config["url_prefix"],static_folder='static')
app.add_url_rule('%s/<path:name>' % app.config["url_prefix"],'page', post)