我正在使用 FastAPI 开发 API,并且遇到了接受可选文本或文件参数的 POST 端点的问题。尽管为这些参数设置了默认值,我仍然收到 400 Bad Request 错误。
这是我的代码的相关部分:
from dotenv import load_dotenv
load_dotenv()
from fastapi import APIRouter, HTTPException, UploadFile, File
import base64
import os
from ai_interaction.prompt import assemble_prompt
from ai_interaction.llm import stream_openai_response
router = APIRouter()
@router.post("/query")
async def process_user_query(text: str = None, file: UploadFile = File(None)):
print("Received text:", text)
print("Received file:", file)
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
raise HTTPException(status_code=500, detail="API key not configured.")
if not text and not file:
raise HTTPException(status_code=400, detail="No text or file provided.")
if text:
image_url = text # Add URL validation here
elif file:
image_url = await process_uploaded_file(file)
prompt = assemble_prompt(image_url)
response = await stream_openai_response(prompt, api_key)
return {"response": response}
async def process_uploaded_file(file: UploadFile):
content = await file.read()
base64_encoded = base64.b64encode(content).decode('utf-8')
file_url = f"data:{file.content_type};base64,{base64_encoded}"
await file.close()
return file_url
import requests
url = "http://localhost:8000/api/query"
payload = [{"text": "Explain the water molecule structure"}]
response = requests.post(url, json=payload)
print("Status Code:", response.status_code)
print("Response Body:", response.json())
尝试使用 BaseModel 解析请求正文。该代码正在接收 json 输入,但本质上并不知道如何将其拆分为两个变量。当我在我的机器上运行你的代码时,类似的事情起作用了。
from pydantic import BaseModel
class Item(BaseModel):
text: str = None
file: UploadFile = File(None)
router = APIRouter()
@router.post("/query")
async def process_user_query(item: Item):
text = item.text
file = item.file