Skip to content

Commit 857ec21

Browse files
committed
Cache loaded YAML
This gives me an 80+% speedup when freezing the site (5.3s→0.6s)
1 parent cc4e5e6 commit 857ec21

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

bookshelf.py

+15-4
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import collections
55
import json
66
from pathlib import Path
7+
import functools
78

89
from flask import Flask, render_template, url_for, abort, send_from_directory, jsonify
910
from flask_frozen import Freezer
@@ -102,15 +103,25 @@ def find_photo(book_slug):
102103

103104

104105
def read_yaml(filename, default=MISSING):
106+
107+
# Reading YAML is slow. To avoid loading all the time, we cache the result.
108+
# To make the site react to changes in the files, we use the file size
109+
# and last-modified time as part of the cache key. If either changes,
110+
# the cache will be invalidated and the file will be read from disk again.
111+
105112
try:
106-
file = open(filename, encoding='utf-8')
113+
info = os.stat(filename)
107114
except FileNotFoundError:
108115
if default is MISSING:
109116
raise
110117
return default
111-
with file:
112-
data = yaml.safe_load(file)
113-
return data
118+
return _read_yaml_cached(filename, info.st_size, info.st_mtime)
119+
120+
121+
@functools.lru_cache()
122+
def _read_yaml_cached(filename, size, mtime):
123+
with open(filename, encoding='utf-8') as file:
124+
return yaml.safe_load(file)
114125

115126

116127
@app.context_processor

0 commit comments

Comments
 (0)