Skip to content

Commit

Permalink
Merge pull request #189 from multiflexi/update_presenters
Browse files Browse the repository at this point in the history
Update presenters
  • Loading branch information
milankowww authored Nov 29, 2023
2 parents a70a9fa + ef29301 commit 0c5b3d2
Show file tree
Hide file tree
Showing 8 changed files with 370 additions and 411 deletions.
54 changes: 5 additions & 49 deletions docker/Dockerfile.presenters
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM python:3.7-alpine3.14 AS build_shared
FROM python:3.12-alpine3.18 AS build_shared

WORKDIR /build_shared/

Expand All @@ -8,7 +8,7 @@ RUN python -m build



FROM python:3.7-alpine3.14 AS production
FROM python:3.12-alpine3.18 AS production

WORKDIR /app/

Expand All @@ -20,59 +20,15 @@ RUN \
apk add --no-cache \
libpng \
libjpeg \
wkhtmltopdf
py3-gobject3 \
pango

# install fonts
RUN \
apk add --no-cache \
msttcorefonts-installer \
fontconfig \
font-noto \
font-noto-adlam \
font-noto-adlamunjoined \
font-noto-arabic \
font-noto-armenian \
font-noto-avestan \
font-noto-bamum \
font-noto-bengali \
font-noto-buhid \
font-noto-carian \
font-noto-chakma \
font-noto-cherokee \
font-noto-cypriot \
font-noto-deseret \
font-noto-devanagari \
font-noto-ethiopic \
font-noto-extra \
font-noto-georgian \
font-noto-glagolitic \
font-noto-gothic \
font-noto-gujarati \
font-noto-gurmukhi \
font-noto-hebrew \
font-noto-kannada \
font-noto-kayahli \
font-noto-khmer \
font-noto-lao \
font-noto-lisu \
font-noto-malayalam \
font-noto-mandaic \
font-noto-myanmar \
font-noto-nko \
font-noto-olchiki \
font-noto-oldturkic \
font-noto-oriya \
font-noto-osage \
font-noto-osmanya \
font-noto-shavian \
font-noto-sinhala \
font-noto-tamil \
font-noto-telugu \
font-noto-thaana \
font-noto-thai \
font-noto-tibetan \
font-noto-tifinagh \
font-noto-vai \
font-noto-all \
terminus-font \
ttf-opensans \
font-bakoma \
Expand Down
22 changes: 17 additions & 5 deletions src/presenters/managers/auth_manager.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
"""Authorization manager for the API.
Returns:
wrapper: Wrapper function for the API endpoints.
"""
from functools import wraps
from flask import request
import os
import ssl

api_key = os.getenv('API_KEY')
api_key = os.getenv("API_KEY")

if os.getenv('SSL_VERIFICATION') == "False":
if os.getenv("SSL_VERIFICATION") == "False":
try:
_create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
Expand All @@ -15,11 +20,18 @@


def api_key_required(fn):
"""Check for API key in the request header.
Arguments:
fn -- The function to be decorated.
Returns:
wrapper: Wrapper function for the API endpoints.
"""

@wraps(fn)
def wrapper(*args, **kwargs):

if not request.headers.has_key('Authorization') or request.headers['Authorization'] != ('Bearer ' + api_key):
return {'error': 'not authorized'}, 401
if "Authorization" not in request.headers.keys() or request.headers["Authorization"] != ("Bearer " + api_key):
return {"error": "not authorized"}, 401
else:
return fn(*args, **kwargs)

Expand Down
97 changes: 49 additions & 48 deletions src/presenters/presenters/pdf_presenter.py
Original file line number Diff line number Diff line change
@@ -1,96 +1,97 @@
"""PDF Presenter.
Returns:
dict: mime type and base64 encoded data of the generated PDF document
"""
import datetime
import os
import tempfile
from base64 import b64encode
import jinja2
import pdfkit
from weasyprint import HTML

from .base_presenter import BasePresenter
from shared.schema.parameter import Parameter, ParameterType


class PDFPresenter(BasePresenter):
"""PDF Presenter class.
Args:
BasePresenter (class): Base presenter class
"""

type = "PDF_PRESENTER"
name = "PDF Presenter"
description = "Presenter for generating PDF documents"

parameters = [
Parameter(0, "HEADER_TEMPLATE_PATH", "Header template path", "Path of header template file",
ParameterType.STRING),
Parameter(0, "BODY_TEMPLATE_PATH", "Body template path", "Path of body template file",
ParameterType.STRING),
Parameter(0, "FOOTER_TEMPLATE_PATH", "Footer template path", "Path of footer template file",
ParameterType.STRING)
]
parameters = [Parameter(0, "PDF_TEMPLATE_PATH", "Template path", "Path of header template file", ParameterType.STRING)]

