Skip to content

Latest commit

 

History

History
609 lines (377 loc) · 13.5 KB

2.7.md

File metadata and controls

609 lines (377 loc) · 13.5 KB

Mini-projekt / Mini-project


Choose Your Project / Wybierz swój projekt

Pick one of these projects to practice files, JSON, exceptions, modules, and APIs.

Wybierz jeden z tych projektów aby przećwiczyć pliki, JSON, wyjątki, moduły i API.

All APIs are free and require no authentication — perfect for learning!

Wszystkie API są darmowe i nie wymagają uwierzytelniania — idealne do nauki!


Project Option 1: Dog Gallery / Opcja 1: Galeria Psów

API: Dog CEO's Dog API

Free API serving random dog images.

Darmowe API serwujące losowe zdjęcia psów.

Requirements / Wymagania

Build a command-line dog image gallery that:

Zbuduj konsolową galerię zdjęć psów, która:

  1. Fetches random dog images from the API

    Pobiera losowe zdjęcia psów z API

  2. Saves image URLs to JSON file

    Zapisuje URL-e obrazów do pliku JSON

  3. Shows user their saved collection

    Pokazuje użytkownikowi zapisaną kolekcję

  4. Handles errors gracefully (network issues, etc.)

    Obsługuje błędy elegancko (problemy sieciowe, itp.)

API Endpoints / Endpointy API

# Random dog image / Losowe zdjęcie psa
"https://dog.ceo/api/breeds/image/random"

# Multiple random images / Wiele losowych zdjęć
"https://dog.ceo/api/breeds/image/random/3"

# List all breeds / Lista wszystkich ras
"https://dog.ceo/api/breeds/list/all"

# Random image of specific breed / Losowe zdjęcie konkretnej rasy
"https://dog.ceo/api/breed/hound/images/random"

Starter Code / Kod startowy

Create dog_gallery.py:

Utwórz dog_gallery.py:

import requests
import json
from pathlib import Path
from typing import Dict, List, Any

class DogGallery:
    API_URL = "https://dog.ceo/api"

    def __init__(self, storage_file: str = "dog_collection.json"):
        self.storage_file = Path(storage_file)
        self.collection: List[str] = self._load_collection()

    def _load_collection(self) -> List[str]:
        """Load saved collection from file"""
        if self.storage_file.exists():
            try:
                content = self.storage_file.read_text()
                data = json.loads(content)
                return data.get("images", [])
            except json.JSONDecodeError:
                print("⚠ Could not load collection - starting fresh")
                return []
        return []

    def _save_collection(self) -> None:
        """Save collection to file"""
        data = {"images": self.collection}
        self.storage_file.write_text(json.dumps(data, indent=2))

    def fetch_random_dog(self) -> str | None:
        """Fetch random dog image URL from API"""
        # TODO: Implement this method
        # - Make GET request to API
        # - Handle errors (network, timeout, etc.)
        # - Return image URL or None if failed
        pass

    def add_to_collection(self) -> None:
        """Fetch and add a new dog to collection"""
        # TODO: Implement this method
        # - Fetch random dog
        # - Add to collection
        # - Save to file
        pass

    def show_collection(self) -> None:
        """Display saved collection"""
        # TODO: Implement this method
        # - Show all saved dog URLs
        # - Show count
        pass

    def clear_collection(self) -> None:
        """Clear all saved dogs"""
        # TODO: Implement this method
        pass

def main():
    gallery = DogGallery()

    print("🐕 Dog Gallery")
    print("="*50)
    # TODO: Implement menu interface
    # - Show options (add dog, view collection, clear, quit)
    # - Handle user input
    # - Call appropriate methods

if __name__ == "__main__":
    main()

Expected Features / Oczekiwane funkcje

  • Fetch random dog images

    Pobieranie losowych zdjęć psów

  • Save URLs to JSON file

    Zapisywanie URL-i do pliku JSON

  • Load saved collection on startup

    Wczytywanie zapisanej kolekcji przy starcie

  • Show collection with count

    Pokazywanie kolekcji z licznikiem

  • Handle network errors

    Obsługa błędów sieciowych

  • User-friendly menu interface

    Przyjazny interfejs menu


Project Option 2: Pokemon Explorer / Opcja 2: Eksplorator Pokemon

API: PokeAPI

Free API with detailed Pokemon data.

Darmowe API ze szczegółowymi danymi o Pokemon.

Requirements / Wymagania

Build a Pokemon information tool that:

