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.

86 lines
2.1 KiB
Python

from flask import Flask, render_template, Response, abort, url_for
# from weasyprint import HTML
import os
from pagedjs import make_pdf_from_url
from settings import DEBUG, HTML_TMP_DIR, SITEURL
import tempfile
from werkzeug.security import safe_join
app = Flask(__name__)
"""
Shows the index page of the application
"""
@app.route('/')
def index():
return render_template('index.html')
"""
This is where the book generation happens.
Possibly adjust the allowed methods.
"""
@app.route('/generate', methods=['GET', 'POST'])
def generate ():
"""
Insert your own Python code in this function.
"""
# Rendering of the template. Forward generated data to the template
# using named arguments, for example, if a variable chapters was generated
# you can add it to the function like so:
# html = render_template('book.html', DEBUG=DEBUG, chapters=chapters)
html = render_template('book.html', DEBUG=DEBUG)
if (DEBUG):
return html
else:
pdf = make_pdf(html)
r = Response(pdf, mimetype='application/pdf')
r.headers.extend({
'Content-Disposition': 'attachment; filename="Title of the.pdf"'
})
return r
"""
Proxy(?) for pagedjs, it stores the provided html in a separate file.
Now pagedjs can connect to the application through HTTP.
This way static files, like fonts, images and css can be served in a regular way.
"""
def make_pdf (html):
if not os.path.exists(HTML_TMP_DIR):
os.mkdir(HTML_TMP_DIR)
with tempfile.NamedTemporaryFile(mode='w', prefix='book_', dir=HTML_TMP_DIR, delete=False) as tmpfile:
tmpfile.write(html)
tmpfile.flush()
bookname = os.path.basename(tmpfile.name)
url = SITEURL + url_for('show_book', bookname=bookname)
tmpfile.close()
# Generate the pdf with pagedjs
return make_pdf_from_url(url)
"""
View for pagedjs. It loads the generated HTML from the tmp dir and returns it.
"""
@app.route('/book/<string:bookname>')
def show_book (bookname):
bookpath = safe_join(HTML_TMP_DIR, bookname)
if os.path.exists(bookpath):
with open(bookpath, 'r') as h:
html = h.read()
return html
abort(404)