Spaces:
Sleeping
Sleeping
feat(es): add Spanish coding exercises (Tier 1-3)
Browse files
languages/es/exercises/tier2/frase_del_dia.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Tier 2 - Ejercicio 2: Cliente API Simple / Simple API Client
|
| 2 |
+
# Dificultad: ⭐⭐⭐ | Tiempo estimado: 25 min
|
| 3 |
+
# Ejecutar: legesher run languages/es/exercises/tier2/frase_del_dia.py --lang es
|
| 4 |
+
|
| 5 |
+
importar socket
|
| 6 |
+
importar json
|
| 7 |
+
|
| 8 |
+
definir obtener_frase():
|
| 9 |
+
"""Obtiene la frase del día desde la API y la imprime."""
|
| 10 |
+
anfitrion = "frasedeldia.azurewebsites.net"
|
| 11 |
+
peticion = "GET /api/phrase HTTP/1.1\r\nHost: frasedeldia.azurewebsites.net\r\nConnection: close\r\n\r\n"
|
| 12 |
+
|
| 13 |
+
probar:
|
| 14 |
+
conexion = socket.create_connection((anfitrion, 80))
|
| 15 |
+
conexion.send(peticion.encode())
|
| 16 |
+
respuesta = b""
|
| 17 |
+
mientras verdadero:
|
| 18 |
+
fragmento = conexion.recv(4096)
|
| 19 |
+
si no fragmento:
|
| 20 |
+
romper
|
| 21 |
+
respuesta += fragmento
|
| 22 |
+
conexion.close()
|
| 23 |
+
|
| 24 |
+
texto = respuesta.decode("utf-8", errors="ignore")
|
| 25 |
+
inicio = texto.find("{")
|
| 26 |
+
fin = texto.rfind("}") + 1
|
| 27 |
+
json_texto = texto[inicio:fin]
|
| 28 |
+
datos = json.loads(json_texto)
|
| 29 |
+
imprimir(f"Frase: {datos['phrase']}")
|
| 30 |
+
imprimir(f"Autor: {datos['author']}")
|
| 31 |
+
excepto Exception como error:
|
| 32 |
+
imprimir(f"Error: {error}")
|
| 33 |
+
|
| 34 |
+
si __name__ == "__main__":
|
| 35 |
+
obtener_frase()
|