Zbuduj narzędzie informacyjne o Pokemon, które:

  1. Searches Pokemon by name

    Wyszukuje Pokemon po nazwie

  2. Displays stats (HP, Attack, Defense, etc.)

    Wyświetla statystyki (HP, Atak, Obrona, itp.)

  3. Saves favorite Pokemon to JSON

    Zapisuje ulubione Pokemon do JSON

  4. Compares two Pokemon stats

    Porównuje statystyki dwóch Pokemon

API Endpoints / Endpointy API

# Get Pokemon by name / Pobierz Pokemon po nazwie
f"https://pokeapi.co/api/v2/pokemon/{name}"

# List first 151 Pokemon / Lista pierwszych 151 Pokemon
"https://pokeapi.co/api/v2/pokemon?limit=151"

Starter Code / Kod startowy

Create pokemon_explorer.py:

Utwórz pokemon_explorer.py:

import requests
import json
from pathlib import Path
from typing import Dict, List, Any

class PokemonExplorer:
    API_URL = "https://pokeapi.co/api/v2"

    def __init__(self, favorites_file: str = "favorites.json"):
        self.favorites_file = Path(favorites_file)
        self.favorites: List[Dict[str, Any]] = self._load_favorites()

    def _load_favorites(self) -> List[Dict[str, Any]]:
        """Load favorites from file"""
        # TODO: Implement loading
        pass

    def _save_favorites(self) -> None:
        """Save favorites to file"""
        # TODO: Implement saving
        pass

    def get_pokemon(self, name: str) -> Dict[str, Any] | None:
        """Fetch Pokemon data by name"""
        # TODO: Implement API call
        # - Handle errors
        # - Return pokemon data
        pass

    def display_pokemon(self, pokemon: Dict[str, Any]) -> None:
        """Display Pokemon information"""
        # TODO: Show name, types, stats
        pass

    def add_favorite(self, pokemon_name: str) -> None:
        """Add Pokemon to favorites"""
        # TODO: Fetch pokemon, add to favorites, save
        pass

    def show_favorites(self) -> None:
        """Display all favorite Pokemon"""
        # TODO: Show saved favorites
        pass

def main():
    explorer = PokemonExplorer()

    print("⚡ Pokemon Explorer")
    print("="*50)
    # TODO: Implement menu
    # - Search Pokemon
    # - Add to favorites
    # - View favorites
    # - Compare two Pokemon

if __name__ == "__main__":
    main()

Expected Features / Oczekiwane funkcje

  • Search Pokemon by name (lowercase)

    Wyszukiwanie Pokemon po nazwie (małe litery)

  • Display stats and types

    Wyświetlanie statystyk i typów

  • Save favorites to JSON

    Zapisywanie ulubionych do JSON

  • Load favorites on startup

    Wczytywanie ulubionych przy starcie

  • Handle Pokemon not found (404)

    Obsługa Pokemon nie znalezionego (404)


Project Option 3: Daily Advice App / Opcja 3: Aplikacja Dziennych Rad

API: Advice Slip API

Free API delivering random advice.

Darmowe API dostarczające losowe rady.

Requirements / Wymagania

Build a daily advice application that:

Zbuduj aplikację dziennych rad, która:

  1. Fetches random advice

    Pobiera losowe rady

  2. Saves advice history to CSV

    Zapisuje historię rad do CSV

  3. Searches advice by keyword

    Wyszukuje rady po słowie kluczowym

  4. Shows statistics (total saved, etc.)

    Pokazuje statystyki (łącznie zapisanych, itp.)

API Endpoints / Endpointy API

# Random advice / Losowa rada
"https://api.adviceslip.com/advice"

# Search advice / Szukaj rad
f"https://api.adviceslip.com/advice/search/{query}"

Starter Code / Kod startowy

Create advice_app.py:

Utwórz advice_app.py:

import requests
import csv
from datetime import datetime
from pathlib import Path
from typing import List, Dict, Any

class AdviceApp:
    API_URL = "https://api.adviceslip.com"

    def __init__(self, history_file: str = "advice_history.csv"):
        self.history_file = Path(history_file)
        self._init_csv()

    def _init_csv(self) -> None:
        """Initialize CSV file with headers"""
        if not self.history_file.exists():
            with open(self.history_file, "w", newline="") as f:
                writer = csv.writer(f)
                writer.writerow(["Date", "Time", "Advice"])

    def fetch_random_advice(self) -> str | None:
        """Fetch random advice from API"""
        # TODO: Implement API call
        pass

    def save_advice(self, advice: str) -> None:
        """Save advice to CSV with timestamp"""
        # TODO: Append to CSV with date and time
        pass

    def show_history(self) -> None:
        """Display all saved advice"""
        # TODO: Read CSV and display
        pass

    def search_advice(self, query: str) -> List[Dict[str, Any]]:
        """Search advice by keyword"""
        # TODO: Use search endpoint
        pass

    def get_stats(self) -> Dict[str, int]:
        """Get statistics about saved advice"""
        # TODO: Count lines in CSV
        pass

