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

2 years ago
import os
2 years ago
from flask import Flask, render_template, url_for, send_from_directory, request, redirect
2 years ago
import frontmatter
import markdown
from prefix import PrefixMiddleware
from dotenv import load_dotenv
from time import strftime, localtime
import glob
2 years ago
import subprocess
2 years ago
load_dotenv()
prefix = os.environ.get('URL_PREFIX', '')
port = os.environ.get('PORT', 3000)
debug = os.environ.get('DEBUG', False)
2 years ago
update_script = os.environ.get('UPDATE', 'update.sh' )
2 years ago
# ---
# 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
2 years ago
def render_list():
2 years ago
subprocess.run(update_script, shell=True)
2 years ago
with open('list.html', 'w+') as f:
f.write(render_template('home.html', writings=txt_list()))
2 years ago
# ---
# Create Flask App
# ---
app = Flask(__name__)
app.wsgi_app = PrefixMiddleware(app.wsgi_app, prefix=prefix)
# ---
# Routes
# ---
@app.route('/')
def home():
2 years ago
return send_from_directory(app.root_path,'list.html')
2 years ago
@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!'
2 years ago
@app.route('/api/update', methods=['GET', 'POST'])
def update():
render_list()
if request.method == 'POST':
render_list()
return redirect(url_for('home'))
2 years ago
# ---
# Run the app
# ---
2 years ago
app.run(port=port, debug=debug)