当前位置: 首页 > news >正文

算法模型部署后_python脚本API测试指南-记录3

API 测试指南

服务运行后,可以通过以下方式测试:

Curl:

curl -X POST -F "file=@./test_dataset/surface/surface57.png" http://<服务器IP>:9000/api/v1/predict

Python 脚本: (参考 svm_request测试.py)

import requestsurl = 'http://<服务器IP>:9000/api/v1/predict'
file_path = './test_dataset/surface/surface57.png' # 使用实际路径try:with open(file_path, 'rb') as f:files = {'file': f}response = requests.post(url, files=files)response.raise_for_status() # 检查请求是否成功print(response.json())
except FileNotFoundError:print(f"Error: File not found at {file_path}")
except requests.exceptions.RequestException as e:print(f"Error during request: {e}")

使用 Python 脚本 (通过命令行参数传递图像路径):

您还可以使用项目提供的 svm_request_dynamic.pysvm_request_simplified.py 脚本来测试 API。这些脚本允许您通过命令行参数直接指定图像文件的路径。

  1. 使用 svm_request_dynamic.py (输出详细JSON):
    此脚本会发送图像到 API 并打印完整的 JSON 响应。

    python svm_request_dynamic.py <你的图像路径>
    

    例如:

    python svm_request_dynamic.py ./test_dataset/corona/corona111.png
    

    或者使用绝对路径:

    python svm_request_dynamic.py /path/to/your/image.png
    

测试效果:
在这里插入图片描述

  1. 使用 svm_request_simplified.py (输出简化结果):
    此脚本会发送图像到 API 并仅打印预测的类别和置信度。

    python svm_request_simplified.py <你的图像路径>
    

    例如:

    python svm_request_simplified.py ./test_dataset/surface/surface57.png
    

    或者使用绝对路径:

    python svm_request_simplified.py /path/to/your/other_image.jpg
    

测试效果:
在这里插入图片描述

注意:

  • 请将 <你的图像路径> 替换为实际的图像文件路径。
  • 确保 API 服务 (svm_fastapi.py) 正在运行。
  • 如果脚本与 API 服务不在同一台机器上,请修改脚本中的 url 变量,将其中的 127.0.0.1localhost 替换为 API 服务器的实际 IP 地址。

完整代码如下:
svm_request_dynamic.py

import requests
import os
import sysurl = 'http://127.0.0.1:9000/api/v1/predict'  # 替换为实际的API地址def send_request(image_path):if not os.path.isabs(image_path):# 如果不是绝对路径,则假定它是相对于当前工作目录的路径file_path = os.path.abspath(image_path) # 获取绝对路径else:file_path = image_pathtry:with open(file_path, 'rb') as f:files = {'file': f}print(f"正在发送图像 '{file_path}' 到 {url}...")response = requests.post(url, files=files)response.raise_for_status()  # 如果请求失败 (状态码 4xx or 5xx),则抛出HTTPError异常print("请求成功,响应内容:")print(response.json())except FileNotFoundError:print(f"错误:文件未找到,请检查路径 '{file_path}' 是否正确。")except requests.exceptions.ConnectionError:print(f"错误:无法连接到服务器 {url}。请确保API服务正在运行并且地址正确。")except requests.exceptions.HTTPError as http_err:print(f"HTTP错误:{http_err} - {response.status_code}")try:print(f"服务器响应:{response.json()}")except ValueError:print(f"服务器响应 (非JSON):{response.text}")except requests.exceptions.RequestException as e:print(f"请求过程中发生错误:{e}")except Exception as e:print(f"发生未知错误:{e}")print("-"*50) # 分隔每次请求的输出if __name__ == "__main__":if len(sys.argv) < 2:print("错误:请提供图像文件的路径作为命令行参数。")print("用法: python svm_request_dynamic.py <图像路径>")sys.exit(1)image_file_path = sys.argv[1]send_request(image_file_path)

svm_request_simplified.py:

import requests
import os
import sysurl = 'http://127.0.0.1:9000/api/v1/predict'  # 替换为实际的API地址def send_request(image_path):if not os.path.isabs(image_path):# 如果不是绝对路径,则假定它是相对于当前工作目录的路径file_path = os.path.abspath(image_path) # 获取绝对路径else:file_path = image_pathtry:with open(file_path, 'rb') as f:files = {'file': f}response = requests.post(url, files=files)response.raise_for_status()  # 如果请求失败 (状态码 4xx or 5xx),则抛出HTTPError异常data = response.json()print(data.get('predicted_category'))print(data.get('predicted_probability'))except FileNotFoundError:print(f"错误:文件未找到,请检查路径 '{file_path}' 是否正确。")except requests.exceptions.ConnectionError:print(f"错误:无法连接到服务器 {url}。请确保API服务正在运行并且地址正确。")except requests.exceptions.HTTPError as http_err:print(f"HTTP错误:{http_err} - {response.status_code}")try:print(f"服务器响应:{response.json()}")except ValueError:print(f"服务器响应 (非JSON):{response.text}")except requests.exceptions.RequestException as e:print(f"请求过程中发生错误:{e}")except Exception as e:print(f"发生未知错误:{e}")if __name__ == "__main__":if len(sys.argv) < 2:print("错误:请提供图像文件的路径作为命令行参数。")print("用法: python svm_request_simplified.py <图像路径>")sys.exit(1)image_file_path = sys.argv[1]send_request(image_file_path)

相关文章:

  • 四、STM32 HAL库API完全指南:从功能分类到实战示例
  • 微信小程序仿淘宝拍照/照片点位识图、点位裁剪生图、图片裁剪组件、图片点位框选、裁剪生成图片,canvasToImg
  • Parasoft C++Test软件单元测试_实例讲解(指针类型的处理)
  • Spring MVC 根据请求头 (如 Accept) 怎么返回 JSON 或 XML 数据?
  • WebFlux vs WebMVC vs Servlet 对比
  • 【SSM-SpringMVC(二)】Spring接入Web环境!本篇开始研究SpringMVC的使用!SpringMVC数据响应和获取请求数据
  • Spring MVC参数传递
  • tensorflow-cpu
  • tabs切换#
  • git|gitee仓库同步到github
  • PyCharm 快捷键指南
  • 基于Qt6 + MuPDF在 Arm IMX6ULL运行的PDF浏览器——MuPDF Tools
  • Spring Boot集成RabbitMQ高级篇:可靠性与性能提升
  • 面试题:请解释Java中的设计模式,并举例说明单例模式(Singleton Pattern)的实现方式
  • 解决WSL、Ubuntu的.ico图标不正确显示缩略图
  • 解决IDEA Maven编译时@spring.profiles.active@没有替换成具体环境变量的问题
  • 将本地文件上传到云服务器上
  • Redis+Caffeine构建高性能二级缓存
  • 数据出境的安全合规思考
  • 蓝桥杯13届国赛 2022
  • 马上评丨75万采购300元设备,仅仅终止采购还不够
  • 5年建成强化城市核心功能新引擎,上海北外滩“风景文化都是顶流”
  • 警方通报“网约车司机偷拍女乘客”:已被行政拘留
  • 山西忻州市人大常委会副主任郭建平接受审查调查
  • 邯郸一酒店办婚宴发生火灾,新郎母亲:饭没吃成酒店还要收费
  • 习近平会见塞尔维亚总统武契奇