This repository was archived by the owner on Apr 28, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcli_tool.py
More file actions
176 lines (140 loc) · 4.97 KB
/
cli_tool.py
File metadata and controls
176 lines (140 loc) · 4.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
#!/usr/bin/env python3
"""Interactive CLI client for the Ticket Booking API.
This script communicates with the API exclusively over HTTP.
It MUST NOT import anything from the app package.
"""
from __future__ import annotations
import argparse
import os
import sys
from typing import Any
import requests
DEFAULT_BASE_URL = "http://localhost:5000"
MENU = """
========================================
Ticket Booking CLI Client
========================================
1. Check API Health
2. List Events
3. List Tickets
4. Book a Ticket
0. Exit
========================================
"""
def _url(base: str, path: str) -> str:
"""Build a full URL from base and path."""
return f"{base.rstrip('/')}{path}"
def _print_table(headers: list[str], rows: list[list[str]]) -> None:
"""Print a simple aligned text table."""
if not rows:
print(" (no data)")
return
widths = [len(h) for h in headers]
for row in rows:
for i, cell in enumerate(row):
widths[i] = max(widths[i], len(cell))
fmt = " ".join(f"{{:<{w}}}" for w in widths)
print(fmt.format(*headers))
print(fmt.format(*["-" * w for w in widths]))
for row in rows:
print(fmt.format(*row))
def check_health(base_url: str) -> None:
"""Check API health endpoint."""
try:
resp = requests.get(_url(base_url, "/api/health"), timeout=5)
resp.raise_for_status()
data: dict[str, Any] = resp.json()
except requests.RequestException as exc:
print(f" Error : failed to check API health: {exc}")
return
except ValueError:
print(" Error : health endpoint returned a non-JSON response")
return
print(f" Status : {data.get('status', 'unknown')}")
print(f" Message: {data.get('message', '')}")
def list_events(base_url: str) -> None:
"""List all events."""
resp = requests.get(_url(base_url, "/api/events"), timeout=5)
resp.raise_for_status()
events: list[dict[str, Any]] = resp.json()
rows = [
[str(e["id"]), e["name"], e["date"], e.get("description", "")] for e in events
]
_print_table(["ID", "Name", "Date", "Description"], rows)
def list_tickets(base_url: str) -> None:
"""List all tickets."""
resp = requests.get(_url(base_url, "/api/tickets"), timeout=5)
resp.raise_for_status()
tickets: list[dict[str, Any]] = resp.json()
rows = [[str(t["id"]), str(t["event_id"]), t.get("details", "")] for t in tickets]
_print_table(["ID", "Event ID", "Details"], rows)
def book_ticket(base_url: str) -> None:
"""Attempt to book a ticket by prompting for ticket ID and quantity."""
try:
ticket_id_str = input(" Enter Ticket ID: ").strip()
ticket_id = int(ticket_id_str)
except (ValueError, EOFError):
print(" Invalid ticket ID.")
return
try:
quantity_str = input(" Enter Quantity [1]: ").strip() or "1"
quantity = int(quantity_str)
except (ValueError, EOFError):
print(" Invalid quantity.")
return
resp = requests.post(
_url(base_url, f"/api/tickets/{ticket_id}/reserve"),
json={"quantity": quantity},
timeout=5,
)
try:
data: Any = resp.json()
except ValueError:
data = resp.text
if resp.ok:
print(f" Booking successful: {data}")
else:
error_message = data.get("error", data) if isinstance(data, dict) else data
print(f" Booking failed ({resp.status_code}): {error_message}")
def main() -> None:
"""Run the interactive CLI client."""
parser = argparse.ArgumentParser(description="Ticket Booking CLI Client")
parser.add_argument(
"--base-url",
default=os.getenv("API_BASE_URL", DEFAULT_BASE_URL),
help=f"Base URL of the API (default: {DEFAULT_BASE_URL})",
)
args = parser.parse_args()
base_url: str = args.base_url
print(f"\n Connecting to API at: {base_url}")
actions: dict[str, tuple[str, Any]] = {
"1": ("Check API Health", lambda: check_health(base_url)),
"2": ("List Events", lambda: list_events(base_url)),
"3": ("List Tickets", lambda: list_tickets(base_url)),
"4": ("Book a Ticket", lambda: book_ticket(base_url)),
}
while True:
print(MENU)
try:
choice = input("Select an option: ").strip()
except (EOFError, KeyboardInterrupt):
print("\n Goodbye!")
sys.exit(0)
if choice == "0":
print(" Goodbye!")
break
action = actions.get(choice)
if action is None:
print(" Invalid option. Try again.")
continue
label, func = action
print(f"\n --- {label} ---")
try:
func()
except requests.ConnectionError:
print(f" Cannot connect to API at {base_url}")
print(" Is the server running?")
except requests.RequestException as exc:
print(f" Request error: {exc}")
if __name__ == "__main__":
main()