From a35311111e15396ada5f54028aaca8124a7d6792 Mon Sep 17 00:00:00 2001 From: Simon Bruder Date: Fri, 5 Jul 2019 20:47:56 +0000 Subject: [PATCH] backend: always send etags to make use of cache-control --- backend.py | 7 +++++-- mangareader.py | 16 +++++++++++++--- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/backend.py b/backend.py index 787319b..1e9e625 100644 --- a/backend.py +++ b/backend.py @@ -184,16 +184,19 @@ class CalibreDB: path = self.get_volume_filepath(volume_id) with ZipFile(path, 'r') as volume: try: - page_filename = volume.filelist[page_number - 1].filename + zip_info = volume.filelist[page_number - 1] except IndexError: raise exceptions.NotFound() return None + page_filename = zip_info.filename + page_data = BytesIO() page_data.write(volume.read(page_filename)) page_data.seek(0) return { 'data': page_data, - 'mimetype': mimetypes[os.path.splitext(page_filename)[1]] + 'mimetype': mimetypes[os.path.splitext(page_filename)[1]], + 'etag': str(zip_info.CRC) } diff --git a/mangareader.py b/mangareader.py index c5c6af5..a40116b 100755 --- a/mangareader.py +++ b/mangareader.py @@ -3,6 +3,7 @@ from backend import CalibreDB from flask import Flask, jsonify, send_from_directory, send_file, render_template, request from flask_cors import CORS from werkzeug.routing import BaseConverter +from zlib import crc32 import os @@ -10,6 +11,13 @@ def send_from_cwd(filename): return send_from_directory(os.getcwd(), filename) +def send_file_with_etag(fp, **kwargs): + response = send_file(fp, **kwargs) + response.set_etag(str(crc32(fp.read()))) + fp.seek(0) + return response + + app = Flask(__name__, static_folder='frontend/dist/static', template_folder='frontend/dist') app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 604800 # 1 week CORS(app) @@ -37,7 +45,7 @@ def get_series_cover(series_id): @app.route('/api/series//cover/thumbnail') def get_series_cover_thumbnail(series_id): thumbnail = db.get_series_cover_thumbnail(series_id) - return send_file(thumbnail, mimetype='image/jpeg') + return send_file_with_etag(thumbnail, mimetype='image/jpeg') @app.route('/api/series/') @@ -53,7 +61,7 @@ def get_volume_cover(volume_id): @app.route('/api/volume//cover/thumbnail') def get_volume_cover_thumbnail(volume_id): thumbnail = db.get_volume_cover_thumbnail(volume_id) - return send_file(thumbnail, mimetype='image/jpeg') + return send_file_with_etag(thumbnail, mimetype='image/jpeg') @app.route('/api/volume/') @@ -64,7 +72,9 @@ def get_volume_info(volume_id): @app.route('/api/volume//page/') def get_volume_page(volume_id, page_number): page = db.get_volume_page(volume_id, page_number) - return send_file(page['data'], mimetype=page['mimetype']) + response = send_file(page['data'], mimetype=page['mimetype']) + response.set_etag(page['etag']) + return response if __name__ == '__main__':