testClient.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import json
  2. import requests
  3. from typing import Dict, Any
  4. import os
  5. def load_json_file(file_path: str) -> Dict[str, Any]:
  6. """从JSON文件加载数据"""
  7. if not os.path.exists(file_path):
  8. raise FileNotFoundError(f"文件不存在: {file_path}")
  9. with open(file_path, 'r', encoding='utf-8') as f:
  10. try:
  11. return json.load(f)
  12. except json.JSONDecodeError as e:
  13. raise ValueError(f"JSON解析错误: {str(e)}")
  14. def send_to_server(api_url: str, payload: Dict[str, Any]) -> None:
  15. """发送数据到服务器并处理响应"""
  16. headers = {'Content-Type': 'application/json'}
  17. try:
  18. response = requests.post(
  19. api_url,
  20. json=payload,
  21. headers=headers,
  22. timeout=10
  23. )
  24. # 解析响应
  25. resp_data = response.json()
  26. print("\n服务器响应:")
  27. print(f"状态码: {response.status_code}")
  28. print(f"响应内容: {resp_data}")
  29. # 检查响应格式
  30. if not isinstance(resp_data, dict) or 'status' not in resp_data or 'msg' not in resp_data:
  31. print("警告: 服务器返回了非标准响应格式")
  32. if response.status_code == 200 and resp_data.get('status') == 200:
  33. print("请求处理成功!")
  34. else:
  35. print("请求处理失败!")
  36. except requests.exceptions.RequestException as e:
  37. print(f"\n请求失败: {str(e)}")
  38. if hasattr(e, 'response') and e.response is not None:
  39. print(f"错误响应: {e.response.text}")
  40. def main():
  41. # 配置参数
  42. config = {
  43. "server_url": "http://127.0.0.1:8081/process_brdf/",
  44. "json_file": "test_data.json"
  45. }
  46. print("=== BRDF 测试客户端 ===")
  47. print(f"服务器地址: {config['server_url']}")
  48. print(f"测试数据文件: {config['json_file']}")
  49. try:
  50. # 1. 加载测试数据
  51. print("\n正在加载测试数据...")
  52. payload = load_json_file(config['json_file'])
  53. print("测试数据加载成功!")
  54. print(json.dumps(payload, indent=2, ensure_ascii=False))
  55. # 2. 发送到服务器
  56. print("\n正在发送数据到服务器...")
  57. send_to_server(config['server_url'], payload)
  58. except Exception as e:
  59. print(f"\n发生错误: {str(e)}")
  60. if __name__ == "__main__":
  61. main()