parameters.extend(BasePresenter.parameters)

def generate(self, presenter_input):
"""Generate PDF document.
Args:
presenter_input (_type_): Parameters from settings
Returns:
dict: mime type and base64 encoded data of the generated PDF document
"""
try:
temporary_directory = tempfile.gettempdir() + "/"
output_body_html = temporary_directory + 'pdf_body.html'
output_pdf = temporary_directory + 'pdf_report__' + datetime.datetime.now().strftime(
"%d-%m-%Y_%H:%M") + '.pdf'
output_html = temporary_directory + "pdf_body.html"
output_pdf = temporary_directory + "pdf_report__" + datetime.datetime.now().strftime("%d-%m-%Y_%H:%M") + ".pdf"

pdf_header_template = presenter_input.parameter_values_map['HEADER_TEMPLATE_PATH']
pdf_footer_template = presenter_input.parameter_values_map['FOOTER_TEMPLATE_PATH']
head, tail = os.path.split(presenter_input.parameter_values_map['BODY_TEMPLATE_PATH'])
head, tail = os.path.split(presenter_input.parameter_values_map["PDF_TEMPLATE_PATH"])

input_data = BasePresenter.generate_input_data(presenter_input)

env = jinja2.Environment(loader=jinja2.FileSystemLoader(head))
env.filters["strfdate"] = BasePresenter._filter_datetime
body = env.get_template(tail)
output_text = body.render(data=input_data)
with open(output_body_html, 'w') as output_file:
pdf = env.get_template(tail)
output_text = pdf.render(data=input_data)
with open(output_html, "w") as output_file:
output_file.write(output_text)

if not os.path.exists(temporary_directory):
os.mkdir(temporary_directory)

options = {
'dpi': 500,
'page-size': 'A4',
'margin-top': '1.55in',
'margin-right': '0.75in',
'margin-bottom': '1.55in',
'margin-left': '0.75in',
'encoding': "UTF-8",
'header-html': pdf_header_template,
'footer-html': pdf_footer_template,
'custom-header': [
('Accept-Encoding', 'gzip')
],
'no-outline': None,
'enable-local-file-access': None
}

pdfkit.from_file(input=output_body_html, output_path=output_pdf, options=options)

encoding = 'UTF-8'
# options = {
# 'dpi': 500,
# 'page-size': 'A4',
# 'margin-top': '1.55in',
# 'margin-right': '0.75in',
# 'margin-bottom': '1.55in',
# 'margin-left': '0.75in',
# 'encoding': "UTF-8",
# 'header-html': pdf_header_template,
# 'footer-html': pdf_footer_template,
# 'custom-header': [
# ('Accept-Encoding', 'gzip')
# ],
# 'no-outline': None,
# 'enable-local-file-access': None
# }
HTML(output_html).write_pdf(output_pdf)

encoding = "UTF-8"
file = output_pdf

with open(file, 'rb') as open_file:
with open(file, "rb") as open_file:
byte_content = open_file.read()

base64_bytes = b64encode(byte_content)

data = base64_bytes.decode(encoding)

presenter_output = {
'mime_type': 'application/pdf',
'data': data
}
presenter_output = {"mime_type": "application/pdf", "data": data}

os.remove(output_body_html)
os.remove(output_html)
os.remove(file)

return presenter_output
except Exception as error:
BasePresenter.print_exception(self, error)
presenter_output = {
'mime_type': 'text/plain',
'data': b64encode(("TEMPLATING ERROR\n"+str(error)).encode()).decode('UTF-8')
}
presenter_output = {"mime_type": "text/plain", "data": b64encode(("TEMPLATING ERROR\n" + str(error)).encode()).decode("UTF-8")}
return presenter_output
25 changes: 9 additions & 16 deletions src/presenters/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,17 +1,10 @@
Flask==1.1.4
Flask-Cors==3.0.10
Flask-RESTful==0.3.7
gevent==21.8.0
greenlet==1.1.1
gunicorn==20.0.4
Jinja2==2.11.3
MarkupSafe==1.1.0
marshmallow==3.18.0
Flask==3.0.0
Flask-Cors==4.0.0
Flask-RESTful==0.3.10
gevent==23.9.1
gunicorn==21.2.0
Jinja2==3.1.2
marshmallow==3.20.1
marshmallow-enum==1.5.1
pdfkit==0.6.1
PyJWT==1.7.1
python-dotenv==0.10.5
pytz==2019.3
PyYAML==6.0.1
six==1.14.0
Werkzeug==0.16.0
python-dotenv==1.0.0
weasyprint==60.1
Loading

0 comments on commit 0c5b3d2

Please sign in to comment.