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

发布于:2025-05-13 ⋅ 阅读:(10) ⋅ 点赞:(0)

API 测试指南

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

Curl:

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

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

import requests

url = '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 sys

url = '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_path

    try:
        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 sys

url = '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_path

    try:
        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)

网站公告

今日签到

点亮在社区的每一天
去签到