feat: FASE 0 - Setup progetto TieMeasureFlow
Struttura monorepo completa con server FastAPI e client Flask: - Server: FastAPI + SQLAlchemy 2.0 async + Alembic migrations - Client: Flask + blueprints (auth, measure, maker, statistics) - Database: docker-compose MySQL 8.0 + Alembic async config - Config: pydantic-settings, TailwindCSS, Flask-Babel i18n - Piano implementazione completo (18 sezioni, 1600 righe) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
# ===========================
|
||||
# TieMeasureFlow Configuration
|
||||
# ===========================
|
||||
|
||||
# --- Database ---
|
||||
DB_HOST=localhost
|
||||
DB_PORT=3306
|
||||
DB_NAME=tiemeasureflow
|
||||
DB_USER=tmflow
|
||||
DB_PASSWORD=change_me_in_production
|
||||
|
||||
# --- Server ---
|
||||
SERVER_HOST=0.0.0.0
|
||||
SERVER_PORT=8000
|
||||
SERVER_SECRET_KEY=change-this-to-a-random-secret-key
|
||||
SERVER_CORS_ORIGINS=http://localhost:5000
|
||||
|
||||
# --- Client ---
|
||||
CLIENT_HOST=0.0.0.0
|
||||
CLIENT_PORT=5000
|
||||
CLIENT_SECRET_KEY=change-this-to-another-random-secret-key
|
||||
API_SERVER_URL=http://localhost:8000
|
||||
|
||||
# --- File Storage ---
|
||||
UPLOAD_DIR=server/uploads
|
||||
MAX_UPLOAD_SIZE_MB=50
|
||||
|
||||
# --- HTTPS (Production) ---
|
||||
# SSL_CERTFILE=/path/to/cert.pem
|
||||
# SSL_KEYFILE=/path/to/key.pem
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
*.so
|
||||
*.egg-info/
|
||||
dist/
|
||||
build/
|
||||
*.egg
|
||||
.eggs/
|
||||
|
||||
# Virtual environments
|
||||
venv/
|
||||
.venv/
|
||||
env/
|
||||
|
||||
# Environment
|
||||
.env
|
||||
|
||||
# IDE
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
desktop.ini
|
||||
|
||||
# Uploads (server-side files)
|
||||
server/uploads/images/*
|
||||
server/uploads/pdfs/*
|
||||
server/uploads/logos/*
|
||||
server/uploads/reports/*
|
||||
!server/uploads/images/.gitkeep
|
||||
!server/uploads/pdfs/.gitkeep
|
||||
!server/uploads/logos/.gitkeep
|
||||
!server/uploads/reports/.gitkeep
|
||||
|
||||
# TailwindCSS output
|
||||
client/static/css/tailwind.css
|
||||
|
||||
# Node
|
||||
node_modules/
|
||||
|
||||
# Flask-Babel compiled
|
||||
*.mo
|
||||
|
||||
# Alembic
|
||||
server/migrations/versions/*.py
|
||||
!server/migrations/versions/.gitkeep
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
|
||||
# Testing
|
||||
.pytest_cache/
|
||||
.coverage
|
||||
htmlcov/
|
||||
|
||||
# Competitor analysis (local only)
|
||||
Concorrente/
|
||||
@@ -0,0 +1,74 @@
|
||||
# TieMeasureFlow - Istruzioni Progetto
|
||||
|
||||
## Panoramica
|
||||
TieMeasureFlow by Tielogic - Sistema di gestione task per misurazioni con calibro manuale.
|
||||
Monorepo con server FastAPI (backend API) e client Flask (frontend tablet).
|
||||
|
||||
## Stack
|
||||
- **Server**: FastAPI + SQLAlchemy 2.0 async + asyncmy + MySQL 8.0
|
||||
- **Client**: Flask 3.0 + Jinja2 + htmx 2.0 + Alpine.js 3.x + TailwindCSS 3.x
|
||||
- **Grafici**: Plotly.js (browser) + Kaleido (server export SVG)
|
||||
- **PDF**: WeasyPrint (HTML → PDF), PDF.js (rendering browser)
|
||||
- **Annotazioni**: Fabric.js 6.x (editor Maker), Canvas overlay (display MeasurementTec)
|
||||
- **i18n**: Flask-Babel (server) + alpinejs-i18n (client), lingue IT/EN
|
||||
- **Auth**: API Key nell'header X-API-Key
|
||||
|
||||
## Struttura
|
||||
```
|
||||
TieMeasureFlow/
|
||||
├── server/ # FastAPI Backend (porta 8000)
|
||||
│ ├── main.py # Entry point
|
||||
│ ├── config.py # Settings da .env
|
||||
│ ├── database.py # SQLAlchemy async engine
|
||||
│ ├── models/ # SQLAlchemy ORM models
|
||||
│ ├── schemas/ # Pydantic validation schemas
|
||||
│ ├── routers/ # API endpoint routers
|
||||
│ ├── services/ # Business logic
|
||||
│ ├── middleware/ # API key auth, logging
|
||||
│ └── migrations/ # Alembic migrations
|
||||
├── client/ # Flask Frontend (porta 5000)
|
||||
│ ├── app.py # Entry point
|
||||
│ ├── blueprints/ # Flask route blueprints
|
||||
│ ├── services/ # API client wrapper
|
||||
│ ├── templates/ # Jinja2 HTML templates
|
||||
│ ├── static/ # CSS, JS, immagini
|
||||
│ └── translations/ # Flask-Babel i18n
|
||||
└── docs/ # Documentazione
|
||||
```
|
||||
|
||||
## Convenzioni Codice
|
||||
- Python 3.11+, type hints ovunque
|
||||
- async/await per tutte le operazioni DB (server)
|
||||
- Pydantic v2 per validazione I/O API
|
||||
- Nomi variabili e commenti in inglese, UI strings in IT/EN via i18n
|
||||
- File imports ordinati: stdlib, third-party, local
|
||||
- Nessun import wildcard (from x import *)
|
||||
|
||||
## Database
|
||||
- MySQL 8.0 con charset utf8mb4
|
||||
- SQLAlchemy 2.0 async con asyncmy driver
|
||||
- Alembic per migrations
|
||||
- Tabelle: users, recipes, recipe_versions, recipe_tasks, recipe_subtasks, measurements, access_logs, system_settings, recipe_version_audit
|
||||
|
||||
## Ruoli Utente
|
||||
- **Maker**: crea/modifica ricette
|
||||
- **MeasurementTec**: esegue misurazioni
|
||||
- **Metrologist**: visualizza statistiche SPC
|
||||
- Ruoli combinabili (JSON array), flag `is_admin` separato
|
||||
|
||||
## Pattern Importanti
|
||||
- **Recipe Versioning**: copy-on-write immutabile. Modifiche creano nuova versione, misure restano legate a versione originale
|
||||
- **Pass/Fail**: calcolato da tolleranze UTL/UWL/LWL/LTL su ogni subtask
|
||||
- **File Storage**: uploads/{images,pdfs,logos,reports}/{recipe_id}/{version_id}/
|
||||
|
||||
## Comandi
|
||||
- Server: `cd server && uvicorn main:app --reload --host 0.0.0.0 --port 8000`
|
||||
- Client: `cd client && flask run --host 0.0.0.0 --port 5000`
|
||||
- Migrations: `cd server && alembic upgrade head`
|
||||
- TailwindCSS: `cd client && npx tailwindcss -i static/css/input.css -o static/css/tailwind.css --watch`
|
||||
|
||||
## Brand
|
||||
- Colore primario: #2563EB (blu industriale)
|
||||
- Colore secondario: #64748B (grigio acciaio)
|
||||
- Font UI: Inter
|
||||
- Font numeri: JetBrains Mono
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,66 @@
|
||||
"""TieMeasureFlow Client - Flask Entry Point."""
|
||||
import os
|
||||
|
||||
from flask import Flask, redirect, url_for, session, request
|
||||
from flask_babel import Babel
|
||||
|
||||
from config import Config
|
||||
|
||||
|
||||
def get_locale():
|
||||
"""Get user's preferred language from session or Accept-Language header."""
|
||||
# 1. User preference in session
|
||||
if "language" in session:
|
||||
return session["language"]
|
||||
# 2. Browser Accept-Language
|
||||
return request.accept_languages.best_match(
|
||||
Config.LANGUAGES.keys(), default="it"
|
||||
)
|
||||
|
||||
|
||||
def create_app() -> Flask:
|
||||
"""Application factory."""
|
||||
app = Flask(__name__)
|
||||
app.config.from_object(Config)
|
||||
|
||||
# Initialize Flask-Babel
|
||||
Babel(app, locale_selector=get_locale)
|
||||
|
||||
# Register blueprints
|
||||
from blueprints.auth import auth_bp
|
||||
from blueprints.measure import measure_bp
|
||||
from blueprints.maker import maker_bp
|
||||
from blueprints.statistics import statistics_bp
|
||||
|
||||
app.register_blueprint(auth_bp)
|
||||
app.register_blueprint(measure_bp, url_prefix="/measure")
|
||||
app.register_blueprint(maker_bp, url_prefix="/maker")
|
||||
app.register_blueprint(statistics_bp, url_prefix="/statistics")
|
||||
|
||||
@app.route("/")
|
||||
def index():
|
||||
"""Root redirect to login or dashboard based on session."""
|
||||
if "user" in session:
|
||||
return redirect(url_for("measure.select_recipe"))
|
||||
return redirect(url_for("auth.login"))
|
||||
|
||||
@app.context_processor
|
||||
def inject_globals():
|
||||
"""Inject global variables into all templates."""
|
||||
return {
|
||||
"current_user": session.get("user"),
|
||||
"current_theme": session.get("theme", "light"),
|
||||
"current_language": get_locale(),
|
||||
"languages": Config.LANGUAGES,
|
||||
}
|
||||
|
||||
return app
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app = create_app()
|
||||
app.run(
|
||||
host=os.getenv("CLIENT_HOST", "0.0.0.0"),
|
||||
port=int(os.getenv("CLIENT_PORT", "5000")),
|
||||
debug=True,
|
||||
)
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Authentication blueprint - login, logout, profile."""
|
||||
from flask import Blueprint, render_template, request, redirect, url_for, session, flash
|
||||
|
||||
auth_bp = Blueprint("auth", __name__)
|
||||
|
||||
|
||||
@auth_bp.route("/login", methods=["GET", "POST"])
|
||||
def login():
|
||||
"""Login page."""
|
||||
if request.method == "POST":
|
||||
# TODO: Implement API call to server /api/auth/login
|
||||
pass
|
||||
return render_template("auth/login.html")
|
||||
|
||||
|
||||
@auth_bp.route("/logout")
|
||||
def logout():
|
||||
"""Logout - clear session."""
|
||||
session.clear()
|
||||
return redirect(url_for("auth.login"))
|
||||
|
||||
|
||||
@auth_bp.route("/profile", methods=["GET", "POST"])
|
||||
def profile():
|
||||
"""User profile - change display name, language, theme."""
|
||||
if "user" not in session:
|
||||
return redirect(url_for("auth.login"))
|
||||
if request.method == "POST":
|
||||
# TODO: Implement API call to server /api/auth/me PUT
|
||||
pass
|
||||
return render_template("auth/profile.html")
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Maker blueprint - recipe creation and editing."""
|
||||
from flask import Blueprint, render_template, session, redirect, url_for
|
||||
|
||||
maker_bp = Blueprint("maker", __name__)
|
||||
|
||||
|
||||
@maker_bp.route("/recipes")
|
||||
def recipe_list():
|
||||
"""List all recipes with filters."""
|
||||
if "user" not in session:
|
||||
return redirect(url_for("auth.login"))
|
||||
return render_template("maker/recipe_list.html")
|
||||
|
||||
|
||||
@maker_bp.route("/recipes/new")
|
||||
@maker_bp.route("/recipes/<int:recipe_id>/edit")
|
||||
def recipe_editor(recipe_id: int | None = None):
|
||||
"""Recipe editor - create or edit."""
|
||||
if "user" not in session:
|
||||
return redirect(url_for("auth.login"))
|
||||
return render_template("maker/recipe_editor.html", recipe_id=recipe_id)
|
||||
|
||||
|
||||
@maker_bp.route("/recipes/<int:recipe_id>/tasks")
|
||||
def task_editor(recipe_id: int):
|
||||
"""Task/subtask editor with tolerances."""
|
||||
if "user" not in session:
|
||||
return redirect(url_for("auth.login"))
|
||||
return render_template("maker/task_editor.html", recipe_id=recipe_id)
|
||||
|
||||
|
||||
@maker_bp.route("/recipes/<int:recipe_id>/preview")
|
||||
def recipe_preview(recipe_id: int):
|
||||
"""Preview recipe as MeasurementTec would see it."""
|
||||
if "user" not in session:
|
||||
return redirect(url_for("auth.login"))
|
||||
return render_template("maker/recipe_preview.html", recipe_id=recipe_id)
|
||||
|
||||
|
||||
@maker_bp.route("/recipes/<int:recipe_id>/versions")
|
||||
def version_history(recipe_id: int):
|
||||
"""Version history with diff."""
|
||||
if "user" not in session:
|
||||
return redirect(url_for("auth.login"))
|
||||
return render_template("maker/version_history.html", recipe_id=recipe_id)
|
||||
@@ -0,0 +1,36 @@
|
||||
"""MeasurementTec blueprint - recipe selection and measurement execution."""
|
||||
from flask import Blueprint, render_template, session, redirect, url_for
|
||||
|
||||
measure_bp = Blueprint("measure", __name__)
|
||||
|
||||
|
||||
@measure_bp.route("/select")
|
||||
def select_recipe():
|
||||
"""Recipe selection page."""
|
||||
if "user" not in session:
|
||||
return redirect(url_for("auth.login"))
|
||||
return render_template("measure/select_recipe.html")
|
||||
|
||||
|
||||
@measure_bp.route("/tasks/<int:recipe_id>")
|
||||
def task_list(recipe_id: int):
|
||||
"""Task list for selected recipe."""
|
||||
if "user" not in session:
|
||||
return redirect(url_for("auth.login"))
|
||||
return render_template("measure/task_list.html", recipe_id=recipe_id)
|
||||
|
||||
|
||||
@measure_bp.route("/execute/<int:task_id>")
|
||||
def task_execute(task_id: int):
|
||||
"""Execute measurements for a task."""
|
||||
if "user" not in session:
|
||||
return redirect(url_for("auth.login"))
|
||||
return render_template("measure/task_execute.html", task_id=task_id)
|
||||
|
||||
|
||||
@measure_bp.route("/complete/<int:recipe_id>")
|
||||
def task_complete(recipe_id: int):
|
||||
"""Task completion summary."""
|
||||
if "user" not in session:
|
||||
return redirect(url_for("auth.login"))
|
||||
return render_template("measure/task_complete.html", recipe_id=recipe_id)
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Metrologist blueprint - SPC statistics and dashboards."""
|
||||
from flask import Blueprint, render_template, session, redirect, url_for
|
||||
|
||||
statistics_bp = Blueprint("statistics", __name__)
|
||||
|
||||
|
||||
@statistics_bp.route("/dashboard")
|
||||
def dashboard():
|
||||
"""SPC dashboard overview."""
|
||||
if "user" not in session:
|
||||
return redirect(url_for("auth.login"))
|
||||
return render_template("statistics/dashboard.html")
|
||||
|
||||
|
||||
@statistics_bp.route("/control-chart")
|
||||
def control_chart():
|
||||
"""X-bar / R control chart."""
|
||||
if "user" not in session:
|
||||
return redirect(url_for("auth.login"))
|
||||
return render_template("statistics/control_chart.html")
|
||||
|
||||
|
||||
@statistics_bp.route("/histogram")
|
||||
def histogram():
|
||||
"""Histogram with normal curve."""
|
||||
if "user" not in session:
|
||||
return redirect(url_for("auth.login"))
|
||||
return render_template("statistics/histogram.html")
|
||||
|
||||
|
||||
@statistics_bp.route("/capability")
|
||||
def capability():
|
||||
"""Cp/Cpk/Pp/Ppk capability gauge."""
|
||||
if "user" not in session:
|
||||
return redirect(url_for("auth.login"))
|
||||
return render_template("statistics/capability.html")
|
||||
|
||||
|
||||
@statistics_bp.route("/trend")
|
||||
def trend():
|
||||
"""Temporal trends and period comparison."""
|
||||
if "user" not in session:
|
||||
return redirect(url_for("auth.login"))
|
||||
return render_template("statistics/trend.html")
|
||||
@@ -0,0 +1,24 @@
|
||||
"""TieMeasureFlow Client Configuration."""
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv(os.path.join(os.path.dirname(__file__), '..', '.env'))
|
||||
|
||||
|
||||
class Config:
|
||||
"""Flask client configuration."""
|
||||
|
||||
# Flask
|
||||
SECRET_KEY = os.getenv("CLIENT_SECRET_KEY", "change-this-to-another-random-secret-key")
|
||||
|
||||
# API Server connection
|
||||
API_SERVER_URL = os.getenv("API_SERVER_URL", "http://localhost:8000")
|
||||
|
||||
# Session
|
||||
SESSION_COOKIE_HTTPONLY = True
|
||||
SESSION_COOKIE_SAMESITE = "Lax"
|
||||
|
||||
# Babel i18n
|
||||
BABEL_DEFAULT_LOCALE = "it"
|
||||
BABEL_DEFAULT_TIMEZONE = "Europe/Rome"
|
||||
LANGUAGES = {"it": "Italiano", "en": "English"}
|
||||
@@ -0,0 +1,10 @@
|
||||
# Flask
|
||||
flask>=3.0.0
|
||||
flask-babel>=4.0.0
|
||||
|
||||
# HTTP Client (to call FastAPI server)
|
||||
requests>=2.31.0
|
||||
urllib3>=2.0.0
|
||||
|
||||
# Utilities
|
||||
python-dotenv>=1.0.0
|
||||
@@ -0,0 +1,80 @@
|
||||
"""API Client - wrapper for HTTP requests to FastAPI server."""
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
from flask import session
|
||||
|
||||
from config import Config
|
||||
|
||||
|
||||
class APIClient:
|
||||
"""HTTP client for TieMeasureFlow API server."""
|
||||
|
||||
def __init__(self):
|
||||
self.base_url = Config.API_SERVER_URL.rstrip("/")
|
||||
self.timeout = 30
|
||||
|
||||
@property
|
||||
def _headers(self) -> dict[str, str]:
|
||||
"""Build request headers with API key from session."""
|
||||
headers = {"Content-Type": "application/json"}
|
||||
api_key = session.get("api_key")
|
||||
if api_key:
|
||||
headers["X-API-Key"] = api_key
|
||||
return headers
|
||||
|
||||
def get(self, endpoint: str, params: dict | None = None) -> dict[str, Any]:
|
||||
"""GET request to API server."""
|
||||
response = requests.get(
|
||||
f"{self.base_url}{endpoint}",
|
||||
headers=self._headers,
|
||||
params=params,
|
||||
timeout=self.timeout,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
def post(self, endpoint: str, data: dict | None = None, files: dict | None = None) -> dict[str, Any]:
|
||||
"""POST request to API server."""
|
||||
if files:
|
||||
headers = {"X-API-Key": session.get("api_key", "")}
|
||||
response = requests.post(
|
||||
f"{self.base_url}{endpoint}",
|
||||
headers=headers,
|
||||
data=data,
|
||||
files=files,
|
||||
timeout=self.timeout,
|
||||
)
|
||||
else:
|
||||
response = requests.post(
|
||||
f"{self.base_url}{endpoint}",
|
||||
headers=self._headers,
|
||||
json=data,
|
||||
timeout=self.timeout,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
def put(self, endpoint: str, data: dict | None = None) -> dict[str, Any]:
|
||||
"""PUT request to API server."""
|
||||
response = requests.put(
|
||||
f"{self.base_url}{endpoint}",
|
||||
headers=self._headers,
|
||||
json=data,
|
||||
timeout=self.timeout,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
def delete(self, endpoint: str) -> dict[str, Any]:
|
||||
"""DELETE request to API server."""
|
||||
response = requests.delete(
|
||||
f"{self.base_url}{endpoint}",
|
||||
headers=self._headers,
|
||||
timeout=self.timeout,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
|
||||
api_client = APIClient()
|
||||
@@ -0,0 +1,3 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
Vendored
@@ -0,0 +1,34 @@
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
module.exports = {
|
||||
content: [
|
||||
"./templates/**/*.html",
|
||||
"./static/js/**/*.js",
|
||||
],
|
||||
darkMode: 'class',
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
primary: {
|
||||
DEFAULT: '#2563EB',
|
||||
dark: '#1E40AF',
|
||||
light: '#3B82F6',
|
||||
},
|
||||
steel: {
|
||||
DEFAULT: '#64748B',
|
||||
light: '#94A3B8',
|
||||
dark: '#475569',
|
||||
},
|
||||
measure: {
|
||||
pass: '#059669',
|
||||
warning: '#D97706',
|
||||
fail: '#DC2626',
|
||||
},
|
||||
},
|
||||
fontFamily: {
|
||||
sans: ['Inter', 'system-ui', 'sans-serif'],
|
||||
mono: ['JetBrains Mono', 'monospace'],
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [],
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
[python: blueprints/**.py]
|
||||
[jinja2: templates/**.html]
|
||||
encoding = utf-8
|
||||
@@ -0,0 +1,29 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
mysql:
|
||||
image: mysql:8.0
|
||||
container_name: tmflow-mysql
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
MYSQL_ROOT_PASSWORD: root_password_change_me
|
||||
MYSQL_DATABASE: tiemeasureflow
|
||||
MYSQL_USER: tmflow
|
||||
MYSQL_PASSWORD: change_me_in_production
|
||||
ports:
|
||||
- "3306:3306"
|
||||
volumes:
|
||||
- mysql_data:/var/lib/mysql
|
||||
command: >
|
||||
--default-authentication-plugin=mysql_native_password
|
||||
--character-set-server=utf8mb4
|
||||
--collation-server=utf8mb4_unicode_ci
|
||||
healthcheck:
|
||||
test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
volumes:
|
||||
mysql_data:
|
||||
driver: local
|
||||
@@ -0,0 +1,51 @@
|
||||
"""TieMeasureFlow Server Configuration."""
|
||||
from pathlib import Path
|
||||
from pydantic_settings import BaseSettings
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
"""Application settings loaded from environment variables."""
|
||||
|
||||
# Database
|
||||
db_host: str = "localhost"
|
||||
db_port: int = 3306
|
||||
db_name: str = "tiemeasureflow"
|
||||
db_user: str = "tmflow"
|
||||
db_password: str = "change_me_in_production"
|
||||
|
||||
# Server
|
||||
server_host: str = "0.0.0.0"
|
||||
server_port: int = 8000
|
||||
server_secret_key: str = "change-this-to-a-random-secret-key"
|
||||
server_cors_origins: str = "http://localhost:5000"
|
||||
|
||||
# File Storage
|
||||
upload_dir: str = "uploads"
|
||||
max_upload_size_mb: int = 50
|
||||
|
||||
# SSL (Production)
|
||||
ssl_certfile: str | None = None
|
||||
ssl_keyfile: str | None = None
|
||||
|
||||
@property
|
||||
def database_url(self) -> str:
|
||||
"""Async MySQL connection string."""
|
||||
return (
|
||||
f"mysql+asyncmy://{self.db_user}:{self.db_password}"
|
||||
f"@{self.db_host}:{self.db_port}/{self.db_name}"
|
||||
)
|
||||
|
||||
@property
|
||||
def cors_origins(self) -> list[str]:
|
||||
"""Parse CORS origins from comma-separated string."""
|
||||
return [origin.strip() for origin in self.server_cors_origins.split(",")]
|
||||
|
||||
@property
|
||||
def upload_path(self) -> Path:
|
||||
"""Absolute path to upload directory."""
|
||||
return Path(__file__).parent / self.upload_dir
|
||||
|
||||
model_config = {"env_file": "../.env", "env_file_encoding": "utf-8"}
|
||||
|
||||
|
||||
settings = Settings()
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Async SQLAlchemy database engine and session management."""
|
||||
from collections.abc import AsyncGenerator
|
||||
|
||||
from sqlalchemy.ext.asyncio import (
|
||||
AsyncSession,
|
||||
async_sessionmaker,
|
||||
create_async_engine,
|
||||
)
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
from config import settings
|
||||
|
||||
# Create async engine
|
||||
engine = create_async_engine(
|
||||
settings.database_url,
|
||||
echo=False,
|
||||
pool_size=10,
|
||||
max_overflow=20,
|
||||
pool_recycle=3600,
|
||||
)
|
||||
|
||||
# Session factory
|
||||
async_session_factory = async_sessionmaker(
|
||||
engine,
|
||||
class_=AsyncSession,
|
||||
expire_on_commit=False,
|
||||
)
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
"""Base class for all SQLAlchemy models."""
|
||||
pass
|
||||
|
||||
|
||||
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
||||
"""Dependency for FastAPI - yields an async database session."""
|
||||
async with async_session_factory() as session:
|
||||
try:
|
||||
yield session
|
||||
await session.commit()
|
||||
except Exception:
|
||||
await session.rollback()
|
||||
raise
|
||||
finally:
|
||||
await session.close()
|
||||
|
||||
|
||||
async def init_db() -> None:
|
||||
"""Create all tables (dev only - use Alembic in production)."""
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
@@ -0,0 +1,45 @@
|
||||
"""TieMeasureFlow Server - FastAPI Entry Point."""
|
||||
from contextlib import asynccontextmanager
|
||||
from collections.abc import AsyncGenerator
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from config import settings
|
||||
from database import init_db
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
|
||||
"""Application lifespan: startup and shutdown events."""
|
||||
# Startup
|
||||
# Ensure upload directories exist
|
||||
for subdir in ["images", "pdfs", "logos", "reports"]:
|
||||
(settings.upload_path / subdir).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
yield
|
||||
|
||||
# Shutdown (cleanup if needed)
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="TieMeasureFlow API",
|
||||
description="API per gestione task misurazioni con calibro manuale",
|
||||
version="0.1.0",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
# CORS middleware
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=settings.cors_origins,
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/health")
|
||||
async def health_check() -> dict:
|
||||
"""Health check endpoint."""
|
||||
return {"status": "ok", "service": "TieMeasureFlow API", "version": "0.1.0"}
|
||||
@@ -0,0 +1,36 @@
|
||||
[alembic]
|
||||
script_location = .
|
||||
sqlalchemy.url = mysql+asyncmy://tmflow:change_me_in_production@localhost:3306/tiemeasureflow
|
||||
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARN
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[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
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Alembic environment configuration for async SQLAlchemy."""
|
||||
import asyncio
|
||||
from logging.config import fileConfig
|
||||
|
||||
from alembic import context
|
||||
from sqlalchemy import pool
|
||||
from sqlalchemy.ext.asyncio import create_async_engine
|
||||
|
||||
# Alembic Config object
|
||||
config = context.config
|
||||
|
||||
# Logging configuration
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
# Import all models so Alembic can detect them
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from config import settings
|
||||
from database import Base
|
||||
|
||||
# Override alembic.ini URL with .env settings (keep in sync)
|
||||
config.set_main_option("sqlalchemy.url", settings.database_url)
|
||||
|
||||
# Import all models here so they register with Base.metadata
|
||||
# from models.user import User
|
||||
# from models.recipe import Recipe, RecipeVersion
|
||||
# from models.task import RecipeTask, RecipeSubtask
|
||||
# from models.measurement import Measurement
|
||||
# from models.access_log import AccessLog
|
||||
# from models.setting import SystemSetting
|
||||
|
||||
target_metadata = Base.metadata
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
"""Run migrations in 'offline' mode."""
|
||||
url = config.get_main_option("sqlalchemy.url")
|
||||
context.configure(
|
||||
url=url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def do_run_migrations(connection):
|
||||
"""Run migrations with connection."""
|
||||
context.configure(connection=connection, target_metadata=target_metadata)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
async def run_async_migrations() -> None:
|
||||
"""Run migrations in 'online' mode with async engine."""
|
||||
connectable = create_async_engine(
|
||||
config.get_main_option("sqlalchemy.url"),
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
|
||||
async with connectable.connect() as connection:
|
||||
await connection.run_sync(do_run_migrations)
|
||||
|
||||
await connectable.dispose()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
"""Run migrations in 'online' mode."""
|
||||
asyncio.run(run_async_migrations())
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
@@ -0,0 +1,26 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = ${repr(up_revision)}
|
||||
down_revision: Union[str, None] = ${repr(down_revision)}
|
||||
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
${downgrades if downgrades else "pass"}
|
||||
@@ -0,0 +1,28 @@
|
||||
# FastAPI + ASGI
|
||||
fastapi>=0.110.0
|
||||
uvicorn[standard]>=0.30.0
|
||||
|
||||
# Database
|
||||
sqlalchemy[asyncio]>=2.0.0
|
||||
asyncmy>=0.2.0
|
||||
alembic>=1.13.0
|
||||
|
||||
# Validation
|
||||
pydantic>=2.0.0
|
||||
pydantic-settings>=2.0.0
|
||||
|
||||
# Security
|
||||
passlib[bcrypt]>=1.7.0
|
||||
bcrypt>=4.0.0
|
||||
|
||||
# File handling
|
||||
pillow>=10.0.0
|
||||
python-multipart>=0.0.6
|
||||
|
||||
# Reports
|
||||
plotly>=5.0.0
|
||||
kaleido>=0.2.0
|
||||
weasyprint>=62.0
|
||||
|
||||
# Utilities
|
||||
python-dotenv>=1.0.0
|
||||
Reference in New Issue
Block a user