Compare commits
11 Commits
081915dacf
...
feat/app-f
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
01bb09af0d | ||
|
|
3d237a928c | ||
|
|
15c629a5e7 | ||
|
|
86be10af8c | ||
|
|
dd30c10801 | ||
|
|
50cbd08950 | ||
|
|
2545ab84fd | ||
|
|
799fdbd905 | ||
|
|
49e2f16dbb | ||
| 800ccd8376 | |||
|
|
fca9462bc7 |
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.
|
||||||
46
README.md
46
README.md
@@ -23,3 +23,49 @@ python app.py
|
|||||||
```
|
```
|
||||||
|
|
||||||
Das Formular ist dann unter http://127.0.0.1:5000/ erreichbar.
|
Das Formular ist dann unter http://127.0.0.1:5000/ erreichbar.
|
||||||
|
|
||||||
|
Migrations (Flask-Migrate / Alembic)
|
||||||
|
---------------------------------
|
||||||
|
|
||||||
|
Das Projekt verwendet jetzt Flask-Migrate (Alembic) für Datenbank-Migrationen. Ablauf lokal:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# virtuelles Environment aktivieren
|
||||||
|
source .venv/bin/activate
|
||||||
|
|
||||||
|
# Migrationen initialisieren (nur einmal)
|
||||||
|
export FLASK_APP=app.py
|
||||||
|
flask db init
|
||||||
|
|
||||||
|
# Neue Migration auf Basis der Models erzeugen
|
||||||
|
flask db migrate -m "Beschreibung der Änderung"
|
||||||
|
|
||||||
|
# Migration anwenden
|
||||||
|
flask db upgrade
|
||||||
|
```
|
||||||
|
|
||||||
|
Hinweis: Wenn die Datenbank bereits Tabellen enthält, benutze `flask db stamp head`, damit Alembic den aktuellen Stand als angewendet markiert.
|
||||||
|
|
||||||
|
Tests
|
||||||
|
-----
|
||||||
|
|
||||||
|
Die Tests laufen mit pytest:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
source .venv/bin/activate
|
||||||
|
python -m pytest -q
|
||||||
|
```
|
||||||
|
|
||||||
|
vCard Export
|
||||||
|
-----------
|
||||||
|
|
||||||
|
Nach dem Absenden eines Anmeldeformulars wird eine vCard 4.0 im Ordner `vcards/` erzeugt. Dateiname-Muster:
|
||||||
|
|
||||||
|
```
|
||||||
|
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`.
|
||||||
|
|||||||
154
app.py
154
app.py
@@ -1,140 +1,26 @@
|
|||||||
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
|
|
||||||
|
|
||||||
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)
|
|
||||||
|
|
||||||
# --- 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')
|
|
||||||
adresse = Adresse.query.get(id)
|
|
||||||
return render_template('danke.html', adresse=adresse)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
# Ensure DB exists
|
# In development only: if there is no migrations directory, create tables automatically.
|
||||||
if not os.path.exists(DB_PATH):
|
migrations_dir = os.path.join(app.BASE_DIR, 'migrations')
|
||||||
db.create_all()
|
if not os.path.exists(migrations_dir):
|
||||||
|
app.logger.info('No migrations directory found; creating database tables with db.create_all()')
|
||||||
|
with app.app_context():
|
||||||
|
db.create_all()
|
||||||
|
else:
|
||||||
|
app.logger.info('Migrations directory present; please use "flask db upgrade" to update the database schema')
|
||||||
app.run(debug=True)
|
app.run(debug=True)
|
||||||
|
|||||||
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)
|
||||||
1
migrations/README
Normal file
1
migrations/README
Normal file
@@ -0,0 +1 @@
|
|||||||
|
Single-database configuration for Flask.
|
||||||
50
migrations/alembic.ini
Normal file
50
migrations/alembic.ini
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
# A generic, single database configuration.
|
||||||
|
|
||||||
|
[alembic]
|
||||||
|
# template used to generate migration files
|
||||||
|
# file_template = %%(rev)s_%%(slug)s
|
||||||
|
|
||||||
|
# set to 'true' to run the environment during
|
||||||
|
# the 'revision' command, regardless of autogenerate
|
||||||
|
# revision_environment = false
|
||||||
|
|
||||||
|
|
||||||
|
# Logging configuration
|
||||||
|
[loggers]
|
||||||
|
keys = root,sqlalchemy,alembic,flask_migrate
|
||||||
|
|
||||||
|
[handlers]
|
||||||
|
keys = console
|
||||||
|
|
||||||
|
[formatters]
|
||||||
|
keys = generic
|
||||||
|
|
||||||
|
[logger_root]
|
||||||
|
level = WARN
|
||||||
|
handlers = console
|
||||||
|
qualname =
|
||||||
|
|
||||||
|
[logger_sqlalchemy]
|
||||||
|
level = WARN
|
||||||
|
handlers =
|
||||||
|
qualname = sqlalchemy.engine
|
||||||
|
|
||||||
|
[logger_alembic]
|
||||||
|
level = INFO
|
||||||
|
handlers =
|
||||||
|
qualname = alembic
|
||||||
|
|
||||||
|
[logger_flask_migrate]
|
||||||
|
level = INFO
|
||||||
|
handlers =
|
||||||
|
qualname = flask_migrate
|
||||||
|
|
||||||
|
[handler_console]
|
||||||
|
class = StreamHandler
|
||||||
|
args = (sys.stderr,)
|
||||||
|
level = NOTSET
|
||||||
|
formatter = generic
|
||||||
|
|
||||||
|
[formatter_generic]
|
||||||
|
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||||
|
datefmt = %H:%M:%S
|
||||||
113
migrations/env.py
Normal file
113
migrations/env.py
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
import logging
|
||||||
|
from logging.config import fileConfig
|
||||||
|
|
||||||
|
from flask import current_app
|
||||||
|
|
||||||
|
from alembic import context
|
||||||
|
|
||||||
|
# this is the Alembic Config object, which provides
|
||||||
|
# access to the values within the .ini file in use.
|
||||||
|
config = context.config
|
||||||
|
|
||||||
|
# Interpret the config file for Python logging.
|
||||||
|
# This line sets up loggers basically.
|
||||||
|
fileConfig(config.config_file_name)
|
||||||
|
logger = logging.getLogger('alembic.env')
|
||||||
|
|
||||||
|
|
||||||
|
def get_engine():
|
||||||
|
try:
|
||||||
|
# this works with Flask-SQLAlchemy<3 and Alchemical
|
||||||
|
return current_app.extensions['migrate'].db.get_engine()
|
||||||
|
except (TypeError, AttributeError):
|
||||||
|
# this works with Flask-SQLAlchemy>=3
|
||||||
|
return current_app.extensions['migrate'].db.engine
|
||||||
|
|
||||||
|
|
||||||
|
def get_engine_url():
|
||||||
|
try:
|
||||||
|
return get_engine().url.render_as_string(hide_password=False).replace(
|
||||||
|
'%', '%%')
|
||||||
|
except AttributeError:
|
||||||
|
return str(get_engine().url).replace('%', '%%')
|
||||||
|
|
||||||
|
|
||||||
|
# add your model's MetaData object here
|
||||||
|
# for 'autogenerate' support
|
||||||
|
# from myapp import mymodel
|
||||||
|
# target_metadata = mymodel.Base.metadata
|
||||||
|
config.set_main_option('sqlalchemy.url', get_engine_url())
|
||||||
|
target_db = current_app.extensions['migrate'].db
|
||||||
|
|
||||||
|
# other values from the config, defined by the needs of env.py,
|
||||||
|
# can be acquired:
|
||||||
|
# my_important_option = config.get_main_option("my_important_option")
|
||||||
|
# ... etc.
|
||||||
|
|
||||||
|
|
||||||
|
def get_metadata():
|
||||||
|
if hasattr(target_db, 'metadatas'):
|
||||||
|
return target_db.metadatas[None]
|
||||||
|
return target_db.metadata
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_offline():
|
||||||
|
"""Run migrations in 'offline' mode.
|
||||||
|
|
||||||
|
This configures the context with just a URL
|
||||||
|
and not an Engine, though an Engine is acceptable
|
||||||
|
here as well. By skipping the Engine creation
|
||||||
|
we don't even need a DBAPI to be available.
|
||||||
|
|
||||||
|
Calls to context.execute() here emit the given string to the
|
||||||
|
script output.
|
||||||
|
|
||||||
|
"""
|
||||||
|
url = config.get_main_option("sqlalchemy.url")
|
||||||
|
context.configure(
|
||||||
|
url=url, target_metadata=get_metadata(), literal_binds=True
|
||||||
|
)
|
||||||
|
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_online():
|
||||||
|
"""Run migrations in 'online' mode.
|
||||||
|
|
||||||
|
In this scenario we need to create an Engine
|
||||||
|
and associate a connection with the context.
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
# this callback is used to prevent an auto-migration from being generated
|
||||||
|
# when there are no changes to the schema
|
||||||
|
# reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
|
||||||
|
def process_revision_directives(context, revision, directives):
|
||||||
|
if getattr(config.cmd_opts, 'autogenerate', False):
|
||||||
|
script = directives[0]
|
||||||
|
if script.upgrade_ops.is_empty():
|
||||||
|
directives[:] = []
|
||||||
|
logger.info('No changes in schema detected.')
|
||||||
|
|
||||||
|
conf_args = current_app.extensions['migrate'].configure_args
|
||||||
|
if conf_args.get("process_revision_directives") is None:
|
||||||
|
conf_args["process_revision_directives"] = process_revision_directives
|
||||||
|
|
||||||
|
connectable = get_engine()
|
||||||
|
|
||||||
|
with connectable.connect() as connection:
|
||||||
|
context.configure(
|
||||||
|
connection=connection,
|
||||||
|
target_metadata=get_metadata(),
|
||||||
|
**conf_args
|
||||||
|
)
|
||||||
|
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
if context.is_offline_mode():
|
||||||
|
run_migrations_offline()
|
||||||
|
else:
|
||||||
|
run_migrations_online()
|
||||||
24
migrations/script.py.mako
Normal file
24
migrations/script.py.mako
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
"""${message}
|
||||||
|
|
||||||
|
Revision ID: ${up_revision}
|
||||||
|
Revises: ${down_revision | comma,n}
|
||||||
|
Create Date: ${create_date}
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
${imports if imports else ""}
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = ${repr(up_revision)}
|
||||||
|
down_revision = ${repr(down_revision)}
|
||||||
|
branch_labels = ${repr(branch_labels)}
|
||||||
|
depends_on = ${repr(depends_on)}
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
${upgrades if upgrades else "pass"}
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
${downgrades if downgrades else "pass"}
|
||||||
@@ -1 +1,2 @@
|
|||||||
pytest
|
pytest
|
||||||
|
Flask-Migrate>=4.0
|
||||||
|
|||||||
@@ -1,2 +1,6 @@
|
|||||||
Flask>=2.0
|
Flask>=2.0
|
||||||
Flask-SQLAlchemy>=3.0
|
Flask-SQLAlchemy>=3.0
|
||||||
|
Flask-Migrate>=4.0
|
||||||
|
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