basic profile

This commit is contained in:
Nicola Malizia
2025-10-10 19:22:01 +02:00
parent c9a0d557aa
commit 41da3553aa
34 changed files with 1555 additions and 35 deletions

13
packages/backend/.env Normal file
View File

@@ -0,0 +1,13 @@
# ============== POSTGRES ==============
POSTGRES_SERVER=db
POSTGRES_DB=mydatabase
POSTGRES_USER=myuser
POSTGRES_PASSWORD=mysecretpassword
# URL del database per SQLAlchemy e Alembic
# La porta 5432 è quella interna di Docker. 'db' è il nome del servizio in docker-compose.
DATABASE_URL=postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_SERVER}/${POSTGRES_DB}
# ============== FRONTEND ==============
# L'URL a cui il frontend contatterà il backend (attraverso il proxy)
VITE_API_URL=http://localhost:8080/api

View File

@@ -1,10 +1,147 @@
# ... altre configurazioni ...
[alembic]
# ...
script_location = alembic
# ...
# A generic, single database configuration.
# Aggiungi questa riga per leggere l'URL dal file .env
[alembic]
# path to migration scripts.
# this is typically a path given in POSIX (e.g. forward slashes)
# format, relative to the token %(here)s which refers to the location of this
# ini file
script_location = %(here)s/alembic
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory. for multiple paths, the path separator
# is defined by "path_separator" below.
prepend_sys_path = .
# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python>=3.9 or backports.zoneinfo library and tzdata library.
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
# string value is passed to ZoneInfo()
# leave blank for localtime
# timezone =
# max length of characters to apply to the "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; This defaults
# to <script_location>/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "path_separator"
# below.
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
# path_separator; This indicates what character is used to split lists of file
# paths, including version_locations and prepend_sys_path within configparser
# files such as alembic.ini.
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
# to provide os-dependent path splitting.
#
# Note that in order to support legacy alembic.ini files, this default does NOT
# take place if path_separator is not present in alembic.ini. If this
# option is omitted entirely, fallback logic is as follows:
#
# 1. Parsing of the version_locations option falls back to using the legacy
# "version_path_separator" key, which if absent then falls back to the legacy
# behavior of splitting on spaces and/or commas.
# 2. Parsing of the prepend_sys_path option falls back to the legacy
# behavior of splitting on spaces, commas, or colons.
#
# Valid values for path_separator are:
#
# path_separator = :
# path_separator = ;
# path_separator = space
# path_separator = newline
#
# Use os.pathsep. Default configuration used for new projects.
path_separator = os
# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
# database URL. This is consumed by the user-maintained env.py script only.
# other means of configuring database URLs may be customized within the env.py
# file.
sqlalchemy.url = ${DATABASE_URL}
# ... altre configurazioni ...
[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME
# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
# hooks = ruff
# ruff.type = module
# ruff.module = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
# Alternatively, use the exec runner to execute a binary found on your PATH
# hooks = ruff
# ruff.type = exec
# ruff.executable = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
# Logging configuration. This is also consumed by the user-maintained
# env.py script only.
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARNING
handlers = console
qualname =
[logger_sqlalchemy]
level = WARNING
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

View File

@@ -0,0 +1 @@
Generic single-database configuration.

View File

@@ -0,0 +1,45 @@
# packages/backend/alembic/env.py
import os
import sys
from logging.config import fileConfig
from dotenv import load_dotenv # <--- 1. AGGIUNGI QUESTO IMPORT
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
# Aggiungi la root del progetto (/app) al percorso di ricerca di Python
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
# Aggiungi l'import del tuo modello specifico sotto l'import di Base
from app.models import Base, Celebrity
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# === 2. AGGIUNGI QUESTA SEZIONE PER CARICARE LA VARIABILE D'AMBIENTE ===
# Carica il file .env che si trova nella root del progetto (/app)
# Dato che lo script è in /app/alembic, dobbiamo risalire di un livello
dotenv_path = os.path.join(os.path.dirname(__file__), '..', '.env')
load_dotenv(dotenv_path=dotenv_path)
# Imposta programmaticamente l'URL del database nell'oggetto di configurazione di Alembic
config.set_main_option('sqlalchemy.url', os.getenv('DATABASE_URL'))
# === FINE DELLA SEZIONE DA AGGIUNGERE ===
# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = Base.metadata
# ... il resto del file rimane invariato ...

View File

@@ -0,0 +1,28 @@
"""${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, Sequence[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:
"""Upgrade schema."""
${upgrades if upgrades else "pass"}
def downgrade() -> None:
"""Downgrade schema."""
${downgrades if downgrades else "pass"}

View File

@@ -0,0 +1,28 @@
"""Initial migration with celebrities table
Revision ID: 23353f53a7cf
Revises:
Create Date: 2025-10-10 17:00:56.622311
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '23353f53a7cf'
down_revision: Union[str, Sequence[str], None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
pass
def downgrade() -> None:
"""Downgrade schema."""
pass

Binary file not shown.

View File

@@ -0,0 +1,37 @@
from sqlalchemy.orm import Session
from . import models, schemas
def get_celebrity(db: Session, celebrity_id: int):
return db.query(models.Celebrity).filter(models.Celebrity.id == celebrity_id).first()
def get_celebrities(db: Session, skip: int = 0, limit: int = 100):
return db.query(models.Celebrity).offset(skip).limit(limit).all()
def create_celebrity(db: Session, celebrity: schemas.CelebrityCreate):
db_celebrity = models.Celebrity(**celebrity.model_dump())
db.add(db_celebrity)
db.commit()
db.refresh(db_celebrity)
return db_celebrity
def update_celebrity(db: Session, celebrity_id: int, celebrity_update: schemas.CelebrityUpdate):
db_celebrity = get_celebrity(db, celebrity_id)
if not db_celebrity:
return None
update_data = celebrity_update.model_dump(exclude_unset=True)
for key, value in update_data.items():
setattr(db_celebrity, key, value)
db.commit()
db.refresh(db_celebrity)
return db_celebrity
def delete_celebrity(db: Session, celebrity_id: int):
db_celebrity = get_celebrity(db, celebrity_id)
if not db_celebrity:
return None
db.delete(db_celebrity)
db.commit()
return db_celebrity

View File

@@ -0,0 +1,25 @@
import os
from sqlalchemy import create_engine
# MODIFICA: La best practice moderna è usare DeclarativeBase
from sqlalchemy.orm import sessionmaker, DeclarativeBase
from dotenv import load_dotenv
load_dotenv()
DATABASE_URL = os.getenv("DATABASE_URL")
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# Assicurati che Base sia definito così
class Base(DeclarativeBase):
pass
# Dependency per ottenere una sessione DB per ogni richiesta
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()

View File

@@ -1,7 +1,11 @@
from fastapi import FastAPI
from .routers import celebrities # Importa il nuovo router
app = FastAPI()
# Includi il router delle celebrities nell'app principale
app.include_router(celebrities.router)
@app.get("/api")
def read_root():
return {"message": "Ciao dal backend FastAPI!"}

View File

@@ -0,0 +1,91 @@
import enum
from sqlalchemy import (Column, Integer, String, Date, Enum, Boolean,
DECIMAL, Text, TIMESTAMP, ForeignKey)
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship # Aggiungi questo import
from .database import Base
# Definiamo gli Enum Python corrispondenti ai tipi custom di PostgreSQL
class GenderType(str, enum.Enum):
male = "male"
female = "female"
other = "other"
class ShoeSystemType(str, enum.Enum):
EU = "EU"
US = "US"
UK = "UK"
class BraSystemType(str, enum.Enum):
US = "US"
UK = "UK"
EU = "EU"
FR = "FR"
AU = "AU"
IT = "IT"
JP = "JP"
class Image(Base):
__tablename__ = "images"
id = Column(Integer, primary_key=True, index=True)
celebrity_id = Column(Integer, ForeignKey("celebrities.id"), nullable=False)
file_path = Column(String, nullable=False)
caption = Column(Text, nullable=True)
uploaded_at = Column(TIMESTAMP(timezone=True), server_default=func.now())
# Relazione inversa: "questa immagine appartiene a UNA celebrità".
# Specifichiamo che deve usare la colonna `celebrity_id` di QUESTA tabella.
celebrity = relationship("Celebrity", back_populates="images", foreign_keys=[celebrity_id])
class Celebrity(Base):
__tablename__ = "celebrities"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, unique=True, nullable=False, index=True)
gender = Column(Enum(GenderType), nullable=False)
birth_date = Column(Date, nullable=True)
birth_place = Column(String, nullable=True)
nationality = Column(String, nullable=True)
ethnicity = Column(String, nullable=True)
sexuality = Column(String, nullable=True)
hair_color = Column(String, nullable=True)
eye_color = Column(String, nullable=True)
height_cm = Column(Integer, nullable=True)
weight_kg = Column(Integer, nullable=True)
body_type = Column(String, nullable=True)
bust_cm = Column(Integer, nullable=True)
waist_cm = Column(Integer, nullable=True)
hips_cm = Column(Integer, nullable=True)
chest_circumference_cm = Column(Integer, nullable=True)
bra_band_size = Column(Integer, nullable=True)
bra_cup_size = Column(String, nullable=True)
bra_size_system = Column(Enum(BraSystemType), nullable=True)
boobs_are_natural = Column(Boolean, nullable=True)
shoe_size = Column(DECIMAL(4, 1), nullable=True)
shoe_size_system = Column(Enum(ShoeSystemType), nullable=True)
biography = Column(Text, nullable=True)
official_website = Column(String, nullable=True)
# 1. Relazione "una celebrità ha MOLTE immagini".
# SQLAlchemy deve usare la FK che si trova nella tabella Image.
images = relationship("Image", back_populates="celebrity", foreign_keys="[Image.celebrity_id]")
# Chiave esterna per l'immagine del profilo
profile_image_id = Column(Integer, ForeignKey("images.id", ondelete="SET NULL"), nullable=True)
# 2. Relazione "una celebrità ha UNA immagine del profilo".
# SQLAlchemy deve usare la FK che si trova in QUESTA tabella (celebrities).
profile_image = relationship("Image", foreign_keys=[profile_image_id])
created_at = Column(TIMESTAMP(timezone=True), server_default=func.now())
updated_at = Column(TIMESTAMP(timezone=True), default=func.now(), onupdate=func.now())
# Nota: le altre tabelle (images, tattoos, etc.) andrebbero modellate qui
# se si volessero gestire le relazioni in modo completo con SQLAlchemy.
# Per questo esempio, ci concentriamo solo sulla tabella `celebrities`.

View File

@@ -0,0 +1,43 @@
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from .. import crud, models, schemas
from ..database import get_db
router = APIRouter(
prefix="/api/celebrities",
tags=["celebrities"],
responses={404: {"description": "Not found"}},
)
@router.post("/", response_model=schemas.Celebrity, status_code=201)
def create_celebrity(celebrity: schemas.CelebrityCreate, db: Session = Depends(get_db)):
# Qui potresti aggiungere un check per vedere se una celebrità con lo stesso nome esiste già
return crud.create_celebrity(db=db, celebrity=celebrity)
@router.get("/", response_model=List[schemas.Celebrity])
def read_celebrities(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
celebrities = crud.get_celebrities(db, skip=skip, limit=limit)
return celebrities
@router.get("/{celebrity_id}", response_model=schemas.Celebrity)
def read_celebrity(celebrity_id: int, db: Session = Depends(get_db)):
db_celebrity = crud.get_celebrity(db, celebrity_id=celebrity_id)
if db_celebrity is None:
raise HTTPException(status_code=404, detail="Celebrity not found")
return db_celebrity
@router.put("/{celebrity_id}", response_model=schemas.Celebrity)
def update_celebrity(celebrity_id: int, celebrity: schemas.CelebrityUpdate, db: Session = Depends(get_db)):
db_celebrity = crud.update_celebrity(db, celebrity_id=celebrity_id, celebrity_update=celebrity)
if db_celebrity is None:
raise HTTPException(status_code=404, detail="Celebrity not found")
return db_celebrity
@router.delete("/{celebrity_id}", response_model=schemas.Celebrity)
def delete_celebrity(celebrity_id: int, db: Session = Depends(get_db)):
db_celebrity = crud.delete_celebrity(db, celebrity_id=celebrity_id)
if db_celebrity is None:
raise HTTPException(status_code=404, detail="Celebrity not found")
return db_celebrity

View File

@@ -0,0 +1,73 @@
from pydantic import BaseModel
from typing import Optional
from datetime import date, datetime
from .models import GenderType, ShoeSystemType, BraSystemType
# Schema di base con i campi comuni
class CelebrityBase(BaseModel):
name: str
gender: GenderType
birth_date: Optional[date] = None
birth_place: Optional[str] = None
nationality: Optional[str] = None
ethnicity: Optional[str] = None
sexuality: Optional[str] = None
hair_color: Optional[str] = None
eye_color: Optional[str] = None
height_cm: Optional[int] = None
weight_kg: Optional[int] = None
body_type: Optional[str] = None
bust_cm: Optional[int] = None
waist_cm: Optional[int] = None
hips_cm: Optional[int] = None
chest_circumference_cm: Optional[int] = None
bra_band_size: Optional[int] = None
bra_cup_size: Optional[str] = None
bra_size_system: Optional[BraSystemType] = None
boobs_are_natural: Optional[bool] = None
shoe_size: Optional[float] = None
shoe_size_system: Optional[ShoeSystemType] = None
biography: Optional[str] = None
official_website: Optional[str] = None
profile_image_id: Optional[int] = None
# Schema per la creazione di una nuova celebrità (eredita da Base)
class CelebrityCreate(CelebrityBase):
pass
# Schema per l'aggiornamento (tutti i campi sono opzionali)
class CelebrityUpdate(BaseModel):
name: Optional[str] = None
gender: Optional[GenderType] = None
birth_date: Optional[date] = None
birth_place: Optional[str] = None
nationality: Optional[str] = None
ethnicity: Optional[str] = None
sexuality: Optional[str] = None
hair_color: Optional[str] = None
eye_color: Optional[str] = None
height_cm: Optional[int] = None
weight_kg: Optional[int] = None
body_type: Optional[str] = None
bust_cm: Optional[int] = None
waist_cm: Optional[int] = None
hips_cm: Optional[int] = None
chest_circumference_cm: Optional[int] = None
bra_band_size: Optional[int] = None
bra_cup_size: Optional[str] = None
bra_size_system: Optional[BraSystemType] = None
boobs_are_natural: Optional[bool] = None
shoe_size: Optional[float] = None
shoe_size_system: Optional[ShoeSystemType] = None
biography: Optional[str] = None
official_website: Optional[str] = None
profile_image_id: Optional[int] = None
# Schema per la lettura dei dati (include campi generati dal DB)
class Celebrity(CelebrityBase):
id: int
created_at: datetime
updated_at: datetime
class Config:
from_attributes = True # Permette a Pydantic di leggere dati da un modello ORM

View File

@@ -2,6 +2,10 @@
fastapi
uvicorn[standard]
# Pydantic per la validazione e le impostazioni
pydantic
pydantic-settings
# Database
sqlalchemy
psycopg2-binary