csv-to-marp-converter/rest_server.py
2021-06-21 12:25:54 +02:00

120 lines
3.2 KiB
Python

import os
from flask import Flask
from flask import render_template
from flask import request, send_from_directory
from flask_cors import CORS
from flask_httpauth import HTTPBasicAuth
from werkzeug.security import check_password_hash
from werkzeug.utils import redirect
import converter
app = Flask(__name__)
auth = HTTPBasicAuth()
app.config["DEBUG"] = True
CORS(app)
URL_BASE_PATH = "/"
import config_parser
UPLOAD_FODLER = config_parser.upload_path
OUTPUT_FODLER = config_parser.output_path
@auth.verify_password
def verify_password(username, password):
if username == config_parser.credentials['username'] and \
check_password_hash(config_parser.credentials['hashedPassword'], password):
return username
@app.route(URL_BASE_PATH, methods=["GET", "POST"])
@auth.login_required
def upload_image():
if request.method == "POST":
if request.files:
csv_file = request.files["csv"]
print(csv_file)
if not valid_csv(csv_file.filename):
# TODO give some feedback to user
return redirect(request.url)
from werkzeug.utils import secure_filename
filename = secure_filename(csv_file.filename)
output_file_path = os.path.join(UPLOAD_FODLER, filename)
if not os.path.exists(UPLOAD_FODLER):
os.makedirs(UPLOAD_FODLER)
# TODO save to different path in Porduction!
csv_file.save(output_file_path)
# run converter
if config_parser.prod_mode:
converter.convert(output_file_path, False)
else:
converter.convert(output_file_path, True)
return render_template("return_result.html")
# return redirect(request.url)
return render_template("upload-file.html")
def valid_csv(filename):
# We only want files with a . in the filename
if not "." in filename:
return False
# Split the extension from the filename
ext = filename.rsplit(".", 1)[1]
return ext == 'csv'
def get_marp_url():
if config_parser.prod_mode:
return "https://marp.swaghausen.de"
else:
return "http://localhost:4100"
@app.route('/marp')
def redirect_to_marp():
return redirect(get_marp_url(), code=302)
# return get_marp_url()
@app.route(URL_BASE_PATH + 'download', methods=['GET'])
# @auth.login_required
def download_file():
"""Download the .md file."""
# print("sending file with name: " + filename)
current_dir = os.getcwd()
full_dir = os.path.join(current_dir, OUTPUT_FODLER)
print("full_dir: " + full_dir)
return send_from_directory(full_dir, "slide-deck.md", as_attachment=True)
@app.route(URL_BASE_PATH + 'download-pdf', methods=['GET'])
# @auth.login_required
def download_pdf_file():
"""Download the .pdf file."""
# print("sending file with name: " + filename)
current_dir = os.getcwd()
full_dir = os.path.join(current_dir, OUTPUT_FODLER)
print("full_dir: " + full_dir)
return send_from_directory(full_dir, "slide-deck.pdf", as_attachment=True)
if __name__ == '__main__':
flask_options = dict(
host='0.0.0.0',
debug=True,
port=4003,
threaded=True,
)
app.run(**flask_options)