Skip to content

Commit

Permalink
test template
Browse files Browse the repository at this point in the history
  • Loading branch information
piti118 committed Aug 21, 2016
1 parent bdbd8dd commit f8000f9
Show file tree
Hide file tree
Showing 13 changed files with 140 additions and 84 deletions.
30 changes: 22 additions & 8 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,38 @@
from flask import Flask
from flask import Flask, request, jsonify, send_file
import werkzeug
from templates import sample_template
from templates import sample_template, ultimate_sample_template

def make_pdf(data, tempdir):
t = sample_template.SampleTemplate()
return t.compile(data, tempdir)
basic_template = sample_template.SampleTemplate()
ultimate_template = ultimate_sample_template.UltimateSampleTemplate()

app = Flask(__name__)
app.debug = True
app.config.update(PROPAGATE_EXCEPTIONS=True, DEBUG=True)
@app.route('/report', methods=['POST'])


@app.route('/basic', methods=['POST'])
def basic():
if request.is_json:
data = request.get_json()
with TemporaryDirectory() as tempdir:
app.logger.info('working on %s' % tempdir)
pdf = basic_template.compile(data, tempdir)
return send_file(pdf,
as_attachment=True,
attachment_filename='basic.pdf')
else:
return jsonify(error=400, message='Body is not valid json'), 400

@app.route('/ultimate', methods=['POST'])
def report():
if request.is_json:
data = request.get_json()
with TemporaryDirectory() as tempdir:
app.logger.info('working on %s' % tempdir)
pdf = make_pdf(data, tempdir)
pdf = ultimate_template.compile(data, tempdir)
return send_file(pdf,
as_attachment=True,
attachment_filename='report.pdf')
as_attachment=True,
attachment_filename='ultimate.pdf')
else:
return jsonify(error=400, message='Body is not valid json'), 400
16 changes: 10 additions & 6 deletions latex_compiler.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
from os import path
import subprocess

def compile(driver_file, cwd):
def compile(driver_file, cwd, pipe=True):
# compile
out = subprocess.run(['xelatex', driver_file],
cwd=cwd,
stdout=subprocess.PIPE)

print('wtf')
opt = dict(stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
opt = opt if pipe else {}
out = subprocess.run(['xelatex', '-halt-on-error', driver_file],
cwd=cwd)
# stdout=subprocess.PIPE,
# stderr=subprocess.STDOUT)
base = path.splitext(driver_file)[0]

if out.returncode == 0:
return path.join(cwd, base+'.pdf')
else:
raise Exception('Fail to compile: ' + out.stdout.decode('utf-8'))
output = out.stdout.decode('utf-8') if pipe else 'See above'
raise Exception('Fail to compilation: ' + output)
16 changes: 7 additions & 9 deletions template_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,26 +20,24 @@ def preprocess(self, data, cwd):
return data

def get_template(self, data):
return None
raise NotImplementedError()

def compile(self, data, cwd):
def compile(self, data, cwd, pipe=True):
# evaluate template
data = self.preprocess(data, cwd)
print(data)
template_file = self.get_template(data)
if template_file is None:
raise Exception('template_file returns None: Did you override get_template?')
print(template_file, 'sssss')
template = self.jinja.get_template(template_file)
print(template, 'wwwww')

output = template.render(**data)
print(output)
# write output to file ready to compile
driver_file = path.join(cwd, 'driver.tex')
with open(driver_file, 'w') as f:
f.write(output)

# compile
pdf_file = latex_compiler.compile(driver_file, cwd)
pdf_file = latex_compiler.compile('driver.tex', cwd, pipe)
print(pdf_file)
return pdf_file

def sample_data(self):
raise NotImplementedError()
10 changes: 9 additions & 1 deletion templates/sample_template/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
from template_base import TemplateBase
from os import path

__all__=['SampleTemplate']
__all__ = ['template']


def template():
return SampleTemplate()


class SampleTemplate(TemplateBase):
def __init__(self):
Expand All @@ -19,3 +24,6 @@ def preprocess(self, data, cwd):

def get_template(self, data):
return 'template.tex'

def sample_data(self, data):
return {"x": 2, "y": "hellooooooooooow"}
29 changes: 29 additions & 0 deletions templates/ultimate_sample_template/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from template_base import TemplateBase
from os import path
import shutil
__all__=['template']

def template():
return UltimateSampleTemplate()

class UltimateSampleTemplate(TemplateBase):
def __init__(self):
super().__init__(path.dirname(__file__)) #this setup jinja loader
pass

def preprocess(self, data, cwd):
"""
should return a dictionary with all the data
some additional data might be build here
This is the place where we should render graph and put the output
file name in the directory
"""
asset_dir = path.join(path.dirname(__file__), 'assets')
shutil.copytree(asset_dir, path.join(cwd, 'assets')) #should we symlink instead?
return data

def get_template(self, data):
return 'template.tex'

def sample_data(self):
return { "name": "ปิติ" }
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
35 changes: 35 additions & 0 deletions templates/ultimate_sample_template/template.tex
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
\documentclass[12pt]{article}

\usepackage{fontspec}
\usepackage{xltxtra}
\XeTeXlinebreaklocale "th_TH"
\XeTeXlinebreakskip = 0pt plus 1pt
\usepackage{fonts-tlwg}

\setmainfont[
Path=assets/,
BoldFont={THSarabunNew Bold.ttf},
ItalicFont={THSarabunNew Italic.ttf},
BoldItalicFont={THSarabunNew BoldItalic.ttf},
]{THSarabunNew.ttf}


\begin{document}

International Text

สวัสดี (((name))) (((thainame)))

Embed Static Image

\begin{center}
\includegraphics[width=0.7\linewidth]{assets/birthday-cake}
\end{center}

Embed dynamic image เช่น graph ได้เหมือนกัน
\begin{center}
\includegraphics[width=0.7\linewidth]{graph}
\end{center}


\end{document}
56 changes: 0 additions & 56 deletions test.py

This file was deleted.

32 changes: 28 additions & 4 deletions test_template.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,31 @@
from templates import sample_template
from templates import sample_template, ultimate_sample_template
from os import path
from importlib import import_module
import os
import shutil
import sys
import argparse

tmpdir = path.join(path.dirname(__file__), 'temp')

t = sample_template.SampleTemplate()
t.compile({"x": "abc", "y": "def"}, tmpdir)
def main(module_name):
# module_name = 'templates.ultimate_sample_template'

module = import_module(module_name)

t = module.template()
tmpdir = path.join(path.dirname(__file__), 'tmp')
print('Working on '+tmpdir)
shutil.rmtree(tmpdir)
os.makedirs(tmpdir)
t.compile(t.sample_data(), tmpdir, pipe=False)

print('see output at '+tmpdir+'/driver.pdf')


if __name__ == '__main__':
parser = argparse.ArgumentParser(description=
'Test template. Ex: python test_template.py templates.sample_template')
parser.add_argument('module', metavar='module', type=str, nargs=1,
help='template module name(ex: templates.sample_template)')
args = parser.parse_args()
main(args.module[0])

0 comments on commit f8000f9

Please sign in to comment.