def main():
    app = AdviceApp()

    print("💡 Daily Advice App")
    print("="*50)
    # TODO: Implement menu
    # - Get random advice
    # - Search advice
    # - View history
    # - Show stats

if __name__ == "__main__":
    main()

Expected Features / Oczekiwane funkcje

  • Fetch and display random advice

    Pobieranie i wyświetlanie losowych rad

  • Save advice to CSV with timestamp

    Zapisywanie rad do CSV z datą

  • Load and display history

    Wczytywanie i wyświetlanie historii

  • Search advice by keyword

    Wyszukiwanie rad po słowie kluczowym

  • Show statistics

    Pokazywanie statystyk


Project Requirements (All Projects) / Wymagania projektu (wszystkie projekty)

All projects should include:

Wszystkie projekty powinny zawierać:

1. Error Handling / Obsługa błędów

  • Handle network errors (ConnectionError, Timeout)

    Obsługa błędów sieciowych (ConnectionError, Timeout)

  • Handle HTTP errors (404, 500)

    Obsługa błędów HTTP (404, 500)

  • Handle file errors (permission, not found)

    Obsługa błędów plików (uprawnienia, nie znaleziono)

2. File Operations / Operacje na plikach

  • Save data to JSON or CSV

    Zapisywanie danych do JSON lub CSV

  • Load data on startup

    Wczytywanie danych przy starcie

  • Handle file corruption

    Obsługa uszkodzonych plików

3. Code Quality / Jakość kodu

  • Use type hints

    Używanie type hints

  • Split code into functions/methods

    Dzielenie kodu na funkcje/metody

  • Add docstrings

    Dodawanie docstringów

  • Follow naming conventions

    Stosowanie konwencji nazewnictwa

4. User Interface / Interfejs użytkownika

  • Clear menu options

    Jasne opcje menu

  • Input validation

    Walidacja wejścia

  • Helpful error messages

    Pomocne komunikaty błędów


Testing Your Project / Testowanie projektu

After implementation, test these scenarios:

Po implementacji, przetestuj te scenariusze:

  1. Normal operation — does it work as expected?

    Normalna operacja — czy działa zgodnie z oczekiwaniami?

  2. Network failure — unplug internet, does it handle gracefully?

    Awaria sieci — odłącz internet, czy radzi sobie elegancko?

  3. Invalid input — enter wrong data, does it validate?

    Nieprawidłowe wejście — wpisz złe dane, czy waliduje?

  4. File corruption — edit saved file with garbage, does it recover?

    Uszkodzony plik — edytuj zapisany plik ze śmieciami, czy się odzyska?

  5. Empty state — start fresh, does it handle no saved data?

    Pusty stan — zacznij od zera, czy radzi sobie bez zapisanych danych?


Code Quality Check / Sprawdzenie jakości kodu

Before submitting, run quality tools:

Przed wysłaniem, uruchom narzędzia jakości:

# Format code / Formatuj kod
uv run ruff format your_project.py

# Check for issues / Sprawdź problemy
uv run ruff check your_project.py

# Verify types / Zweryfikuj typy
uv run mypy your_project.py

Fix any issues found.

Napraw znalezione problemy.


Submission / Oddanie

Save your work to Git:

Zapisz pracę w Git:

git add your_project.py
git commit -m "Complete mini-project: [project name]"
git push

Podsumowanie / Summary

After completing the mini-project you can:

Po ukończeniu mini-projektu potrafisz:

  • integrate multiple Phase 2 skills into one application

    integrować wiele umiejętności z Fazy 2 w jedną aplikację

  • work with real-world free APIs

    pracować z prawdziwymi darmowymi API

  • handle errors gracefully in production-like code

    obsługiwać błędy elegancko w kodzie podobnym do produkcyjnego

  • structure a complete Python program

    strukturyzować kompletny program Pythona

  • save and load persistent data

    zapisywać i wczytywać trwałe dane

  • create user-friendly command-line interfaces

    tworzyć przyjazne interfejsy wiersza poleceń


Congratulations on completing Phase 2!

Gratulacje ukończenia Fazy 2!

You've learned to work with files, handle errors, use modules, connect to APIs, and maintain code quality.

Nauczyłeś się pracować z plikami, obsługiwać błędy, używać modułów, łączyć się z API i utrzymywać jakość kodu.

What's next?

Co dalej?

Phase 3 will cover more advanced topics like async programming, testing strategies, and database integration.

Faza 3 obejmie bardziej zaawansowane tematy jak programowanie asynchroniczne, strategie testowania i integracja z bazami danych.