​python_modules /
module-09 / ex2 / space_crew.py
106 commits
26-05-2026
131 lines 4.3 kB
  1import json
  2from datetime import datetime
  3from enum import Enum
  4from typing import Any
  5from pydantic import (  # type: ignore
  6    BaseModel,
  7    Field,
  8    ValidationError,
  9    model_validator
 10)
 11
 12
 13class Rank(Enum):
 14    cadet = "cadet"
 15    officer = "officer"
 16    lieutenant = "lieutenant"
 17    captain = "captain"
 18    commander = "commander"
 19
 20
 21class CrewMember(BaseModel):
 22    member_id: str = Field(..., min_length=3, max_length=10)
 23    name: str = Field(..., min_length=2, max_length=50)
 24    rank: Rank
 25    age: int = Field(..., ge=18, le=80)
 26    specialization: str = Field(..., min_length=3, max_length=30)
 27    years_experience: int = Field(..., ge=0, le=50)
 28    is_active: bool = True
 29
 30
 31class SpaceMission(BaseModel):
 32    mission_id: str = Field(..., min_length=5, max_length=15)
 33    mission_name: str = Field(..., min_length=3, max_length=100)
 34    destination: str = Field(..., min_length=3, max_length=50)
 35    launch_date: datetime
 36    duration_days: int = Field(..., ge=1, le=3650)
 37    crew: list[CrewMember] = Field(..., min_length=1, max_length=12)
 38    mission_status: str = "planned"
 39    budget_millions: float = Field(..., ge=1.0, le=10000.0)
 40
 41    @model_validator(mode="after")
 42    def safety_requirements(self) -> "SpaceMission":
 43        if not self.mission_id.startswith("M"):
 44            raise ValueError("mission_id must start with 'M'")
 45        cap_com = {Rank.captain, Rank.commander}
 46        if not any(m.rank in cap_com for m in self.crew):
 47            raise ValueError(
 48                "Mission must have at least one Commander or Captain"
 49            )
 50        if self.duration_days > 365:
 51            experienced = sum(1 for m in self.crew if m.years_experience >= 5)
 52            ratio = experienced / len(self.crew)
 53            if ratio < 0.5:
 54                raise ValueError(
 55                    "Mission over 365 days requires 50% experienced crew"
 56                )
 57        inactive = [m.name for m in self.crew if not m.is_active]
 58        if inactive:
 59            raise ValueError("All crew members must be active")
 60        return self
 61
 62
 63def load_json(path: str) -> list[dict[str, Any]]:
 64    try:
 65        with open(path) as f:
 66            return json.load(f)
 67    except FileNotFoundError:
 68        print(f"Error: '{path}' not found")
 69        return []
 70    except json.JSONDecodeError as e:
 71        print(f"Error: invalid JSON in '{path}' - {e}")
 72        return []
 73
 74
 75def main() -> None:
 76    records = load_json("space_missions.json")
 77    print("Space Mission Crew Validation")
 78    for record in records:
 79        try:
 80            mission = SpaceMission.model_validate(record)
 81            print("=" * 50)
 82            print("Valid mission created:")
 83            print(f"Mission: {mission.mission_name}")
 84            print(f"ID: {mission.mission_id}")
 85            print(f"Destination: {mission.destination}")
 86            print(f"Duration: {mission.duration_days} days")
 87            print(f"Budget: ${mission.budget_millions}M")
 88            print(f"Crew size: {len(mission.crew)}")
 89            print("Crew members:")
 90            for member in mission.crew:
 91                print(
 92                    f"  - {member.name} "
 93                    f"({member.rank.value}) - {member.specialization}"
 94                )
 95            print()
 96        except ValidationError as e:
 97            msg = e.errors()[0]["msg"].removeprefix("Value error, ")
 98            print("=" * 50)
 99            print("Expected validation error:")
100            print(msg)
101            print()
102
103    try:
104        cadet = CrewMember(
105            member_id="CM001",
106            name="Sarah Connor",
107            rank=Rank.cadet,
108            age=43,
109            specialization="Mission Command",
110            years_experience=20,
111        )
112        SpaceMission(
113            mission_id="M11111",
114            mission_name="Solar Observatory Research Mission",
115            destination="Solar Observatory",
116            launch_date="2024-03-30T00:00:00",
117            duration_days=451,
118            crew=[cadet],
119            mission_status="planned",
120            budget_millions=2208.1,
121        )
122    except ValidationError as e:
123        msg = e.errors()[0]["msg"].removeprefix("Value error, ")
124        print("=" * 50)
125        print("Expected validation error:")
126        print(msg)
127        print()
128
129
130if __name__ == "__main__":
131    main()