add web-service

This commit is contained in:
2025-10-20 23:07:10 +05:00
parent a74b8bbb5d
commit 4f9417a032
10 changed files with 1266 additions and 282 deletions

134
example-client.py Executable file
View File

@@ -0,0 +1,134 @@
#!/usr/bin/env python3
"""
Пример клиента для работы с Racing A* Web Service API
"""
import requests
import json
import sys
import os
def solve_map(api_url, map_file):
"""Решает карту, отправляя её на сервер"""
print(f"📂 Загрузка карты из {map_file}...")
if not os.path.exists(map_file):
print(f"❌ Файл {map_file} не найден!")
return None
# Читаем карту
with open(map_file, 'r') as f:
map_data = json.load(f)
print(f"📡 Отправка запроса на {api_url}/solve...")
try:
# Отправляем запрос
response = requests.post(
f'{api_url}/solve',
json=map_data,
headers={'Content-Type': 'application/json'}
)
result = response.json()
if result['success']:
stats = result['statistics']
print(f"\n✅ Решение найдено!")
print(f" Шагов: {stats['steps']}")
print(f" Чекпоинтов: {stats['checkpoints']}")
print(f" Время: {stats['computeTimeSeconds']:.2f}s")
print(f" Макс. скорость: {stats['maxSpeed']}")
print(f" Итераций: {stats['iterations']}")
return result['solution']
else:
print(f"\n❌ Ошибка: {result['error']}")
return None
except requests.exceptions.ConnectionError:
print(f"\nНе удалось подключиться к серверу {api_url}")
print(" Убедитесь, что сервер запущен: ./run-webservice.sh")
return None
except Exception as e:
print(f"\n❌ Ошибка: {e}")
return None
def save_solution(solution, output_file):
"""Сохраняет решение в файл"""
if solution is None:
return
solution_data = {"solution": solution}
with open(output_file, 'w') as f:
json.dump(solution_data, f, indent=2)
print(f"\n💾 Решение сохранено в {output_file}")
def check_health(api_url):
"""Проверяет состояние сервера"""
try:
response = requests.get(f'{api_url}/health')
health = response.json()
print(f"🏥 Health Check:")
print(f" Status: {health['status']}")
print(f" Version: {health['version']}")
print(f" Timestamp: {health['timestamp']}")
return health['status'] == 'healthy'
except:
return False
def main():
"""Главная функция"""
api_url = os.getenv('API_URL', 'http://localhost:5000')
print("╔════════════════════════════════════════════════════════════╗")
print("║ Racing A* Solver - Python Client Example ║")
print("╚════════════════════════════════════════════════════════════╝\n")
# Проверяем аргументы
if len(sys.argv) < 2:
print("Использование:")
print(f" {sys.argv[0]} <map-file.json> [output-file.json]")
print(f"\nПример:")
print(f" {sys.argv[0]} maps/simple-test.json solution.json")
sys.exit(1)
map_file = sys.argv[1]
output_file = sys.argv[2] if len(sys.argv) > 2 else 'solution.json'
print(f"🌐 API URL: {api_url}\n")
# Проверяем здоровье сервера
if not check_health(api_url):
print("\n❌ Сервер недоступен!")
sys.exit(1)
print()
# Решаем карту
solution = solve_map(api_url, map_file)
# Сохраняем решение
if solution:
save_solution(solution, output_file)
print("\n✅ Готово!")
else:
print("\nНе удалось получить решение")
sys.exit(1)
if __name__ == '__main__':
main()