Created
July 7, 2015 11:54
-
-
Save ecarreras/fd9205d29bb7255430aa to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from ast import literal_eval | |
import tempfile | |
import subprocess | |
from flask import Flask, abort, request, Response | |
from flask.ext.mako import MakoTemplates, render_template | |
from destral.openerp import OpenERPService | |
from destral.transaction import Transaction | |
os.environ.update({ | |
'OPENERP_DB_NAME': '', | |
'OPENERP_DB_USER': '', | |
'OPENERP_DB_PASSWORD': '', | |
'OPENERP_DB_HOST': '', | |
'OPENERP_ADDONS_PATH': '', | |
'OPENERP_ROOT_PATH': '', | |
'OPENERP_MONGODB_NAME': '', | |
'OPENERP_MONGODB_HOST': '', | |
'EMPOWERING_COMPANY_ID': '', | |
'EMPOWERING_DEBUG': '', | |
'EMPOWERING_CERT_FILE': '', | |
'EMPOWERING_KEY_FILE': '' | |
}) | |
app = Flask(__name__) | |
mako = MakoTemplates(app) | |
app.template_folder = os.getcwd() | |
def arg_eval(var): | |
try: | |
return literal_eval(var) | |
except Exception: | |
return var | |
class RenderReport(object): | |
def __init__(self, content): | |
self.content = content | |
self.html_file = tempfile.mkstemp(suffix='.html')[1] | |
with open(self.html_file, 'w') as f: | |
f.write(content) | |
self.output = tempfile.mkstemp(suffix='.pdf')[1] | |
def __enter__(self): | |
return self | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
os.unlink(self.html_file) | |
os.unlink(self.output) | |
def render(self): | |
command = [ | |
'wkhtmltopdf', | |
'--margin-top', '0', | |
'--margin-bottom', '0', | |
'--margin-left', '0', | |
'--margin-right', '0', | |
'--page-size', 'A4', | |
'--orientation', 'Portrait', | |
'--load-error-handling', 'ignore', | |
self.html_file, | |
self.output | |
] | |
subprocess.call(command) | |
with open(self.output, 'r') as f: | |
return f.read() | |
@app.route('/<path:report>') | |
def index(report): | |
app.logger.info('Rendering report: %s', report) | |
if not os.path.exists(report): | |
abort(404) | |
args = {} | |
for key, value in request.args.iteritems(): | |
args[key] = arg_eval(value) | |
if 'ids' not in args: | |
abort(404) | |
if 'model' not in args: | |
abort(404) | |
service = OpenERPService() | |
with Transaction().start(service.db_name) as txn: | |
objects = service.pool.get(args['model']).browse(txn.cursor, txn.user, args['ids']) | |
html = render_template(report, objects=objects, **args) | |
with RenderReport(html) as rnd: | |
pdf = rnd.render() | |
return Response(pdf, mimetype='application/pdf') | |
if __name__ == '__main__': | |
app.run(debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment