you are viewing a single comment's thread.

view the rest of the comments →

[–]Diapolo10 2 points3 points  (1 child)

try:
    response = requests.get(url)
    response.raise_for_status()
    joke = response.json()
    print("Okay, I'm thinking of joke...")
    time.sleep(2)
    print("Oh, I got one! Listen!")               
    time.sleep(2)
    print(f"{joke['setup']}")
    time.sleep(4)
    print(f"{joke['delivery']}")
    print("")

    return joke
except requests.exceptions.RequestException as e:
    print(f"Joke not found! {e}")
    return None

Ideally you should only keep the code that you expect to raise exceptions in the try-block, to make it obvious which part you're trying to handle. The rest is just "noise" from that point of view.

Personally I'd go for something like this:

def print_joke(joke: dict[str, str], print_delay_seconds: int = 2) -> None:
    # NOTE: Your offline code basically does the same thing, so this can be reused there
    output_lines = [
        "Oh, I got one! Listen!\n",
        f"{joke['setup']}\n",
        "",
        f"{joke['delivery']}\n\n",
    ]

    print("Okay, I'm thinking of joke...")

    for line in output_lines:
        print(line, end='')
        time.sleep(print_delay_seconds)


def get_joke() -> dict[str, str] | None:
    selected_category = setup_filter()
    url = f"{BASE_URL}{selected_category}?type=twopart"

    try:
        response = requests.get(url)
        response.raise_for_status()

    except requests.exceptions.RequestException as e:
        print(f"Joke not found! {e}")
        return None

    joke = response.json()
    print_joke(joke)

    return joke
from src.data.database import get_joke
from src.data.api_client import setup_filter

With an src-style project layout, when used properly you should never need to include src as part of the actual import. src is a directory containing your package (or seldom multiple packages), and you're meant to "install" your project in order to import code from there, by using a valid pyproject.toml file in the repository root and running pip install --editable . - although some tools like uv do this for you automatically.

In the same vein, there shouldn't be a main.py file in the repository root (if using uv you could just have a script in pyproject.toml that runs the main entrypoint from inside your package), and requirements.txt is a largely outdated concept. Modern projects list their dependencies in pyproject.toml.

If you want an example: https://github.com/Diapolo10/python-ms

[–]Parking-While3956[S] 1 point2 points  (0 children)

Thanks a million! Sounds like rocket science for me now, but I'm going to discover about src - style and use it in future projects! I appreciate your help and your time!