在 json 请求正文中使用 \n 传递文本会在 fastapi 中提供无法处理的实体

Passing text with \n in json request body gives unprocessable entity in fastapi

我正在尝试将多行文本传递给 fastApi 代码。我的代码看起来像

from fastapi import FastAPI
from pydantic import BaseModel

from model import predictT5

testApp = FastAPI() # create an app

@testApp.get("/") # set root directory

# pydantic models
class TextIn(BaseModel):
    text: str
class TextOut(BaseModel):
    Summary: dict 

    # routes
def root():
    return {"message":"jmj"}

@testApp.post("/predict", response_model=TextOut, status_code=200)
def get_prediction(payload: TextIn):
    """
    Gets a text and runs through T5 & outputs summary
    """
    text = payload.text
    t5Summary = predictT5(text)

这适用于像

这样的请求
curl -X 'POST' \
  'http://127.0.0.1:8000/predict' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "text": "A dictionary that maps attention modules to devices. For reference, the t5 models have the following number of attention modules:"
}'

但是,如果我用 \n 拆分文本并有一个像

这样的请求正文
curl -X 'POST' \
  'http://127.0.0.1:8000/predict' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "text": "A dictionary that maps attention modules to devices.  
For reference, the t5 models have the following number of attention modules:"
}'

明白了

Error: Unprocessable Entity "msg": "Invalid control character at: line 2 column 285 (char 286)", "type": "value_error.jsondecode",

有人知道怎么处理吗? 谢谢!

根据 this answer,JSON.

中不允许使用多行字符串

来自同一来源:“您需要用 \n 替换所有换行符”