데이터시트 생성: 온디맨드 및 배치 PDF 생성
이 글에서는 사용자가 요청할 때(온디맨드)와 인기 제품에 대해 미리 생성해 두는 방식(배치)으로 제품 데이터시트를 PDF로 생성하는 방법을 설명합니다.
문제: 제품 데이터시트 생성
각 제품에는 다음과 같은 전문적인 PDF 데이터시트가 필요합니다:
-
제품명 및 이미지
-
카테고리별로 그룹화된 기술 사양
-
회사 브랜딩 및 연락처 정보
-
최적화된 레이아웃 (단일 페이지, 균형 잡힌 열)
매 요청마다 PDF를 생성하면 느립니다 (PDF당 약 2초). 65,000개의 모든 SKU를 미리 생성하면 저장 공간과 시간이 낭비됩니다.
해결책: 하이브리드 접근법
두 가지 생성 방식을 사용합니다:
온디맨드: 사용자가 요청할 때 PDF 생성 (최초 1회)
배치: 인기 제품에 대해 PDF를 미리 생성 (매일 밤)
온디맨드 생성
URL 구조
/ds/<sku>.pdf
/ds/<sku>
두 URL 모두 동일한 PDF를 생성합니다.
요청 흐름
@web.route("/ds/<sku>.pdf")
def datasheet(sku: str):
# Validate SKU
# ... (implementation details omitted)
생성 과정
1단계: 제품 데이터 가져오기
# Product name
name = expand_sku(sku)
# ... (implementation details omitted)
2단계: 열 균형 맞추기
줄 수를 균형 있게 맞추기 위해 기능들이 3개 열에 분배됩니다:
# Calculate lines per feature group
all_groups = []
for heading, f_items in features.items():
# ... (implementation details omitted)
3단계: 이미지 높이 계산
# Main image height (proportional to aspect ratio)
with Image.open(main_image_path) as img:
main_width, main_height = img.size
# ... (implementation details omitted)
4단계: 스페이서 계산
바닥글을 페이지 하단으로 밀어냅니다:
available_height = 25.0 # cm
content_height = total_image_height + text_height_cm
spacer_height = max(0, available_height - content_height)
5단계: HTML 렌더링
html = render_template(
"datasheet.html",
sku=sku,
# ... (implementation details omitted)
6단계: PDF 생성
options = {
"page-size": "A4",
"enable-local-file-access": None,
"load-error-handling": "ignore",
"load-media-error-handling": "ignore",
"no-stop-slow-scripts": None
}
pdf_data = pdfkit.from_string(html, options=options)
7단계: 첫 페이지만 유지
reader = PdfReader(BytesIO(pdf_data))
if len(reader.pages) > 1:
writer = PdfWriter()
writer.add_page(reader.pages[0])
output = BytesIO()
writer.write(output)
pdf_data = output.getvalue()
성능
생성 시간: PDF당 약 2초
캐싱: 캐싱 없음 (항상 최신)
이점: 항상 최신 제품 데이터로 유지됨
배치 생성
목적
인기 제품에 대한 PDF를 미리 생성하여 온디맨드 부하를 줄입니다.
스크립트 위치
scripts/utils/generate_datasheets.py
변경 사항 추적
각 SKU와 관련된 productdb.json 섹션의 변경 사항을 추적합니다:
def get_sku_productdb_hash(sku: str) -> str:
"""Get hash of productdb sections relevant to this SKU."""
with open(PRODUCTDB_PATH, "r") as f:
# ... (implementation details omitted)
우선순위 지정
요청 빈도에 따라 SKU의 우선순위를 지정합니다:
def load_popular_skus() -> List[str]:
"""Load popular SKUs from access logs."""
try:
# ... (implementation details omitted)
생성 전략
def batch_generate():
# Load hash cache
hash_cache = load_hash_cache()
# ... (implementation details omitted)
스케줄링
배치 생성은 cron을 통해 매일 밤 실행됩니다:
0 2 * * * cd /home/ubuntu/manage && python scripts/utils/generate_datasheets.py
저장소
로컬: /home/ubuntu/web-static/ds/<sku>.pdf
S3: s3://thinvent-web-static/ds/<sku>.pdf
CDN: CloudFront를 통해 제공
템플릿 구조
데이터시트 템플릿은 3열 레이아웃을 사용합니다:
<div class="container">
<!-- Header with logo and product name -->
<div class="header">
<img src="/s/logo.png">
<h1>{{ name }}</h1>
</div>
<!-- Main image -->
<img src="{{ images[0][1] }}" style="width: 9.5cm">
<!-- Thumbnails (up to 4) -->
<div class="thumbnails">
{% for name, url in images[1:5] %}
<img src="{{ url }}" style="width: 4.5cm">
{% endfor %}
</div>
<!-- Features in 3 columns -->
<div class="features">
<div class="column">
{% for heading, items in features1 %}
<h3>{{ heading }}</h3>
{% for name, value in items.items() %}
<div><strong>{{ name }}:</strong> {{ value }}</div>
{% endfor %}
{% endfor %}
</div>
<div class="column">
<!-- features2 -->
</div>
<div class="column">
<!-- features3 -->
</div>
</div>
<!-- Spacer to push footer down -->
<div style="height: {{ spacer_height }}cm"></div>
<!-- Footer with contact info -->
<div class="footer">
<p>www.thinvent.in | sales@thinvent.in | +91-124-4343177</p>
</div>
</div>
구성
상수로 레이아웃을 제어합니다:
DATASHEET_COLUMN_COUNT = 3
DATASHEET_HEADING_LINE_WEIGHT = 2 # Lines per heading
DATASHEET_FEATURE_NAME_MAX_LEN = 30 # Chars before wrapping
DATASHEET_FEATURE_VALUE_CHARS_PER_LINE = 40 # Chars per line
PDF_PAGE_SIZE = "A4"
통합 지점
제품 페이지
데이터시트 링크:
<a href="/ds/{{ sku }}.pdf" target="_blank">Download Datasheet</a>
Google Shopping
데이터시트는 제품 피드에 링크됩니다:
<g:product_detail>
<g:section_name>Datasheet</g:section_name>
<g:attribute_name>PDF</g:attribute_name>
<g:attribute_value>https://www.thinvent.in/ds/{{ sku }}.pdf</g:attribute_value>
</g:product_detail>
이메일 캠페인
데이터시트는 견적 이메일에 첨부됩니다.
오류 처리
잘못된 SKU
if not check_sku(sku):
abort(422, description="Product not found.")
생성 실패
try:
pdf_data = generate_datasheet_pdf(sku)
if pdf_data is None:
abort(500, description="PDF generation failed.")
except Exception as e:
logger.error(f"PDF generation failed for {sku}: {e}")
abort(500, description="PDF generation failed.")
누락된 이미지
try:
with Image.open(image_path) as img:
width, height = img.size
except Exception:
# Use default dimensions
width, height = 800, 600
참고 자료
라이브러리
관련 글
요약
데이터시트 생성은 하이브리드 접근법을 사용합니다:
온디맨드:
-
사용자가 요청할 때 생성
-
항상 최신
-
저장 공간 낭비 없음
-
PDF당 약 2초
배치:
-
인기 제품 미리 생성
-
productdb 변경 사항 추적
-
요청 빈도에 따라 우선순위 지정
-
매일 밤 cron 작업
과정:
-
제품 데이터 가져오기 (이름, 이미지, 기능, 설명)
-
3개 열에 걸쳐 기능 균형 맞추기
-
이미지 높이 계산
-
HTML 템플릿 렌더링
-
pdfkit으로 PDF 생성
-
첫 페이지만 유지
저장소:
-
로컬:
/home/ubuntu/web-static/ds/ -
S3:
s3://thinvent-web-static/ds/ -
CDN: CloudFront 배포
이 하이브리드 접근법은 최신성(온디맨드)과 성능(배치 사전 생성)의 균형을 맞춥니다.