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

算法模型部署后_python脚本API测试指南

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

Curl:

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

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

python 复制代码
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 响应。

    bash 复制代码
    python svm_request_dynamic.py <你的图像路径>

    例如:

    bash 复制代码
    python svm_request_dynamic.py ./test_dataset/corona/corona111.png

    或者使用绝对路径:

    bash 复制代码
    python svm_request_dynamic.py /path/to/your/image.png

测试效果:

  1. 使用 svm_request_simplified.py (输出简化结果):

    此脚本会发送图像到 API 并仅打印预测的类别和置信度。

    bash 复制代码
    python svm_request_simplified.py <你的图像路径>

    例如:

    bash 复制代码
    python svm_request_simplified.py ./test_dataset/surface/surface57.png

    或者使用绝对路径:

    bash 复制代码
    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

python 复制代码
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:

python 复制代码
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'))
            # print(data)
    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)
相关推荐
Time Famine1 分钟前
射击游戏demo11
python·游戏·pygame
米粉03055 分钟前
算法图表总结:查找、排序与递归(含 Mermaid 图示)
数据结构·算法·排序算法
人类发明了工具25 分钟前
【优化算法】协方差矩阵自适应进化策略(Covariance Matrix Adaptation Evolution Strategy,CMA-ES)
线性代数·算法·矩阵·cma-es
黑色的山岗在沉睡28 分钟前
LeetCode100.4 移动零
数据结构·算法·leetcode
学地理的小胖砸1 小时前
【Python 面向对象】
开发语言·python
钢铁男儿1 小时前
PyQt 探索QMainWindow:打造专业的PyQt5主窗
python·qt·pyqt
方博士AI机器人1 小时前
算法与数据结构 - 二叉树结构入门
数据结构·算法·二叉树
-qOVOp-1 小时前
zst-2001 上午题-历年真题 算法(5个内容)
算法
九章云极AladdinEdu1 小时前
GPU SIMT架构的极限压榨:PTX汇编指令级并行优化实践
汇编·人工智能·pytorch·python·深度学习·架构·gpu算力
全栈凯哥1 小时前
Java详解LeetCode 热题 100(17):LeetCode 41. 缺失的第一个正数(First Missing Positive)详解
java·算法·leetcode