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.

48 lines
1.3 KiB
Python

#!/usr/bin/env/ python
from sys import stdout
from flask import Flask, Response, render_template, request
from pagedjs import make_pdf
from graft_a_tree import graft_a_tree
from io import StringIO
import sys
import textwrap
BASEURL = ''
MIN_GROW_YEARS = 0
MAX_GROW_YEARS = 25
app = Flask(__name__)
def wrap (text, width):
return'\n'.join([(' \\\n').join(textwrap.wrap(line, width=width - 2)) for line in text.splitlines()])
with open('graft_a_tree.py', 'r') as script:
source_code = script.read()
@app.route('{}/'.format(BASEURL))
def index():
return render_template('index.html', BASEURL=BASEURL)
@app.route('{}/graft'.format(BASEURL), methods=['POST'])
def graft():
years = max(MIN_GROW_YEARS, min(MAX_GROW_YEARS, int(request.form['years'])))
with StringIO() as script_stdout:
default_stdout = sys.stdout
sys.stdout = script_stdout
graft_a_tree(years)
content = script_stdout.getvalue()
sys.stdout = default_stdout
html = render_template('book.html', content=content, source_code=wrap(source_code, 100).replace(' ', '&nbsp;').replace('\n', '<br />'))
# print(html)
print('html rendered')
pdf = make_pdf(html)
print('made pdf')
r = Response(pdf, mimetype='application/pdf')
r.headers.extend({
'Content-Disposition': 'attachment; filename="grafted-tree.pdf"'
})
return r