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

Streamlit对接FastAPI时出现字段缺失错误求助

问题分析与解决方案

核心问题

你遇到的字段缺失错误,本质是两个关键问题导致的:

  1. 请求字段名不匹配:Streamlit发送的字典键名和FastAPI中User_input模型定义的字段名完全不一致,导致Pydantic校验失败。
  2. 请求格式不正确:发送JSON数据时未设置正确的Content-Type请求头,FastAPI无法正确解析请求体。

修正步骤及代码

1. 修正Streamlit代码(关键)

需要将请求字典的键名完全对应FastAPI的User_input字段,同时使用正确的请求方式发送JSON数据:

import streamlit as st
import requests

# 输入控件(可自行修改滑块提示文本)
contract = st.sidebar.slider("合同类型", 0, 100, 20)
children = st.sidebar.slider("子女数量", 0, 100, 20)
credit_amnt = st.sidebar.slider("信贷总额", 0, 100, 20)
members = st.sidebar.slider("家庭成员数", 0, 100, 20)
credit_active = st.sidebar.slider("活跃信贷状态", 0, 100, 20)
amt_income_total = st.sidebar.slider("总收入", 0, 100, 20)
bureau = st.sidebar.slider("征信记录年份", 0, 100, 20)
delay = st.sidebar.slider("分期付款逾期天数", 0, 100, 20)

# 修正键名,完全匹配FastAPI的User_input模型字段
user_input_dict = {
    "name_contract_type": contract,
    "children_count": children,
    "fam_members": members,
    "amt_credit_sum": credit_amnt,
    "DAYS_INSTALMENT_delay": delay,
    "amt_income_total": amt_income_total,
    "credit_active": credit_active,
    "bureau_year": bureau
}

btn_predict = st.sidebar.button("预测")

if btn_predict:
    # 使用json参数直接传递字典,requests会自动处理序列化和Content-Type头
    res = requests.post(url='https://66c4-34-73-148-78.ngrok.io/Loan', json=user_input_dict)
    st.subheader(f"API响应 ={res.text}")

2. 优化FastAPI代码(可选,更简洁)

无需手动解析JSON,直接使用Pydantic模型的属性即可:

from fastapi import FastAPI
from pydantic import BaseModel
import pickle

app = FastAPI()

class User_input(BaseModel):
    name_contract_type: int
    children_count: int
    fam_members: int
    amt_credit_sum: float
    DAYS_INSTALMENT_delay: int
    amt_income_total: float
    credit_active: int
    bureau_year: int

# 请替换为你的模型文件实际路径
PATH = "./"
with open(PATH + "lr.pkl", "rb") as f:
    model = pickle.load(f)

@app.post('/Loan')
def loan_pred(input_parameters: User_input):
    # 直接调用模型属性,避免手动解析字典
    input_list = [
        input_parameters.name_contract_type,
        input_parameters.children_count,
        input_parameters.fam_members,
        input_parameters.amt_credit_sum,
        input_parameters.DAYS_INSTALMENT_delay,
        input_parameters.credit_active,
        input_parameters.amt_income_total,
        input_parameters.bureau_year
    ]

    prediction = model.predict([input_list])

    return 'The customer will refund his loan' if prediction[0] == 0 else 'The customer will not refund his loan'

关键注意事项

  • 字段名严格匹配:FastAPI的Pydantic模型对字段名的大小写、下划线完全敏感,必须和请求中的键名完全一致。
  • 请求头自动处理:使用requests.post的json参数传递数据时,框架会自动添加Content-Type: application/json请求头,确保FastAPI能正确解析JSON格式的请求体。

内容的提问来源于stack exchange,提问作者Alex NOROOZI KIA

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 22:55:16