在构建复杂的AI模型部署服务时,我们通常需要定义多个API端点,例如健康检查、模型预测、日志查询等。Flask的Blueprint机制是实现模块化和版本控制的关键。正确设置请求方法(如GET、POST)对于保证API的安全性和规范性至关重要。
本文将深入讲解如何在Flask Blueprint中配置HTTP请求方法,并提供一个实战示例,用于分离AI服务的健康检查(GET)和核心推理(POST)路由。
Contents
1. Blueprint中设置请求方法的核心机制
无论是在主应用还是在Blueprint中,定义路由请求方法的机制是相同的:通过在@route装饰器中传入methods参数,该参数接受一个HTTP方法名称的列表。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 from flask import Blueprint
model_bp = Blueprint('model_api', __name__, url_prefix='/v1/model')
# 默认情况下,如果不指定 methods,Flask 默认接受 ['GET', 'HEAD', 'OPTIONS']
# 示例1: 仅接受 GET 请求
@model_bp.route('/status', methods=['GET'])
def get_status():
return 'Model is ready'
# 示例2: 仅接受 POST 请求 (用于提交数据进行推理)
@model_bp.route('/infer', methods=['POST'])
def run_inference():
# 处理推理逻辑
return {'prediction': 'result'}
# 示例3: 接受 GET 和 POST 请求
@model_bp.route('/data', methods=['GET', 'POST'])
def handle_data():
# ...
pass
2. 实践:为AI服务创建结构化的Blueprint
我们将创建一个名为inference_bp的Blueprint,用于管理模型部署的API。我们要求健康检查必须是GET请求,而模型预测必须是POST请求(因为通常POST用于传输较大的JSON或二进制数据)。
文件结构
1
2 ├── app.py
└── inference_bp.py
2.1 定义 Blueprint (inference_bp.py)
该文件定义了具体的路由和请求方法限制。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29 from flask import Blueprint, request, jsonify
# 定义 Blueprint,并设置基础 URL 前缀为 /api/v1
inference_bp = Blueprint('inference', __name__, url_prefix='/api/v1')
# 路由 1: 健康检查 (必须使用 GET)
@inference_bp.route('/health', methods=['GET'])
def health_check():
# 典型的 Liveness/Readiness 检查点
return jsonify({"status": "ok", "model_version": "v2.1"}), 200
# 路由 2: 模型预测 (必须使用 POST 提交数据)
@inference_bp.route('/predict', methods=['POST'])
def run_inference():
# 确保请求是 JSON 格式
if not request.is_json:
return jsonify({"error": "Content-Type must be application/json"}), 415
try:
input_data = request.get_json()
# --- 模拟复杂的推理过程 ---
# 在实际应用中,这里会调用模型加载器进行预测
result = {"score": sum(input_data.get('features', [0])) / 10.0}
# -------------------------
return jsonify({"result": result, "method_used": request.method}), 200
except Exception as e:
return jsonify({"error": f"Processing failed: {str(e)}"}), 500
2.2 注册 Blueprint (app.py)
主应用文件负责创建Flask实例并注册Blueprint。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 from flask import Flask
from inference_bp import inference_bp
app = Flask(__name__)
# 注册 Blueprint
app.register_blueprint(inference_bp)
@app.route('/')
def index():
return 'Welcome to the AI Inference Service. See /api/v1/health'
if __name__ == '__main__':
# 在生产环境中,推荐使用 gunicorn 或 uWSGI 部署
app.run(debug=True, port=5000)
3. 运行与验证
启动应用后,我们使用 curl 验证请求方法的限制。
1
2
3
4
5
6
7
8
9
10
11
12
13
14 # 1. 验证健康检查 (GET - 成功)
$ curl -X GET http://127.0.0.1:5000/api/v1/health
{"model_version":"v2.1","status":"ok"}
# 2. 验证模型预测 (POST - 成功)
$ curl -X POST -H "Content-Type: application/json" -d '{"features": [5, 15, 8]}' http://127.0.0.1:5000/api/v1/predict
{"result":{"score":2.8},"method_used":"POST"}
# 3. 尝试使用 GET 访问预测端点 (失败,返回 405 Method Not Allowed)
$ curl -X GET http://127.0.0.1:5000/api/v1/predict
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>405 Method Not Allowed</title>
<h1>Method Not Allowed</h1>
<p>The method is not allowed for the requested URL.</p>
通过以上步骤,我们成功利用Flask Blueprint构建了一个结构清晰、请求方法受限的AI模型部署API,确保了推理端点只能通过POST方法安全地接收数据。
汤不热吧