-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathU4-Ejercicio-3.py
More file actions
149 lines (125 loc) · 5.39 KB
/
U4-Ejercicio-3.py
File metadata and controls
149 lines (125 loc) · 5.39 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
"""
Usa la API de OpenWeatherMap (o similar) para:
- Obtener el clima actual de una ciudad
- Mostrar temperatura, humedad, descripción
- Guardar el historial en un archivo JSON
"""
import requests
import json
from datetime import datetime
class ClienteClima:
def __init__(self, archivo_historial="historial_clima.json"):
self.archivo_historial = archivo_historial
self.base_url = "http://api.openweathermap.org/data/2.5/weather"
# NOTA: En producción, usar una API key real
self.api_key = "tu_api_key_aqui" # Necesitas registrarte en openweathermap.org
def obtener_clima(self, ciudad):
"""Obtiene el clima actual de una ciudad"""
try:
# Para demo, usamos datos simulados
if ciudad.lower() == "quito":
datos_simulados = {
"name": "Quito",
"main": {"temp": 285.15, "humidity": 65}, # 12°C
"weather": [{"description": "cielo claro"}],
"cod": 200
}
return datos_simulados
else:
# Código real para usar la API (necesita API key)
params = {
'q': ciudad,
'appid': self.api_key,
'units': 'metric',
'lang': 'es'
}
respuesta = requests.get(self.base_url, params=params)
return respuesta.json()
except Exception as e:
print(f"Error al obtener datos: {e}")
return None
def mostrar_clima(self, ciudad):
"""Muestra la información del clima de forma legible"""
datos = self.obtener_clima(ciudad)
if datos and datos.get('cod') == 200:
temperatura = datos['main']['temp']
humedad = datos['main']['humidity']
descripcion = datos['weather'][0]['description']
nombre_ciudad = datos['name']
print(f"\n🌤️ CLIMA EN {nombre_ciudad.upper()}")
print(f"📍 Ciudad: {nombre_ciudad}")
print(f"🌡️ Temperatura: {temperatura}°C")
print(f"💧 Humedad: {humedad}%")
print(f"☁️ Condición: {descripcion.title()}")
# Guardar en historial
self.guardar_historial(ciudad, datos)
else:
print(f"❌ No se pudo obtener el clima para {ciudad}")
print("💡 Consejo: Verifica el nombre de la ciudad o tu conexión a internet")
def guardar_historial(self, ciudad, datos):
"""Guarda la consulta en el archivo de historial"""
registro = {
'ciudad': ciudad,
'fecha': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
'temperatura': datos['main']['temp'],
'humedad': datos['main']['humidity'],
'descripcion': datos['weather'][0]['description']
}
try:
# Cargar historial existente
try:
with open(self.archivo_historial, 'r') as f:
historial = json.load(f)
except FileNotFoundError:
historial = []
# Agregar nuevo registro
historial.append(registro)
# Guardar
with open(self.archivo_historial, 'w') as f:
json.dump(historial, f, indent=2, ensure_ascii=False)
print("📝 Registro guardado en historial")
except Exception as e:
print(f"Error guardando historial: {e}")
def mostrar_historial(self):
"""Muestra el historial de consultas"""
try:
with open(self.archivo_historial, 'r') as f:
historial = json.load(f)
print("\n📊 HISTORIAL DE CONSULTAS")
print("=" * 50)
for registro in historial[-5:]: # Últimas 5 consultas
print(f"🏙️ Ciudad: {registro['ciudad']}")
print(f"📅 Fecha: {registro['fecha']}")
print(f"🌡️ Temp: {registro['temperatura']}°C")
print(f"💧 Humedad: {registro['humedad']}%")
print(f"☁️ Clima: {registro['descripcion']}")
print("-" * 30)
except FileNotFoundError:
print("📂 No hay historial de consultas")
except Exception as e:
print(f"Error leyendo historial: {e}")
def menu(self):
"""Menú interactivo del cliente de clima"""
while True:
print("\n" + "="*40)
print("🌤️ CLIENTE DE API DEL CLIMA")
print("="*40)
print("1. Consultar clima de una ciudad")
print("2. Ver historial")
print("3. Salir")
opcion = input("Selecciona una opción: ")
if opcion == '1':
ciudad = input("Ingresa el nombre de la ciudad: ")
self.mostrar_clima(ciudad)
elif opcion == '2':
self.mostrar_historial()
elif opcion == '3':
print("👋 ¡Hasta luego!")
break
else:
print("❌ Opción no válida")
# Ejecutar el cliente de clima
cliente = ClienteClima()
# Para probar sin menú:
print("🌤️ DEMO CLIENTE DE CLIMA")
cliente.mostrar_clima("quito")