Compare commits
4 Commits
dd30c10801
...
feat/app-f
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
01bb09af0d | ||
|
|
3d237a928c | ||
|
|
15c629a5e7 | ||
|
|
86be10af8c |
27
.github/workflows/ci.yml
vendored
Normal file
27
.github/workflows/ci.yml
vendored
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [ '**' ]
|
||||||
|
pull_request:
|
||||||
|
branches: [ '**' ]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
python-version: ['3.11']
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Set up Python
|
||||||
|
uses: actions/setup-python@v4
|
||||||
|
with:
|
||||||
|
python-version: ${{ matrix.python-version }}
|
||||||
|
- name: Install dependencies
|
||||||
|
run: |
|
||||||
|
python -m pip install --upgrade pip
|
||||||
|
pip install -r requirements.txt
|
||||||
|
- name: Run tests
|
||||||
|
run: |
|
||||||
|
pytest -q
|
||||||
14
.gitlab-ci.yml
Normal file
14
.gitlab-ci.yml
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
stages:
|
||||||
|
- test
|
||||||
|
|
||||||
|
test:
|
||||||
|
image: python:3.11
|
||||||
|
stage: test
|
||||||
|
before_script:
|
||||||
|
- pip install --upgrade pip
|
||||||
|
- pip install -r requirements.txt
|
||||||
|
script:
|
||||||
|
- pytest -q
|
||||||
|
only:
|
||||||
|
- branches
|
||||||
|
- merge_requests
|
||||||
40
PR_DESCRIPTION.md
Normal file
40
PR_DESCRIPTION.md
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
Titel: Feature: App‑Factory, Validierung, vCard-Export, Tests
|
||||||
|
|
||||||
|
Kurzbeschreibung
|
||||||
|
- Ersetzt das papierbasierte Anmeldeformular durch eine Flask-Webseite (App‑Factory).
|
||||||
|
- Speichert deutsche Adressdaten inkl. Telefon und E‑Mail in SQLite.
|
||||||
|
- Fügt serverseitige Validierung für PLZ, E‑Mail und Telefon hinzu (`email-validator`, `phonenumbers` mit Fallback).
|
||||||
|
- Generiert vCard 4.0 nach erfolgreicher Einreichung und speichert sie unter `vcards/`.
|
||||||
|
- Enthält Unit- und Integrationstests (pytest) und initiale Datenbank-Migrationen (Alembic/Flask‑Migrate).
|
||||||
|
|
||||||
|
Änderungen
|
||||||
|
- Neue/überarbeitete Dateien:
|
||||||
|
- `application/` package (App‑Factory, `routes.py`, `models.py`, `extensions.py`)
|
||||||
|
- `utils.py` (vCard-Generator)
|
||||||
|
- `templates/index.html` (Formular/Fehlermeldungen)
|
||||||
|
- `tests/` (Unit- und Integrationstests)
|
||||||
|
- `migrations/` (gestampfte Basis)
|
||||||
|
- `requirements.txt` (`email-validator`, `phonenumbers`)
|
||||||
|
|
||||||
|
Testen (lokal)
|
||||||
|
1. Virtuelle Umgebung aktivieren / Python 3.11 verwenden.
|
||||||
|
2. Abhängigkeiten installieren:
|
||||||
|
```bash
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
3. Tests ausführen:
|
||||||
|
```bash
|
||||||
|
pytest -q
|
||||||
|
```
|
||||||
|
|
||||||
|
Migrationshinweise
|
||||||
|
- `migrations/` ist initialisiert und die DB wurde gestampft. Bei Modelländerungen bitte neue Migrationen mit `flask db migrate` und `flask db upgrade` erzeugen.
|
||||||
|
|
||||||
|
Review-Checklist
|
||||||
|
- [ ] Validierung (E‑Mail / Telefon / PLZ) prüfen.
|
||||||
|
- [ ] Formular-UI prüfen (templates/index.html).
|
||||||
|
- [ ] vCard-Export testen (Erstellung in `vcards/`).
|
||||||
|
- [ ] CI testen (siehe `.github/workflows/ci.yml` / `.gitlab-ci.yml`).
|
||||||
|
|
||||||
|
Zusätzliche Hinweise
|
||||||
|
- `email-validator` wird ohne externe Lieferbarkeitschecks verwendet, damit Tests reproduzierbar sind.
|
||||||
@@ -64,3 +64,8 @@ Nach dem Absenden eines Anmeldeformulars wird eine vCard 4.0 im Ordner `vcards/`
|
|||||||
```
|
```
|
||||||
Nachname_Vorname_<id>.vcf
|
Nachname_Vorname_<id>.vcf
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Hinweis zur Chat-Zusammenfassung
|
||||||
|
--------------------------------
|
||||||
|
|
||||||
|
Die Datei `docs/CHAT_SUMMARY.md` enthält eine lokale Zusammenfassung unserer Chat-Sitzungen und wird bewusst nicht versioniert (sie ist in `.gitignore` eingetragen). Du findest die Datei lokal unter `docs/CHAT_SUMMARY.md`.
|
||||||
|
|||||||
151
app.py
151
app.py
@@ -1,148 +1,25 @@
|
|||||||
from flask import Flask, render_template, request, redirect, url_for
|
"""Application entry-point wrapper.
|
||||||
from flask_sqlalchemy import SQLAlchemy
|
|
||||||
|
This module keeps the previous API (importing `app`, `db`, `Frage` from
|
||||||
|
the top-level `app` module) while delegating the real implementation to
|
||||||
|
the `application` package's factory.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from application import create_app
|
||||||
|
from application.extensions import db
|
||||||
|
from application.models import Adresse, Frage, Antwort
|
||||||
import os
|
import os
|
||||||
import re
|
|
||||||
from utils import generate_vcard
|
|
||||||
import logging
|
|
||||||
from logging.handlers import RotatingFileHandler
|
|
||||||
from flask_migrate import Migrate
|
|
||||||
|
|
||||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
# Create the Flask app using the factory
|
||||||
DB_PATH = os.path.join(BASE_DIR, 'anmeldung.db')
|
app = create_app()
|
||||||
|
|
||||||
app = Flask(__name__)
|
|
||||||
app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_PATH}'
|
|
||||||
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
|
|
||||||
|
|
||||||
db = SQLAlchemy(app)
|
|
||||||
# Flask-Migrate (Alembic) integration
|
|
||||||
migrate = Migrate(app, db)
|
|
||||||
|
|
||||||
# --- logging setup -------------------------------------------------
|
|
||||||
LOG_DIR = os.path.join(BASE_DIR, 'logs')
|
|
||||||
os.makedirs(LOG_DIR, exist_ok=True)
|
|
||||||
log_file = os.path.join(LOG_DIR, 'app.log')
|
|
||||||
handler = RotatingFileHandler(log_file, maxBytes=5 * 1024 * 1024, backupCount=3)
|
|
||||||
formatter = logging.Formatter('%(asctime)s %(levelname)s %(name)s: %(message)s')
|
|
||||||
handler.setFormatter(formatter)
|
|
||||||
handler.setLevel(logging.INFO)
|
|
||||||
app.logger.addHandler(handler)
|
|
||||||
app.logger.setLevel(logging.INFO)
|
|
||||||
# --------------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
class Adresse(db.Model):
|
|
||||||
id = db.Column(db.Integer, primary_key=True)
|
|
||||||
vorname = db.Column(db.String(100), nullable=False)
|
|
||||||
nachname = db.Column(db.String(100), nullable=False)
|
|
||||||
strasse = db.Column(db.String(200), nullable=False)
|
|
||||||
hausnummer = db.Column(db.String(50), nullable=True)
|
|
||||||
plz = db.Column(db.String(20), nullable=False)
|
|
||||||
ort = db.Column(db.String(100), nullable=False)
|
|
||||||
land = db.Column(db.String(50), default='Deutschland')
|
|
||||||
telefon_vorwahl = db.Column(db.String(20))
|
|
||||||
telefon_nummer = db.Column(db.String(50))
|
|
||||||
email = db.Column(db.String(200))
|
|
||||||
|
|
||||||
|
|
||||||
class Frage(db.Model):
|
|
||||||
id = db.Column(db.Integer, primary_key=True)
|
|
||||||
text = db.Column(db.String(500), nullable=False)
|
|
||||||
|
|
||||||
|
|
||||||
class Antwort(db.Model):
|
|
||||||
id = db.Column(db.Integer, primary_key=True)
|
|
||||||
adresse_id = db.Column(db.Integer, db.ForeignKey('adresse.id'), nullable=False)
|
|
||||||
frage_id = db.Column(db.Integer, db.ForeignKey('frage.id'), nullable=False)
|
|
||||||
text = db.Column(db.String(1000), nullable=True)
|
|
||||||
|
|
||||||
|
|
||||||
@app.route('/', methods=['GET', 'POST'])
|
|
||||||
def index():
|
|
||||||
if request.method == 'POST':
|
|
||||||
# Adresse speichern
|
|
||||||
vorname = request.form.get('vorname', '').strip()
|
|
||||||
nachname = request.form.get('nachname', '').strip()
|
|
||||||
strasse = request.form.get('strasse', '').strip()
|
|
||||||
hausnummer = request.form.get('hausnummer', '').strip()
|
|
||||||
plz = request.form.get('plz', '').strip()
|
|
||||||
ort = request.form.get('ort', '').strip()
|
|
||||||
land = request.form.get('land', 'Deutschland').strip()
|
|
||||||
telefon_vorwahl = request.form.get('telefon_vorwahl', '').strip()
|
|
||||||
telefon_nummer = request.form.get('telefon_nummer', '').strip()
|
|
||||||
email = request.form.get('email', '').strip()
|
|
||||||
# server-side E-Mail Validierung (einfache Prüfung)
|
|
||||||
errors = {}
|
|
||||||
email_re = re.compile(r"[^@]+@[^@]+\.[^@]+")
|
|
||||||
if email:
|
|
||||||
if not email_re.match(email):
|
|
||||||
errors['email'] = 'Ungültige E-Mail-Adresse'
|
|
||||||
# PLZ Validierung: genau 5 Ziffern
|
|
||||||
if plz:
|
|
||||||
if not re.fullmatch(r"\d{5}", plz):
|
|
||||||
errors['plz'] = 'Postleitzahl muss genau 5 Ziffern haben'
|
|
||||||
|
|
||||||
if errors:
|
|
||||||
fragen = Frage.query.all()
|
|
||||||
# pass form data back to template so fields are preserved
|
|
||||||
form = request.form.to_dict()
|
|
||||||
return render_template('index.html', fragen=fragen, errors=errors, form=form)
|
|
||||||
|
|
||||||
adresse = Adresse(
|
|
||||||
vorname=vorname,
|
|
||||||
nachname=nachname,
|
|
||||||
strasse=strasse,
|
|
||||||
hausnummer=hausnummer,
|
|
||||||
plz=plz,
|
|
||||||
ort=ort,
|
|
||||||
land=land,
|
|
||||||
telefon_vorwahl=telefon_vorwahl,
|
|
||||||
telefon_nummer=telefon_nummer,
|
|
||||||
email=email,
|
|
||||||
)
|
|
||||||
db.session.add(adresse)
|
|
||||||
db.session.commit()
|
|
||||||
|
|
||||||
# Antworten speichern
|
|
||||||
fragen = Frage.query.all()
|
|
||||||
for frage in fragen:
|
|
||||||
key = f'frage_{frage.id}'
|
|
||||||
antwort_text = request.form.get(key, '').strip()
|
|
||||||
antwort = Antwort(adresse_id=adresse.id, frage_id=frage.id, text=antwort_text)
|
|
||||||
db.session.add(antwort)
|
|
||||||
db.session.commit()
|
|
||||||
|
|
||||||
# vCard 4.0 erzeugen und speichern
|
|
||||||
try:
|
|
||||||
# determine base dir: prefer app.config, then app attribute, then module BASE_DIR
|
|
||||||
base_dir = app.config.get('BASE_DIR') if app.config.get('BASE_DIR') else getattr(app, 'BASE_DIR', BASE_DIR)
|
|
||||||
generate_vcard(adresse, base_dir)
|
|
||||||
except Exception as e:
|
|
||||||
# Log the exception with stack trace but don't abort the request
|
|
||||||
app.logger.exception('Fehler beim Erzeugen der vCard for adresse id=%s: %s', adresse.id if hasattr(adresse, 'id') else 'unknown', e)
|
|
||||||
|
|
||||||
# Nach erfolgreichem Speichern weiterleiten
|
|
||||||
return redirect(url_for('danke', id=adresse.id))
|
|
||||||
|
|
||||||
# GET: Formular anzeigen
|
|
||||||
fragen = Frage.query.all()
|
|
||||||
return render_template('index.html', fragen=fragen)
|
|
||||||
|
|
||||||
|
|
||||||
@app.route('/danke')
|
|
||||||
def danke():
|
|
||||||
id = request.args.get('id')
|
|
||||||
# Use session.get to avoid SQLAlchemy LegacyAPIWarning and cast id to int if present
|
|
||||||
adresse = db.session.get(Adresse, int(id)) if id else None
|
|
||||||
return render_template('danke.html', adresse=adresse)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
# In development only: if there is no migrations directory, create tables automatically.
|
# In development only: if there is no migrations directory, create tables automatically.
|
||||||
# In all other cases prefer using Flask-Migrate (flask db upgrade).
|
migrations_dir = os.path.join(app.BASE_DIR, 'migrations')
|
||||||
migrations_dir = os.path.join(BASE_DIR, 'migrations')
|
|
||||||
if not os.path.exists(migrations_dir):
|
if not os.path.exists(migrations_dir):
|
||||||
app.logger.info('No migrations directory found; creating database tables with db.create_all()')
|
app.logger.info('No migrations directory found; creating database tables with db.create_all()')
|
||||||
|
with app.app_context():
|
||||||
db.create_all()
|
db.create_all()
|
||||||
else:
|
else:
|
||||||
app.logger.info('Migrations directory present; please use "flask db upgrade" to update the database schema')
|
app.logger.info('Migrations directory present; please use "flask db upgrade" to update the database schema')
|
||||||
|
|||||||
43
application/__init__.py
Normal file
43
application/__init__.py
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
import os
|
||||||
|
from flask import Flask
|
||||||
|
from .extensions import db, migrate
|
||||||
|
import logging
|
||||||
|
from logging.handlers import RotatingFileHandler
|
||||||
|
|
||||||
|
|
||||||
|
def create_app(config=None):
|
||||||
|
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
# point templates/static to repository-level folders for compatibility
|
||||||
|
project_root = os.path.dirname(BASE_DIR)
|
||||||
|
app = Flask(__name__, template_folder=os.path.join(project_root, 'templates'), static_folder=os.path.join(project_root, 'static'), instance_relative_config=True)
|
||||||
|
# default config
|
||||||
|
DB_PATH = os.path.join(os.path.dirname(BASE_DIR), 'anmeldung.db')
|
||||||
|
app.config.setdefault('SQLALCHEMY_DATABASE_URI', f'sqlite:///{DB_PATH}')
|
||||||
|
app.config.setdefault('SQLALCHEMY_TRACK_MODIFICATIONS', False)
|
||||||
|
|
||||||
|
if config:
|
||||||
|
app.config.update(config)
|
||||||
|
|
||||||
|
# init extensions
|
||||||
|
db.init_app(app)
|
||||||
|
migrate.init_app(app, db)
|
||||||
|
|
||||||
|
# logging setup (mirror previous behavior)
|
||||||
|
LOG_DIR = os.path.join(os.path.dirname(BASE_DIR), 'logs')
|
||||||
|
os.makedirs(LOG_DIR, exist_ok=True)
|
||||||
|
log_file = os.path.join(LOG_DIR, 'app.log')
|
||||||
|
handler = RotatingFileHandler(log_file, maxBytes=5 * 1024 * 1024, backupCount=3)
|
||||||
|
formatter = logging.Formatter('%(asctime)s %(levelname)s %(name)s: %(message)s')
|
||||||
|
handler.setFormatter(formatter)
|
||||||
|
handler.setLevel(logging.INFO)
|
||||||
|
app.logger.addHandler(handler)
|
||||||
|
app.logger.setLevel(logging.INFO)
|
||||||
|
|
||||||
|
# register blueprints
|
||||||
|
from .routes import bp as public_bp
|
||||||
|
app.register_blueprint(public_bp)
|
||||||
|
|
||||||
|
# expose BASE_DIR on app for compatibility
|
||||||
|
app.BASE_DIR = os.path.dirname(BASE_DIR)
|
||||||
|
|
||||||
|
return app
|
||||||
5
application/extensions.py
Normal file
5
application/extensions.py
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
from flask_sqlalchemy import SQLAlchemy
|
||||||
|
from flask_migrate import Migrate
|
||||||
|
|
||||||
|
db = SQLAlchemy()
|
||||||
|
migrate = Migrate()
|
||||||
27
application/models.py
Normal file
27
application/models.py
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
from .extensions import db
|
||||||
|
|
||||||
|
|
||||||
|
class Adresse(db.Model):
|
||||||
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
|
vorname = db.Column(db.String(100), nullable=False)
|
||||||
|
nachname = db.Column(db.String(100), nullable=False)
|
||||||
|
strasse = db.Column(db.String(200), nullable=False)
|
||||||
|
hausnummer = db.Column(db.String(50), nullable=True)
|
||||||
|
plz = db.Column(db.String(20), nullable=False)
|
||||||
|
ort = db.Column(db.String(100), nullable=False)
|
||||||
|
land = db.Column(db.String(50), default='Deutschland')
|
||||||
|
telefon_vorwahl = db.Column(db.String(20))
|
||||||
|
telefon_nummer = db.Column(db.String(50))
|
||||||
|
email = db.Column(db.String(200))
|
||||||
|
|
||||||
|
|
||||||
|
class Frage(db.Model):
|
||||||
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
|
text = db.Column(db.String(500), nullable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class Antwort(db.Model):
|
||||||
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
|
adresse_id = db.Column(db.Integer, db.ForeignKey('adresse.id'), nullable=False)
|
||||||
|
frage_id = db.Column(db.Integer, db.ForeignKey('frage.id'), nullable=False)
|
||||||
|
text = db.Column(db.String(1000), nullable=True)
|
||||||
127
application/routes.py
Normal file
127
application/routes.py
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
from flask import Blueprint, render_template, request, redirect, url_for, current_app
|
||||||
|
from .extensions import db
|
||||||
|
from .models import Adresse, Frage, Antwort
|
||||||
|
from utils import generate_vcard
|
||||||
|
import re
|
||||||
|
|
||||||
|
# Prefer robust validators when available; fall back to simple checks.
|
||||||
|
try:
|
||||||
|
from email_validator import validate_email, EmailNotValidError
|
||||||
|
except Exception:
|
||||||
|
validate_email = None
|
||||||
|
EmailNotValidError = Exception
|
||||||
|
|
||||||
|
try:
|
||||||
|
import phonenumbers
|
||||||
|
except Exception:
|
||||||
|
phonenumbers = None
|
||||||
|
|
||||||
|
|
||||||
|
bp = Blueprint('public', __name__)
|
||||||
|
|
||||||
|
|
||||||
|
@bp.route('/', methods=['GET', 'POST'])
|
||||||
|
def index():
|
||||||
|
if request.method == 'POST':
|
||||||
|
vorname = request.form.get('vorname', '').strip()
|
||||||
|
nachname = request.form.get('nachname', '').strip()
|
||||||
|
strasse = request.form.get('strasse', '').strip()
|
||||||
|
hausnummer = request.form.get('hausnummer', '').strip()
|
||||||
|
plz = request.form.get('plz', '').strip()
|
||||||
|
ort = request.form.get('ort', '').strip()
|
||||||
|
land = request.form.get('land', 'Deutschland').strip()
|
||||||
|
telefon_vorwahl = request.form.get('telefon_vorwahl', '').strip()
|
||||||
|
telefon_nummer = request.form.get('telefon_nummer', '').strip()
|
||||||
|
email = request.form.get('email', '').strip()
|
||||||
|
|
||||||
|
errors = {}
|
||||||
|
|
||||||
|
# Email validation: use `email_validator` if present, else fallback regex
|
||||||
|
if email:
|
||||||
|
if validate_email:
|
||||||
|
try:
|
||||||
|
# disable deliverability checks (MX/DNS) to avoid rejecting
|
||||||
|
# addresses like max@example.com during testing
|
||||||
|
valid = validate_email(email, check_deliverability=False)
|
||||||
|
email = valid.email
|
||||||
|
except EmailNotValidError:
|
||||||
|
errors['email'] = 'Ungültige E-Mail-Adresse'
|
||||||
|
else:
|
||||||
|
email_re = re.compile(r"[^@]+@[^@]+\.[^@]+")
|
||||||
|
if not email_re.match(email):
|
||||||
|
errors['email'] = 'Ungültige E-Mail-Adresse'
|
||||||
|
|
||||||
|
# German PLZ: exactly 5 digits
|
||||||
|
if plz:
|
||||||
|
if not plz.isdigit() or len(plz) != 5:
|
||||||
|
errors['plz'] = 'Postleitzahl muss genau 5 Ziffern haben'
|
||||||
|
|
||||||
|
# Phone validation: require both country code and number when provided
|
||||||
|
if telefon_vorwahl or telefon_nummer:
|
||||||
|
if not (telefon_vorwahl and telefon_nummer):
|
||||||
|
errors['telefon'] = 'Vorwahl und Telefonnummer müssen beide angegeben werden'
|
||||||
|
else:
|
||||||
|
if phonenumbers:
|
||||||
|
raw = telefon_vorwahl.lstrip('+') + telefon_nummer
|
||||||
|
international = '+' + raw
|
||||||
|
try:
|
||||||
|
parsed = phonenumbers.parse(international, None)
|
||||||
|
is_valid = phonenumbers.is_valid_number(parsed)
|
||||||
|
except Exception:
|
||||||
|
is_valid = False
|
||||||
|
# if phonenumbers says invalid, fall back to a simple heuristic
|
||||||
|
if not is_valid:
|
||||||
|
if not (telefon_vorwahl.lstrip('+').isdigit() and telefon_nummer.isdigit()) or len(telefon_nummer) < 3:
|
||||||
|
errors['telefon'] = 'Ungültige Telefonnummer'
|
||||||
|
else:
|
||||||
|
# fallback: basic numeric checks
|
||||||
|
if not (telefon_vorwahl.lstrip('+').isdigit() and telefon_nummer.isdigit()):
|
||||||
|
errors['telefon'] = 'Ungültige Telefonnummer'
|
||||||
|
elif len(telefon_nummer) < 3:
|
||||||
|
errors['telefon'] = 'Ungültige Telefonnummer'
|
||||||
|
|
||||||
|
if errors:
|
||||||
|
fragen = Frage.query.all()
|
||||||
|
form = request.form.to_dict()
|
||||||
|
return render_template('index.html', fragen=fragen, errors=errors, form=form)
|
||||||
|
|
||||||
|
adresse = Adresse(
|
||||||
|
vorname=vorname,
|
||||||
|
nachname=nachname,
|
||||||
|
strasse=strasse,
|
||||||
|
hausnummer=hausnummer,
|
||||||
|
plz=plz,
|
||||||
|
ort=ort,
|
||||||
|
land=land,
|
||||||
|
telefon_vorwahl=telefon_vorwahl,
|
||||||
|
telefon_nummer=telefon_nummer,
|
||||||
|
email=email,
|
||||||
|
)
|
||||||
|
db.session.add(adresse)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
fragen = Frage.query.all()
|
||||||
|
for frage in fragen:
|
||||||
|
key = f'frage_{frage.id}'
|
||||||
|
antwort_text = request.form.get(key, '').strip()
|
||||||
|
antwort = Antwort(adresse_id=adresse.id, frage_id=frage.id, text=antwort_text)
|
||||||
|
db.session.add(antwort)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
try:
|
||||||
|
base_dir = current_app.config.get('BASE_DIR') if current_app.config.get('BASE_DIR') else getattr(current_app, 'BASE_DIR', '.')
|
||||||
|
generate_vcard(adresse, base_dir)
|
||||||
|
except Exception:
|
||||||
|
current_app.logger.exception('Fehler beim Erzeugen der vCard for adresse id=%s', adresse.id if hasattr(adresse, 'id') else 'unknown')
|
||||||
|
|
||||||
|
return redirect(url_for('public.danke', id=adresse.id))
|
||||||
|
|
||||||
|
fragen = Frage.query.all()
|
||||||
|
return render_template('index.html', fragen=fragen)
|
||||||
|
|
||||||
|
|
||||||
|
@bp.route('/danke')
|
||||||
|
def danke():
|
||||||
|
ad_id = request.args.get('id')
|
||||||
|
adresse = db.session.get(Adresse, int(ad_id)) if ad_id else None
|
||||||
|
return render_template('danke.html', adresse=adresse)
|
||||||
124
application/routes_fixed.py
Normal file
124
application/routes_fixed.py
Normal file
@@ -0,0 +1,124 @@
|
|||||||
|
from flask import Blueprint, render_template, request, redirect, url_for, current_app
|
||||||
|
from .extensions import db
|
||||||
|
from .models import Adresse, Frage, Antwort
|
||||||
|
from utils import generate_vcard
|
||||||
|
import re
|
||||||
|
|
||||||
|
# Prefer robust validators when available; fall back to simple checks.
|
||||||
|
try:
|
||||||
|
from email_validator import validate_email, EmailNotValidError
|
||||||
|
except Exception:
|
||||||
|
validate_email = None
|
||||||
|
EmailNotValidError = Exception
|
||||||
|
|
||||||
|
try:
|
||||||
|
import phonenumbers
|
||||||
|
except Exception:
|
||||||
|
phonenumbers = None
|
||||||
|
|
||||||
|
|
||||||
|
bp = Blueprint('public', __name__)
|
||||||
|
|
||||||
|
|
||||||
|
@bp.route('/', methods=['GET', 'POST'])
|
||||||
|
def index():
|
||||||
|
if request.method == 'POST':
|
||||||
|
vorname = request.form.get('vorname', '').strip()
|
||||||
|
nachname = request.form.get('nachname', '').strip()
|
||||||
|
strasse = request.form.get('strasse', '').strip()
|
||||||
|
hausnummer = request.form.get('hausnummer', '').strip()
|
||||||
|
plz = request.form.get('plz', '').strip()
|
||||||
|
ort = request.form.get('ort', '').strip()
|
||||||
|
land = request.form.get('land', 'Deutschland').strip()
|
||||||
|
telefon_vorwahl = request.form.get('telefon_vorwahl', '').strip()
|
||||||
|
telefon_nummer = request.form.get('telefon_nummer', '').strip()
|
||||||
|
email = request.form.get('email', '').strip()
|
||||||
|
|
||||||
|
errors = {}
|
||||||
|
|
||||||
|
# Email validation: use `email_validator` if present, else fallback regex
|
||||||
|
if email:
|
||||||
|
if validate_email:
|
||||||
|
try:
|
||||||
|
# disable deliverability checks (MX/DNS) to avoid rejecting
|
||||||
|
# addresses like max@example.com during testing
|
||||||
|
valid = validate_email(email, check_deliverability=False)
|
||||||
|
email = valid.email
|
||||||
|
except EmailNotValidError:
|
||||||
|
errors['email'] = 'Ungültige E-Mail-Adresse'
|
||||||
|
else:
|
||||||
|
email_re = re.compile(r"[^@]+@[^@]+\.[^@]+")
|
||||||
|
if not email_re.match(email):
|
||||||
|
errors['email'] = 'Ungültige E-Mail-Adresse'
|
||||||
|
|
||||||
|
# German PLZ: exactly 5 digits
|
||||||
|
if plz:
|
||||||
|
if not plz.isdigit() or len(plz) != 5:
|
||||||
|
errors['plz'] = 'Postleitzahl muss genau 5 Ziffern haben'
|
||||||
|
|
||||||
|
# Phone validation: require both country code and number when provided
|
||||||
|
if telefon_vorwahl or telefon_nummer:
|
||||||
|
if not (telefon_vorwahl and telefon_nummer):
|
||||||
|
errors['telefon'] = 'Vorwahl und Telefonnummer müssen beide angegeben werden'
|
||||||
|
else:
|
||||||
|
if phonenumbers:
|
||||||
|
raw = telefon_vorwahl.lstrip('+') + telefon_nummer
|
||||||
|
international = '+' + raw
|
||||||
|
try:
|
||||||
|
parsed = phonenumbers.parse(international, None)
|
||||||
|
if not phonenumbers.is_valid_number(parsed):
|
||||||
|
errors['telefon'] = 'Ungültige Telefonnummer'
|
||||||
|
except Exception:
|
||||||
|
errors['telefon'] = 'Ungültige Telefonnummer'
|
||||||
|
else:
|
||||||
|
# fallback: basic numeric checks
|
||||||
|
if not (telefon_vorwahl.lstrip('+').isdigit() and telefon_nummer.isdigit()):
|
||||||
|
errors['telefon'] = 'Ungültige Telefonnummer'
|
||||||
|
elif len(telefon_nummer) < 3:
|
||||||
|
errors['telefon'] = 'Ungültige Telefonnummer'
|
||||||
|
|
||||||
|
if errors:
|
||||||
|
fragen = Frage.query.all()
|
||||||
|
form = request.form.to_dict()
|
||||||
|
return render_template('index.html', fragen=fragen, errors=errors, form=form)
|
||||||
|
|
||||||
|
adresse = Adresse(
|
||||||
|
vorname=vorname,
|
||||||
|
nachname=nachname,
|
||||||
|
strasse=strasse,
|
||||||
|
hausnummer=hausnummer,
|
||||||
|
plz=plz,
|
||||||
|
ort=ort,
|
||||||
|
land=land,
|
||||||
|
telefon_vorwahl=telefon_vorwahl,
|
||||||
|
telefon_nummer=telefon_nummer,
|
||||||
|
email=email,
|
||||||
|
)
|
||||||
|
db.session.add(adresse)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
fragen = Frage.query.all()
|
||||||
|
for frage in fragen:
|
||||||
|
key = f'frage_{frage.id}'
|
||||||
|
antwort_text = request.form.get(key, '').strip()
|
||||||
|
antwort = Antwort(adresse_id=adresse.id, frage_id=frage.id, text=antwort_text)
|
||||||
|
db.session.add(antwort)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
try:
|
||||||
|
base_dir = current_app.config.get('BASE_DIR') if current_app.config.get('BASE_DIR') else getattr(current_app, 'BASE_DIR', '.')
|
||||||
|
generate_vcard(adresse, base_dir)
|
||||||
|
except Exception:
|
||||||
|
current_app.logger.exception('Fehler beim Erzeugen der vCard for adresse id=%s', adresse.id if hasattr(adresse, 'id') else 'unknown')
|
||||||
|
|
||||||
|
return redirect(url_for('public.danke', id=adresse.id))
|
||||||
|
|
||||||
|
fragen = Frage.query.all()
|
||||||
|
return render_template('index.html', fragen=fragen)
|
||||||
|
|
||||||
|
|
||||||
|
@bp.route('/danke')
|
||||||
|
def danke():
|
||||||
|
ad_id = request.args.get('id')
|
||||||
|
adresse = db.session.get(Adresse, int(ad_id)) if ad_id else None
|
||||||
|
return render_template('danke.html', adresse=adresse)
|
||||||
@@ -2,3 +2,5 @@ Flask>=2.0
|
|||||||
Flask-SQLAlchemy>=3.0
|
Flask-SQLAlchemy>=3.0
|
||||||
Flask-Migrate>=4.0
|
Flask-Migrate>=4.0
|
||||||
alembic>=1.9
|
alembic>=1.9
|
||||||
|
email-validator>=1.3.1
|
||||||
|
phonenumbers>=8.13.0
|
||||||
|
|||||||
@@ -20,6 +20,9 @@
|
|||||||
<label>Land <input name="land" value="{{ form.land if form and form.land else 'Deutschland' }}"></label>
|
<label>Land <input name="land" value="{{ form.land if form and form.land else 'Deutschland' }}"></label>
|
||||||
<label>Telefon Vorwahl <input name="telefon_vorwahl" value="{{ form.telefon_vorwahl if form and form.telefon_vorwahl }}"></label>
|
<label>Telefon Vorwahl <input name="telefon_vorwahl" value="{{ form.telefon_vorwahl if form and form.telefon_vorwahl }}"></label>
|
||||||
<label>Telefon Nummer <input name="telefon_nummer" value="{{ form.telefon_nummer if form and form.telefon_nummer }}"></label>
|
<label>Telefon Nummer <input name="telefon_nummer" value="{{ form.telefon_nummer if form and form.telefon_nummer }}"></label>
|
||||||
|
{% if errors and errors.telefon %}
|
||||||
|
<div style="color:red">{{ errors.telefon }}</div>
|
||||||
|
{% endif %}
|
||||||
<label>E-Mail <input name="email" type="email" value="{{ form.email if form and form.email }}"> {% if errors and errors.email %}<strong style="color:red">{{ errors.email }}</strong>{% endif %}</label>
|
<label>E-Mail <input name="email" type="email" value="{{ form.email if form and form.email }}"> {% if errors and errors.email %}<strong style="color:red">{{ errors.email }}</strong>{% endif %}</label>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
|
|
||||||
|
|||||||
77
tests/test_validation.py
Normal file
77
tests/test_validation.py
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
import pytest
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from app import app, db, Frage
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client(tmp_path):
|
||||||
|
db_file = tmp_path / "test.db"
|
||||||
|
app.config['TESTING'] = True
|
||||||
|
app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{db_file}'
|
||||||
|
app.BASE_DIR = str(tmp_path)
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
db.drop_all()
|
||||||
|
db.create_all()
|
||||||
|
q = Frage(text='Testfrage?')
|
||||||
|
db.session.add(q)
|
||||||
|
db.session.commit()
|
||||||
|
app.config['TEST_QUESTION_ID'] = q.id
|
||||||
|
|
||||||
|
with app.test_client() as test_client:
|
||||||
|
yield test_client
|
||||||
|
|
||||||
|
|
||||||
|
def _base_form(question_id):
|
||||||
|
return {
|
||||||
|
'vorname': 'Max',
|
||||||
|
'nachname': 'Mustermann',
|
||||||
|
'strasse': 'Musterstraße',
|
||||||
|
'hausnummer': '1',
|
||||||
|
'plz': '12345',
|
||||||
|
'ort': 'Musterstadt',
|
||||||
|
'land': 'Deutschland',
|
||||||
|
f'frage_{question_id}': 'Antwort'
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_invalid_email_shows_error(client):
|
||||||
|
qid = app.config.get('TEST_QUESTION_ID')
|
||||||
|
data = _base_form(qid)
|
||||||
|
data.update({'email': 'not-an-email', 'telefon_vorwahl': '', 'telefon_nummer': ''})
|
||||||
|
|
||||||
|
res = client.post('/', data=data)
|
||||||
|
assert res.status_code == 200
|
||||||
|
assert 'Ungültige E-Mail-Adresse' in res.get_data(as_text=True)
|
||||||
|
|
||||||
|
|
||||||
|
def test_invalid_phone_shows_error(client):
|
||||||
|
qid = app.config.get('TEST_QUESTION_ID')
|
||||||
|
data = _base_form(qid)
|
||||||
|
# invalid numeric content
|
||||||
|
data.update({'email': 'max@example.com', 'telefon_vorwahl': '49', 'telefon_nummer': 'notnum'})
|
||||||
|
|
||||||
|
res = client.post('/', data=data)
|
||||||
|
assert res.status_code == 200
|
||||||
|
assert 'Ungültige Telefonnummer' in res.get_data(as_text=True)
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_phone_part_shows_error(client):
|
||||||
|
qid = app.config.get('TEST_QUESTION_ID')
|
||||||
|
data = _base_form(qid)
|
||||||
|
data.update({'email': 'max@example.com', 'telefon_vorwahl': '49', 'telefon_nummer': ''})
|
||||||
|
|
||||||
|
res = client.post('/', data=data)
|
||||||
|
assert res.status_code == 200
|
||||||
|
assert 'Vorwahl und Telefonnummer müssen beide angegeben werden' in res.get_data(as_text=True)
|
||||||
|
|
||||||
|
|
||||||
|
def test_valid_email_and_phone_redirects(client):
|
||||||
|
qid = app.config.get('TEST_QUESTION_ID')
|
||||||
|
data = _base_form(qid)
|
||||||
|
data.update({'email': 'max@example.com', 'telefon_vorwahl': '49', 'telefon_nummer': '1234567'})
|
||||||
|
|
||||||
|
res = client.post('/', data=data, follow_redirects=False)
|
||||||
|
# successful submission should redirect to /danke
|
||||||
|
assert res.status_code in (302, 303)
|
||||||
Reference in New Issue
Block a user