繁体   English   中英

我需要一个 HTML 前端来测试和使用 Django API

[英]I need a HTML front end to test and use a Django API

新手在这里。 我按照在线指南成功部署了 Keras model 和 Django ZDB974238714CA8DE6434A7CE1D083。 I wanted to create a HTML file which connected to the Django API, where I can load image into the model for processing, and then send back the prediction.

以下是 API 的代码。 我需要有人指导我。

import datetime
import pickle
import json
from django.shortcuts import render
from django.http import HttpResponse
from rest_framework.decorators import api_view
from api.settings import BASE_DIR

from custom_code import image_converter

@api_view(['GET'])
def __index__function(request):
    start_time = datetime.datetime.now()
    elapsed_time = datetime.datetime.now() - start_time
    elapsed_time_ms = (elapsed_time.days * 86400000) + (elapsed_time.seconds * 1000) + (elapsed_time.microseconds / 1000)
    return_data = {
        "error" : "0",
        "message" : "Successful",
        "restime" : elapsed_time_ms
    }
    return HttpResponse(json.dumps(return_data), content_type='application/json; charset=utf-8')

@api_view(['POST','GET'])
def predict_plant_disease(request):
    try:
        if request.method == "GET" :
            return_data = {
                "error" : "0",
                "message" : "Plant Assessment System"
            }
        else:
            if request.body:
                request_data = request.data["plant_image"]
                header, image_data = request_data.split(';base64,')
                image_array, err_msg = image_converter.convert_image(image_data)
                if err_msg == None :
                    model_file = f"{BASE_DIR}/ml_files/cnn_model.pkl"
                    saved_classifier_model = pickle.load(open(model_file,'rb'))
                    prediction = saved_classifier_model.predict(image_array) 
                    label_binarizer = pickle.load(open(f"{BASE_DIR}/ml_files/label_transform.pkl",'rb'))
                    return_data = {
                        "error" : "0",
                        "data" : f"{label_binarizer.inverse_transform(prediction)[0]}"
                    }
                else :
                    return_data = {
                        "error" : "4",
                        "message" : f"Error : {err_msg}"
                    }
            else :
                return_data = {
                    "error" : "1",
                    "message" : "Request Body is empty",
                }
    except Exception as e:
        return_data = {
            "error" : "3",
            "message" : f"Error : {str(e)}",
        }
    return HttpResponse(json.dumps(return_data), content_type='application/json; charset=utf-8')

如果您只需要测试您的 API,请下载 Postman 并从应用程序发出请求。 这比实际制作整个 HTML 脚本来测试您的 API 要容易得多。 但是,如果您绝对需要通过前端应用程序测试您的 API,请尝试以下步骤。

  1. 您需要在 HTML 代码中上传图片 function。

<body>
   <input type="file accept="image/png, image/jpeg"/>
</body>

  1. 确保您有一个有效的 API 请求 URL
// For example

POST <site>/v1/plant-image
  1. 从 JS 脚本发出请求
<script type="text/javascript">

    var HTTP = new XMLHttpRequest();
        HTTP.onreadystatechange = function () {
            if (HTTP.readyState === 4 && HTTP.status === 200) {
                console.log(HTTP.responseText);
            }
        }
        HTTP.open('POST', 'https://<site>/v1/plant-image', true);
        HTTP.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
        HTTP.send();
</script>

由于您使用的是 DRF,因此请确保通过引发错误而不是将它们作为响应返回来处理错误。 这可以使错误处理更容易。

from rest_framework.exceptions import ValidationError

// some code...

raise ValidationError()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM