API测试.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import requests
  2. import os
  3. import io
  4. import zipfile
  5. from PIL import Image, ImageDraw
  6. # --- 配置 ---
  7. # 请确保你的 FastAPI 服务器正在运行,并修改此处的地址和端口
  8. BASE_URL = "http://127.0.0.1:7745/api"
  9. SINGLE_STITCH_URL = f"{BASE_URL}/stitch"
  10. # --- 测试函数 1:单个拼图接口 ---
  11. def single_puzzle_api(zipfile_path):
  12. """
  13. 测试 /stitch/ 接口 (单个拼图)
  14. 使用 模板匹配法 (template_match)
  15. """
  16. print("--- 1. 开始测试: 单个拼图接口 (/stitch) ---")
  17. # 1. 准备请求数据
  18. form_data = {
  19. 'method': 'template_match',
  20. 'num_cols': 4,
  21. 'num_rows': 6,
  22. 'overlap_h': 405,
  23. 'overlap_v': 440,
  24. 'tm_blend_type': 'half_importance_add_weight',
  25. 'tm_light_compensation': True,
  26. }
  27. try:
  28. # 打开文件
  29. with open(zipfile_path, "rb") as f:
  30. files = {
  31. 'zip_file': (os.path.basename(zipfile_path), f, 'application/zip')
  32. }
  33. # 4. 发送 POST 请求
  34. print("向服务器发送请求...")
  35. response = requests.post(SINGLE_STITCH_URL, data=form_data, files=files) # 设置较长超时
  36. # 5. 处理响应
  37. print(f"服务器响应状态码: {response.status_code}")
  38. if response.status_code == 200:
  39. # 检查响应头,确认是图片
  40. content_type = response.headers.get('content-type')
  41. print(f"响应内容类型: {content_type}")
  42. if 'image/jpeg' in content_type:
  43. # 将返回的图片内容保存到本地文件
  44. output_filename = "stitched_single_result.jpg"
  45. with open(output_filename, "wb") as f:
  46. f.write(response.content)
  47. print(f"✅ 成功! 拼接后的大图已保存为: {output_filename}")
  48. else:
  49. print(f"❌ 失败! 期望得到 'image/jpeg',但收到了 '{content_type}'")
  50. else:
  51. # 如果接口返回错误,打印错误详情
  52. print(f"❌ 请求失败! 错误信息: {response.text}")
  53. except requests.exceptions.RequestException as e:
  54. print(f"❌ 请求异常! 无法连接到服务器: {e}")
  55. print("-" * 40 + "\n")
  56. # --- 测试函数 2:批量拼图接口 ---
  57. if __name__ == "__main__":
  58. # 依次运行两个测试函数
  59. single_puzzle_api(r"C:\Code\ML\Project\StitchImageServer\temp\Input\front_0_1.zip")