You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

94 lines
2.4 KiB
Python

import os
from flask import Flask, render_template, url_for, send_from_directory, request, redirect
import frontmatter
import markdown
from prefix import PrefixMiddleware
from dotenv import load_dotenv
from time import strftime, localtime
import glob
import subprocess
load_dotenv()
prefix = os.environ.get('URL_PREFIX', '')
port = os.environ.get('PORT', 3000)
debug = os.environ.get('DEBUG', False)
update_script = os.environ.get('UPDATE', 'update.sh' )
# ---
# Functions
# ---
def list_files(folder, remove_ext=False):
''' Read all the functions in a folder '''
names = []
for entry in os.scandir(folder):
# add to the list only proper files
if entry.is_file(follow_symlinks=False):
# remove the extension from the filename
n = entry.name
if remove_ext:
n = os.path.splitext(entry.name)[0]
names.append(n)
return names
def txt_list():
''' Generate list of writings '''
files = sorted(filter(os.path.isfile, glob.glob('txt/[!.]*.md')), key=lambda file: os.path.getmtime(file), reverse=True)
writings = []
for file in files:
with open(file) as f:
meta, content = frontmatter.parse(f.read())
meta['slug'] = os.path.splitext(os.path.basename(file))[0]
meta['last_edit'] = strftime('%d.%m.%Y', localtime(os.path.getmtime(file)))
writings.append(meta)
return writings
def render_list():
subprocess.run(['sh', update_script], shell=True)
with open('list.html', 'w+') as f:
f.write(render_template('home.html', writings=txt_list()))
# ---
# Create Flask App
# ---
app = Flask(__name__)
app.wsgi_app = PrefixMiddleware(app.wsgi_app, prefix=prefix)
# ---
# Routes
# ---
@app.route('/')
def home():
return send_from_directory(app.root_path,'list.html')
@app.route('/txt/<slug>')
def txt(slug):
try:
with open(f'txt/{slug}.md') as f:
meta, content = frontmatter.parse(f.read())
text = {**meta}
text['content']=markdown.markdown(content)
return render_template('text.html', text=text)
except FileNotFoundError:
return 'File not found!'
@app.route('/api/update', methods=['GET', 'POST'])
def update():
render_list()
if request.method == 'POST':
render_list()
return redirect(url_for('home'))
# ---
# Run the app
# ---
app.run(port=port, debug=debug)