简体   繁体   中英

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

newbie here. I followed a guide online and successfully deploy a Keras model with Django API. 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.

Below are the codes for the API. I need someone to guide me.

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')

If you just need to test your API, download Postman and make requests from the application. It is much easier than actually making a whole HTML script to test your API. However, if you absolutely need to test your API through a frontend app, try the steps below.

  1. You need an image upload function in your HTML code.

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

  1. Make sure you have a valid API request URL
// For example

POST <site>/v1/plant-image
  1. Make the request from JS Script
<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>

Since you are using DRF, make sure to handle errors by raising errors instead of returning them as responses. This can make error handling much easier.

from rest_framework.exceptions import ValidationError

// some code...

raise ValidationError()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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