Added lockfile system

This commit is contained in:
thematdev 2021-09-22 14:29:02 +03:00
parent 383df2fb68
commit 636ac88daf
2 changed files with 47 additions and 5 deletions

View File

@ -1,7 +1,8 @@
from flask import Flask, url_for, render_template
from flask import Flask, url_for, render_template, abort
import os
import json
from app.config import PANDOC_LINK, PANDOC_PATH
from app.hash_manager import hash_file_sha512
import subprocess
app = Flask(__name__)
@ -24,17 +25,41 @@ def dated_url_for(endpoint, **values):
return url_for(endpoint, **values)
def render_page(page):
path = f'{PANDOC_PATH}/{page}'
if not os.path.exists(f'{path}'):
raise Exception("Page doesn't exist!")
in_filename = f'{path}/main.md'
out_filename = f'{path}/render.html'
os.system(f'pandoc {in_filename} --to html --mathjax --output {out_filename}')
print('Creating lock file')
os.system(f'echo {hash_file_sha512(in_filename)} > {out_filename}.lock')
@app.route(f'/{PANDOC_LINK}/<page>')
def get_pandoc_page(page):
with open(f'{PANDOC_PATH}/{page}/config.json') as f:
path = f'{PANDOC_PATH}/{page}'
if not os.path.exists(f'{path}'):
abort(404)
with open(f'{path}/config.json') as f:
data = json.loads(f.read())
filename = f'{PANDOC_PATH}/{page}/main.md'
inserted = subprocess.Popen(f'pandoc {filename} -t html --mathjax', shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')
if not os.path.exists(f'{path}/render.html') or not os.path.exists(f'{path}/render.html.lock'):
print('Rendered page or lockfile for {page} does not exist! Rendering {page}')
render_page(page)
else:
with open(f'{path}/render.html.lock', 'r') as f:
rendered_hash = f.read().strip()
current_hash = hash_file_sha512(f'{path}/main.md')
if rendered_hash != current_hash:
print(f'CURRENT: {current_hash}, RENDERED: {rendered_hash}')
print('Integrity test failed, rendering {page}!')
render_page(page)
template = data['template']
with open(f'{path}/render.html', 'r') as f:
inserted = f.read()
return render_template(template, markdown=inserted)
@app.route('/')
def index():
return render_template('index.html')

17
app/hash_manager.py Normal file
View File

@ -0,0 +1,17 @@
import hashlib
BUF_SZ = 4096
def hash_file_sha512(filename):
res = hashlib.sha512()
with open(filename, 'rb') as f:
data = f.read(BUF_SZ)
while data:
res.update(data)
data = f.read(BUF_SZ)
return res.hexdigest()