API测试_v2.py 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import time
  2. import requests
  3. import os
  4. # --- 配置 ---
  5. # 请确保你的 FastAPI 服务器正在运行,并修改此处的地址和端口
  6. BASE_URL = "http://127.0.0.1:7745/api" # 假设您的API前缀是 /api, 如果不是,请修改
  7. STITCH_API_PREFIX = "/stitch"
  8. SINGLE_FOLDER_URL = f"{BASE_URL}{STITCH_API_PREFIX}/folder"
  9. # 用于存放自动生成的测试图片的临时目录
  10. TEST_DATA_DIR = "temp_api_test_data"
  11. # --- 测试函数 1:新的单个拼图接口 (从文件夹上传) ---
  12. def single_puzzle_from_folder_api(image_folder_path: str):
  13. """
  14. 测试 /stitch/from-folder 接口 (单个拼图)
  15. """
  16. print(f"--- 1. 开始测试: 单个拼图接口 (从文件夹上传) ---")
  17. print(f"使用文件夹: {image_folder_path}")
  18. # 1. 准备请求数据
  19. # 从文件夹路径推断输出文件名
  20. output_filename_base = os.path.basename(image_folder_path)
  21. form_data = {
  22. 'output_filename_base': output_filename_base,
  23. 'method': 'template_match',
  24. 'num_cols': 4,
  25. 'num_rows': 6,
  26. 'overlap_h': 405,
  27. 'overlap_v': 440,
  28. 'tm_blend_type': 'half_importance_add_weight',
  29. 'tm_light_compensation': True,
  30. }
  31. # 2. 准备要上传的文件列表
  32. # 'files' 是 FastAPI 接口中定义的参数名
  33. # requests 要求格式为: [('field_name', ('filename', file_object, 'content_type')), ...]
  34. files_to_send = []
  35. file_objects = []
  36. try:
  37. for filename in os.listdir(image_folder_path):
  38. if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
  39. file_path = os.path.join(image_folder_path, filename)
  40. f = open(file_path, 'rb')
  41. file_objects.append(f)
  42. files_to_send.append(('files', (filename, f, 'image/jpeg')))
  43. if not files_to_send:
  44. print("❌ 错误: 在文件夹中未找到可上传的图片。")
  45. return
  46. # 3. 发送 POST 请求
  47. print(f"向服务器 {SINGLE_FOLDER_URL} 发送 {len(files_to_send)} 个文件...")
  48. response = requests.post(SINGLE_FOLDER_URL, data=form_data, files=files_to_send, timeout=60)
  49. # 4. 处理响应
  50. print(f"服务器响应状态码: {response.status_code}")
  51. if response.status_code == 200:
  52. content_type = response.headers.get('content-type')
  53. print(f"响应内容类型: {content_type}")
  54. if 'image/jpeg' in content_type:
  55. output_filename = f"stitched_single_{output_filename_base}.jpg"
  56. with open(output_filename, "wb") as f:
  57. f.write(response.content)
  58. print(f"✅ 成功! 拼接后的大图已保存为: {output_filename}")
  59. else:
  60. print(f"❌ 失败! 期望得到 'image/jpeg',但收到了 '{content_type}'")
  61. else:
  62. print(f"❌ 请求失败! 错误信息: {response.text}")
  63. except requests.exceptions.RequestException as e:
  64. print(f"❌ 请求异常! 无法连接到服务器: {e}")
  65. finally:
  66. # 确保所有打开的文件都被关闭
  67. for f in file_objects:
  68. f.close()
  69. print("-" * 50 + "\n")
  70. if __name__ == "__main__":
  71. t1 = time.time()
  72. single_puzzle_from_folder_api(r"C:\Code\ML\Project\StitchImageServer\temp\Input\_250801_1043_0001")
  73. t2 = time.time()
  74. print("cost: ", t2 - t1)