Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stage #8

Merged
merged 3 commits into from
Dec 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified .DS_Store
Binary file not shown.
5 changes: 5 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules
.serverless
.github
layers
scripts
2 changes: 1 addition & 1 deletion .isort.cfg
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
[settings]
known_third_party =boto3,fitz,jinja2,pdfkit,pydantic,pynamodb
known_third_party =boto3,fitz,jinja2,pydantic,pynamodb,weasyprint
17 changes: 17 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
FROM public.ecr.aws/lambda/python:3.8


ARG FUNCTION_DIR="/var/task"
RUN mkdir -p ${FUNCTION_DIR}

RUN pip install pipenv
RUN yum install -y pango

COPY Pipfile ${LAMBDA_TASK_ROOT}
COPY Pipfile.lock ${LAMBDA_TASK_ROOT}

RUN pipenv install --system --deploy --ignore-pipfile

COPY . ${LAMBDA_TASK_ROOT}

CMD [ "handler.generate_certificate_handler" ]
4 changes: 2 additions & 2 deletions Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ boto3 = "==1.22.7"
pydantic = {version = "<2", extras = ["email"]}
python-dotenv = "==1.0.0"
jinja2 = "==3.1.2"
pdfkit = "1.0.0"
pillow = "==10.1.0"
pymupdf = "==1.23.6"
pynamodb = "==5.5.0"
pynamodb = "==5.5.1"
weasyprint = "==52.5"

[dev-packages]
pre-commit = "==3.3.3"
Expand Down
265 changes: 200 additions & 65 deletions Pipfile.lock

Large diffs are not rendered by default.

Binary file not shown.
26 changes: 26 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"license": "MIT",
"devDependencies": {
"serverless-iam-roles-per-function": "^3.2.0",
"serverless-plugin-log-retention": "^2.0.0",
"serverless-python-requirements": "^6.0.0"
}
}
6 changes: 3 additions & 3 deletions resources/generate_certificate.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
generate:
certMaker:
handler: handler.generate_certificate_handler
timeout: 900
layers:
- Ref: WkhtmltopdfLambdaLayer
- Ref: WeazyprintLambdaLayer
- Ref: PythonRequirementsLambdaLayer
timeout: 900
events:
- sqs:
arn:
Expand Down
24 changes: 12 additions & 12 deletions s3/data_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

from s3.exceptions import PdfServiceInternalError
from s3.s3_constants import PresignedURLMethod
from utils.logger import logger


# pylint: disable=broad-except
Expand All @@ -18,7 +19,6 @@ class S3DataStore:
def __init__(self, bucket_name=os.environ['S3_BUCKET']):
self.__s3_client = boto3_client('s3')
self.__bucket_name = bucket_name
self.__logger = logging.getLogger()

