flask server to upload csv file and download markdown and pdf

This commit is contained in:
dechert 2021-06-16 19:01:41 +02:00
parent 7986ab6bab
commit 409c14dd56
6 changed files with 224 additions and 1 deletions

View File

@ -84,7 +84,8 @@ def write_q_and_a_to_markdown_file(markdown_file, q_and_a):
alpha = alphabet[i]
markdown_file.writelines(' - {}) {}'.format(alpha, q_and_a.answerArray[i]))
markdown_file.writelines('---')
markdown_file.writelines('\n')
markdown_file.writelines('---') # TODO leave out for the last page?
return markdown_file

View File

@ -7,3 +7,4 @@ requests==2.25.1
urllib3==1.26.5
websocket-client==1.1.0
six==1.16.0 # needed for docker to run properly
Flask-Cors==3.0.10

138
rest_server.py Normal file
View File

@ -0,0 +1,138 @@
import os
from flask import Flask
from flask import render_template
from flask import request, send_from_directory
from flask import url_for
from flask_cors import CORS
# from flask_httpauth import HTTPBasicAuth
# from werkzeug.security import check_password_hash
# import main
from werkzeug.utils import redirect
# import config_parser
# from md_tagebuch import diary
import converter
app = Flask(__name__)
# auth = HTTPBasicAuth()
app.config["DEBUG"] = True
CORS(app)
URL_BASE_PATH = "/"
# URL_BASE_PATH = "/tagebuch"
# @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
OUTPUT_FODLER = "output"
UPLOAD_FODLER = "upload"
# @app.route(URL_BASE_PATH + 'home', methods=['GET'])
# # @auth.login_required
# def api_show_form():
# return render_template("index.html")
@app.route(URL_BASE_PATH, methods=["GET", "POST"])
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)
csv_file.save(output_file_path)
# run converter
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'
#
# @app.route(URL_BASE_PATH, methods=['POST', 'GET'])
# # @auth.login_required
# def tagebuch():
# if request.method == "POST":
# user_input = request.form['yearmonth']
# return redirect(url_for("return_result", yearmonth=user_input))
# else:
# return render_template("tagebuch.html")
#
#
# @app.route(URL_BASE_PATH + "<yearmonth>")
# # @auth.login_required
# def return_result(yearmonth):
# print(os.getcwd())
# filename = "slide-deck.md"
#
# print("filename to be served: " + filename)
# data = "test"
# full_file_path = os.path.join(OUTPUT_FODLER, filename)
#
# if os.path.exists(full_file_path):
# with open(full_file_path, 'r', encoding='UTF-8') as open_file:
# data = open_file.read()
# # return data
# # print(data)
# # open_file.close()
# # return f"<h1>{yearmonth}</h1>"
# # return "bla"
# return render_template("tagebuch_output.html", markdown_result=data, markdown_filename=filename)
@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")
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")
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)

35
templates/base.html Normal file
View File

@ -0,0 +1,35 @@
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>{% block title %} {% endblock %}</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col">
<h1 style="color: blue">{% block pageHeader %} {% endblock %}</h1>
<hr>
<!-- <p>This is an HTML file served up by Flask</p>-->
<p>{% block content %} {% endblock %}</p>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</div>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,15 @@
{% extends "base.html" %}
{% block pageHeader %} CSV to marp Markdown Converter {% endblock %}
{% block content %}
<h2>Result</h2>
<!--<textarea rows="4" cols="50"> {{markdown_result}} </textarea>-->
<p>
<!-- will call e.g. route /tagebuch/download/2021-02 -->
<a class="btn btn-primary" href="{{url_for('download_file')}}">Download Markdown File</a>
<a class="btn btn-primary" href="{{url_for('download_pdf_file')}}">Download PDF File</a>
</p>
{% endblock %}

View File

@ -0,0 +1,33 @@
{% extends "base.html" %}
{% block pageHeader %} CSV to marp Markdown Converter {% endblock %}
{% block content %}
<!--<div class="container">-->
<!-- <div class="row">-->
<!-- <div class="col">-->
<h2>Upload a CSV file</h2>
<form action="/" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label>Select csv file</label>
<!-- <div class="custom-file">-->
<!-- <input type="file" class="custom-file-input" name="csv" id="csv">-->
<!-- <label class="custom-file-label" for="csv">Select csv...</label>-->
<!-- </div>-->
<div class="file-upload-wrapper">
<input type="file" id="input-file-max-fs" class="file-upload" name="csv" data-max-file-size="2M"/>
</div>
</div>
<button type="submit" class="btn btn-primary">Upload</button>
</form>
{% endblock %}