data = {"name": "Production Manager"}role = RoleService.create(data)
Implementation from services.py:27:
@staticmethoddef create(data: dict) -> dict: name = data.get("name") if not name or not name.strip(): raise ValidationError("El nombre del rol es requerido") name = name.strip() existing = Role.query.filter_by(name=name).first() if existing: raise ConflictError(f"Ya existe un rol con el nombre '{name}'") role = Role(name=name) db.session.add(role) db.session.commit() return role.to_dict()
@staticmethoddef get_by_id(id_role: int) -> Role: role = Role.query.get(id_role) if not role: raise NotFoundError(f"No se encontró el rol con ID {id_role}") return role
data = {"name": "Senior Production Manager"}RoleService.update(id_role, data)
Implementation from services.py:83:
@staticmethoddef update(id_role: int, data: dict) -> dict: role = RoleService.get_by_id(id_role) name = data.get("name") if not name or not name.strip(): raise ValidationError("El nombre del rol es requerido") name = name.strip() existing = Role.query.filter( Role.name == name, Role.id_role != id_role ).first() if existing: raise ConflictError(f"Ya existe un rol con el nombre '{name}'") role.name = name db.session.commit() return role.to_dict()
The RoleForm class in app/catalogs/roles/forms.py:10 defines the input form:
class RoleForm(FlaskForm): name = StringField( "Nombre", validators=[ DataRequired(message="El nombre del rol es requerido"), Length(max=50, message="El nombre no puede exceder 50 caracteres"), ], )
# Get all active rolesroles = RoleService.get_all()for role in roles: print(f"Role ID {role.id_role}: {role.name}")# Get specific rolerole = RoleService.get_by_id(1)print(f"Role: {role.name}")
Deleting Roles: Before deleting a role, ensure no users are currently assigned to it. Consider implementing a check:
# Future implementationdef delete(id_role: int) -> None: role = RoleService.get_by_id(id_role) # Check if role is in use if role.users.count() > 0: raise ConflictError("Cannot delete role with assigned users") role.active = False role.deleted_at = func.current_timestamp() db.session.commit()