def upload_file(self, file_name: str, object_name: str = None, verbose: bool = True) -> bool:
result = True
Expand All @@ -30,10 +30,10 @@ def upload_file(self, file_name: str, object_name: str = None, verbose: bool = T
try:
self.__s3_client.upload_file(file_name, self.__bucket_name, object_name)
if verbose:
self.__logger.info('Stored file in S3: %s/%s', self.__bucket_name, object_name)
logger.info('Stored file in S3: %s/%s', self.__bucket_name, object_name)
except Exception as e:
message = f'Failed to upload file ({file_name}) to S3, Reason: {type(e).__name__} - {str(e)}'
self.__logger.error(message)
logger.error(message)
raise PdfServiceInternalError(status_code=HTTPStatus.INTERNAL_SERVER_ERROR, message=message) from e

return result
Expand All @@ -44,10 +44,10 @@ def download_file(self, object_name: str, file_name: str, verbose: bool = True)
try:
self.__s3_client.download_file(self.__bucket_name, object_name, file_name)
if verbose:
self.__logger.info('Downloaded file in S3: %s/%s', self.__bucket_name, object_name)
logger.info('Downloaded file in S3: %s/%s', self.__bucket_name, object_name)
except Exception as e:
message = f'Failed to download file ({object_name}) from S3, Reason: {type(e).__name__} - {str(e)}'
self.__logger.error(message)
logger.error(message)
raise PdfServiceInternalError(status_code=HTTPStatus.INTERNAL_SERVER_ERROR, message=message) from e

return result
Expand All @@ -69,10 +69,10 @@ def zip_files(self, bucket_keys: List[str], output_zip_key: str, verbose: bool =
self.__s3_client.put_object(Body=zip_buffer.getvalue(), Bucket=self.__bucket_name, Key=output_zip_key)

if verbose:
self.__logger.info('Stored file in S3: %s', f'{self.__bucket_name}/{output_zip_key}')
logger.info('Stored file in S3: %s', f'{self.__bucket_name}/{output_zip_key}')
except Exception as e:
message = f'Failed to zip files, Reason: {type(e).__name__} - {str(e)}'
self.__logger.error(message)
logger.error(message)
raise PdfServiceInternalError(status_code=HTTPStatus.INTERNAL_SERVER_ERROR, message=message) from e

def generate_presigned_url(
Expand All @@ -90,14 +90,14 @@ def generate_presigned_url(
url = self.__s3_client.generate_presigned_url(
ClientMethod=method.value, Params=params, ExpiresIn=expires_in
)
self.__logger.info('Pre-signed URL generated for file: %s', object_name)
logger.info('Pre-signed URL generated for file: %s', object_name)
except Exception as e:
message = (
f'Failed to generate pre-signed URl for file: ({object_name}), '
f'Reason: '
f'{type(e).__name__} - {str(e)}'
)
self.__logger.error(message)
logger.error(message)
raise PdfServiceInternalError(status_code=HTTPStatus.INTERNAL_SERVER_ERROR, message=message) from e

return url
Expand All @@ -109,7 +109,7 @@ def delete_file(self, object_name: str):
try:
self.__s3_client.delete_object(Bucket=self.__bucket_name, Key=object_name)
except Exception as e:
self.__logger.error('Failed to delete file (%s), Reason: %s - %s', object_name, type(e).__name__, str(e))
logger.error('Failed to delete file (%s), Reason: %s - %s', object_name, type(e).__name__, str(e))
return False

return True
Expand All @@ -118,7 +118,7 @@ def get_file(self, object_key):
try:
s3_response = self.__s3_client.get_object(Bucket=self.__bucket_name, Key=object_key)
except Exception as e:
self.__logger.error('Failed to get file (%s), Reason: %s - %s', object_key, type(e).__name__, str(e))
logger.error('Failed to get file (%s), Reason: %s - %s', object_key, type(e).__name__, str(e))
return None

return s3_response['Body'].read()
Expand All @@ -135,5 +135,5 @@ def copy_object(self, src_bucket, src_key, target_key):
CopySource={'Bucket': src_bucket, 'Key': src_key}, Bucket=self.__bucket_name, Key=target_key
)
except Exception as e:
self.__logger.error('Failed to get copy (%s), Reason: %s - %s', src_key, type(e).__name__, str(e))
logger.error('Failed to get copy (%s), Reason: %s - %s', src_key, type(e).__name__, str(e))
return
12 changes: 7 additions & 5 deletions serverless.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ service: sparcs-certificate-service

custom:
projectName: sparcs-events
serviceName: certificate
serviceName: certificate-generator
stage: ${opt:stage, self:provider.stage}
entities: ${self:custom.stage}-${self:custom.projectName}-entities
bucket: ${self:custom.stage}-${self:custom.projectName}-file-bucket
Expand All @@ -19,6 +19,7 @@ custom:
compatibleRuntimes:
- python3.8
slim: true
logRetentionInDays: 30

provider:
name: aws
Expand Down Expand Up @@ -46,10 +47,11 @@ functions:
plugins:
- serverless-python-requirements
- serverless-iam-roles-per-function
- serverless-plugin-log-retention

layers:
wkhtmltopdf:
name: ${self:custom.projectName}-${self:custom.stage}-wkhtmltopdf
description: wkhtmltopdf Linux Package Layer
weazyprint:
name: ${self:custom.projectName}-${self:custom.stage}-weazyprint
description: weazyprint Linux Package Layer
package:
artifact: layers/wkhtmltox-0.12.6-4.amazonlinux2_lambda.zip
artifact: layers/weasyprint-layer-python3.8.zip
39 changes: 17 additions & 22 deletions template/certificate_template.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,48 +4,43 @@
<meta charset="UTF-8">
<title>{{name}} Certificate</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
overflow: hidden;
}

body {
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
position: relative;
}

img {
width: 100%;
height: auto;
object-fit: cover; /* Ensure the image covers the full area without distortion */
object-fit: cover;
position: absolute;
left: 0;
top: 0;
z-index: -1;
}

span {
.centered {
text-align: center;
font-family: Verdana, sans-serif;
font-size: 48px;
font-weight: bold;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

div {
display: -webkit-box; /* wkhtmltopdf uses this one */
display: flex;
-webkit-box-pack: center; /* wkhtmltopdf uses this one */
justify-content: center;
align-items: center;
-webkit-box-align: center; /* wkhtmltopdf uses this one */
width: 100%;
height: 100%;
position: absolute;
top: 0;
.centered span {
white-space: nowrap; /* Prevents the text from wrapping */
}
</style>
</head>
<body>
<img src="{{template_img}}">
<div>
<div class="centered">
<span>{{name}}</span>
</div>
</body>
Expand Down
21 changes: 4 additions & 17 deletions usecase/certificate_usecase.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@

import fitz
import jinja2
import pdfkit
import weasyprint
from weasyprint import CSS

from model.registrations.registration import RegistrationIn
from repository.events_repository import EventsRepository
Expand Down Expand Up @@ -65,22 +66,8 @@ def generate_certficates(self, event_id: str):
# Convert HTML to PDF-------------------------------------------------------------------------------------------------
certificate_name_pdf = f'{certificate_name}.pdf'
certificate_path = os.path.join(tmpdir, certificate_name_pdf)
options = {
'page-size': 'A4',
'orientation': 'Landscape',
'margin-top': '0mm',
'margin-right': '0mm',
'margin-bottom': '0mm',
'margin-left': '0mm',
'encoding': "UTF-8",
"print-media-type": True,
'disable-smart-shrinking': True,
"enable-local-file-access": True,
}
PATH_WKHTMLTOPDF = '/opt/bin/wkhtmltopdf'
PDFKIT_CONFIG = pdfkit.configuration(wkhtmltopdf=PATH_WKHTMLTOPDF)
pdfkit.from_string(
input=html_out, output_path=certificate_path, options=options, configuration=PDFKIT_CONFIG
weasyprint.HTML(output_path).write_pdf(
certificate_path, stylesheets=[CSS(string='@page { size: A4 landscape; margin: 0;}')]
)

# Get only the first page of the PDF----------------------------------------------------------------------------------
Expand Down
Loading