generate vCard in utils.py; added Tests

This commit is contained in:
Albert
2025-11-09 19:43:03 +01:00
parent 374c242051
commit 998574f26a
6 changed files with 156 additions and 38 deletions

41
app.py
View File

@@ -2,8 +2,7 @@ from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
import os
import re
import pathlib
import unicodedata
from utils import generate_vcard
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DB_PATH = os.path.join(BASE_DIR, 'anmeldung.db')
@@ -98,42 +97,8 @@ def index():
# vCard 4.0 erzeugen und speichern
try:
vcards_dir = os.path.join(BASE_DIR, 'vcards')
os.makedirs(vcards_dir, exist_ok=True)
# sanitize filename: remove diacritics and unsafe chars
def slug(s):
s = unicodedata.normalize('NFKD', s)
s = ''.join(c for c in s if not unicodedata.combining(c))
s = ''.join(c for c in s if c.isalnum() or c in (' ', '_', '-'))
return s.replace(' ', '_')
filename = f"{slug(adresse.nachname)}_{slug(adresse.vorname)}_{adresse.id}.vcf"
filepath = os.path.join(vcards_dir, filename)
# build vCard 4.0 content
lines = [
'BEGIN:VCARD',
'VERSION:4.0',
f'N:{adresse.nachname};{adresse.vorname};;;',
f'FN:{adresse.vorname} {adresse.nachname}',
]
# ADR: PO Box;Extended;Street;Locality;Region;PostalCode;Country
street = adresse.strasse or ''
if adresse.hausnummer:
street = f"{street} {adresse.hausnummer}".strip()
adr = f'ADR:;;{street};{adresse.ort};;{adresse.plz};{adresse.land}'
lines.append(adr)
if adresse.email:
lines.append(f'EMAIL;TYPE=internet:{adresse.email}')
phone = ''
if adresse.telefon_vorwahl or adresse.telefon_nummer:
phone = f"+{adresse.telefon_vorwahl}{adresse.telefon_nummer}".replace('++', '+')
lines.append(f'TEL;TYPE=voice:{phone}')
lines.append('END:VCARD')
with open(filepath, 'w', encoding='utf-8') as f:
f.write('\n'.join(lines))
# generate vcard using helper
generate_vcard(adresse, BASE_DIR)
except Exception:
# nicht kritisch: bei Fehlern nicht die ganze Anfrage abbrechen
pass