You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于Django Rest API将prediction函数封装为返回JSON格式结果的API服务?

如何把你的预测函数封装成Django REST API

别担心,我一步步帮你把这个prediction函数改成可用的API服务,其实很简单的!

第一步:修正预测逻辑并封装成API视图

先梳理你现有代码里的几个小问题:

  • Liquidity.objects.get_or_create()返回的是元组(创建的对象+是否新创建的布尔值),直接赋值会报错,得拆包处理
  • 普通函数不能直接返回字典,Django REST要求返回Response对象
  • 函数需要从请求体中获取features_list,而不是直接作为参数传入

修改后的视图代码如下:

# views.py
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
import numpy as np
import pickle
import config
from .models import Liquidity
from .serializer import LiquiditySerializer

@api_view(['POST'])
def prediction_api(request):
    # 从POST请求的JSON body中提取特征列表
    features_list = request.data.get('features_list')
    if not features_list or not isinstance(features_list, list):
        return Response(
            {'error': '请提供有效的features_list数组'},
            status=status.HTTP_400_BAD_REQUEST
        )
    
    try:
        # 加载预训练模型与缩放器
        classifier = pickle.load(open(config.FINAL_MODEL_PATH, 'rb'))
        scaler = pickle.load(open(config.SCALER_PATH, 'rb'))
        
        # 特征预处理与预测
        sample = np.array(features_list).reshape(1, -1)
        sample_scaled = scaler.transform(sample)
        pred_y = classifier.predict(sample_scaled)[0]
        prob_y = classifier.predict_proba(sample_scaled)
        
        # 计算score值
        if prob_y[0][1] < 0.5:
            score = 0
        elif prob_y[0][1] <= 0.69:
            score = 1
        else:
            score = 2
        
        # 保存结果到数据库
        prediction_obj, created = Liquidity.objects.get_or_create(
            pred_y=pred_y,
            score=score
        )
        
        # 用序列化器格式化返回结果
        serializer = LiquiditySerializer(prediction_obj)
        return Response(serializer.data, status=status.HTTP_200_OK)
    
    except Exception as e:
        return Response(
            {'error': f'预测过程出错:{str(e)}'},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )

第二步:配置API路由

在你的app的urls.py里添加这个新API的路由:

# urls.py
from django.urls import path
from .views import PredictionSet, prediction_api

urlpatterns = [
    # 保留你原来的ModelViewSet路由(用于管理Liquidity记录)
    path('predictions/', PredictionSet.as_view({'get': 'list', 'post': 'create'}), name='prediction-set'),
    # 新增的预测API路由
    path('predict/', prediction_api, name='predict-api'),
]

第三步:测试你的API

现在你可以用Postman、curl或者前端请求来测试:

  • 请求方法:POST
  • 请求地址:http://你的域名/predict/
  • 请求Body(JSON格式):
{
    "features_list": [1.2, 3.5, 5.1, 2.8]  // 替换成你的实际特征数值
}

为什么不用ModelViewSet?

你的PredictionSet是用来对Liquidity模型做增删改查(比如获取所有历史预测记录),但你需要的是接收特征并实时返回预测结果的业务逻辑,用@api_view装饰器更灵活,也更贴合你的需求。

额外优化建议

  • 把模型和缩放器缓存起来(比如用全局变量或Django缓存框架),避免每次请求都重新加载,提升性能
  • 对features_list的数值类型做校验,确保传入的都是有效数字
  • 可以把预测逻辑封装成单独的工具类,让视图代码更简洁

内容的提问来源于stack exchange,提问作者edche

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 19:59:07