109 lines
2.7 KiB
Python
109 lines
2.7 KiB
Python
#!/usr/bin/env python3
|
|
|
|
import traceback
|
|
import os
|
|
import posixpath
|
|
|
|
from flask import Flask, render_template, request
|
|
from pygments import formatters, highlight, lexers
|
|
import markdown
|
|
|
|
from src import (
|
|
utils,
|
|
config,
|
|
files,
|
|
)
|
|
|
|
# TODO: Put the creation of the Flask application into a function
|
|
# https://flask.palletsprojects.com/en/3.0.x/tutorial/factory/
|
|
# def create_app() -> flask.Flask:
|
|
app = Flask(
|
|
__name__,
|
|
template_folder="../templates",
|
|
static_folder="../static",
|
|
)
|
|
|
|
app.jinja_env.globals.update(
|
|
config=config,
|
|
path_join=posixpath.join,
|
|
)
|
|
|
|
|
|
@app.route('/', defaults={'path': ''})
|
|
@app.route('/<path:path>', methods=['POST', 'GET'])
|
|
def index(path):
|
|
data_path = config.get('data_path')
|
|
internal_path = os.path.join(data_path, path + '.md')
|
|
|
|
document_tree = files.DocumentTree.get_tree(data_path)
|
|
document_tree.print_tree()
|
|
|
|
# Checks ###################################################
|
|
|
|
if '..' in path:
|
|
return 'Path cannot contain double dots, i.e. "..".'
|
|
|
|
# If the user sent input, save it ##########################
|
|
|
|
if path == '':
|
|
return (
|
|
render_template(
|
|
"main.html",
|
|
path=path,
|
|
document_tree=document_tree,
|
|
markdown=markdown.markdown,
|
|
content='Welcome',
|
|
edit=False,
|
|
),
|
|
200,
|
|
)
|
|
|
|
raw_markdown = request.form.get('text', None)
|
|
if raw_markdown is not None:
|
|
with open(internal_path, 'w') as file:
|
|
file.write(str(raw_markdown))
|
|
|
|
# Get the document contents ################################
|
|
|
|
is_edit = 'edit' in request.args and path != ''
|
|
|
|
if os.path.exists(internal_path):
|
|
with open(internal_path) as file:
|
|
raw_markdown = file.read()
|
|
elif is_edit:
|
|
raw_markdown = f'# {path}\n\nChangeme'
|
|
else:
|
|
return (
|
|
render_template(
|
|
"error.html",
|
|
code=404,
|
|
msg=f'The path "{path}" does not exist.',
|
|
),
|
|
404,
|
|
)
|
|
|
|
# Actual serving ###########################################
|
|
|
|
return (
|
|
render_template(
|
|
"main.html",
|
|
path=path,
|
|
document_tree=document_tree,
|
|
markdown=markdown.markdown,
|
|
content=raw_markdown,
|
|
edit=is_edit,
|
|
),
|
|
200,
|
|
)
|
|
|
|
|
|
@ app.errorhandler(Exception)
|
|
def internal_error(e):
|
|
tb_text = "".join(traceback.format_exc())
|
|
|
|
lexer = lexers.get_lexer_by_name("pytb", stripall=True)
|
|
formatter = formatters.get_formatter_by_name("terminal")
|
|
tb_colored = highlight(tb_text, lexer, formatter)
|
|
print(tb_colored)
|
|
return utils.ERR_500
|