javascript代码-
<script>
async function postFormDataAsJson({ url, formData }) {
const plainFormData = Object.fromEntries(formData.entries());
console.log(plainFormData)
const formDataJsonString = JSON.stringify(plainFormData);
console.log(formDataJsonString)
console.log(typeof formDataJsonString)
const fetchOptions = {
mode:"no-cors",
method: "POST",
headers: {
"accept": "application/json",
"Content-Type": "application/json"
},
body: formDataJsonString
};
const response = await fetch(url, fetchOptions);
if (!response.ok) {
const errorMessage = await response.text();
throw new Error(errorMessage);
}
return response.json();
}
async function handleFormSubmit(event) {
event.preventDefault();
const form = event.currentTarget;
const url = "http://127.0.0.1:8000/predict_diabetes";
try {
const formData = new FormData(form);
const responseData = await postFormDataAsJson({ url, formData });
console.log({ responseData });
} catch (error) {
console.error(error);
}
}
const Form = document.getElementById("form");
Form.addEventListener("submit", handleFormSubmit);
</script>
PYDANTIC代码:其位于单独的文件diabetes_data. py中。
from pydantic import BaseModel
class Diabetes(BaseModel):
Pregnancies : int
Glucose : int
BloodPressure : int
SkinThickness : int
Insulin : int
BMI : int
DiabetesPedigreeFunction : int
Age : int
FASTAPI代码:
import numpy as np
import pickle
import pandas as pd
import uvicorn
from fastapi import FastAPI
from diabetes_data import Diabetes
from sklearn.preprocessing import StandardScaler
app = FastAPI()
pickle_in = open("svc_model.pkl","rb")
classifier=pickle.load(pickle_in)
sc = StandardScaler()
@app.post('/predict_diabetes')
def predict_diabetes(data:Diabetes):
data = data.dict()
Pregnancies = data['Pregnancies']
Glucose = data['Glucose']
BloodPressure = data['BloodPressure']
SkinThickness = data['SkinThickness']
Insulin = data['Insulin']
BMI = data['BMI']
DiabetesPedigreeFunction = data['DiabetesPedigreeFunction']
Age = data['Age']
data = sc.fit_transform([[Pregnancies,Glucose,BloodPressure,SkinThickness,Insulin,BMI,DiabetesPedigreeFunction,Age]])
prediction = classifier.predict(data)
if(prediction[0]>0.5):
prediction="Diabetic"
else:
prediction="Not Diabetic"
return {'prediction': prediction}
if __name__ == '__main__':
uvicorn.run(app, host='127.0.0.1', port=8000)
将console.log输出复制粘贴到docs上,它工作,但通过javascript发送时不工作。enter image description hereenter image description here
我试图发送表单数据。我首先将表单数据转换成json字符串并使用javascript获取。但得到错误422,但使用快速API文档时一切正常。
1条答案
按热度按时间nvbavucw1#