gpt4 book ai didi

Python FastAPI "Post Unprocessable Entity"错误

转载 作者:行者123 更新时间:2023-12-03 18:59:53 26 4
gpt4 key购买 nike

提交按钮时出错
main.py

from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
from googletrans import Translator

import uvicorn

#from googletrans import Translator
#init
app = FastAPI(debug=True)

templates = Jinja2Templates(directory="template")


#route
@app.get('/')
async def home(request: Request):
data = {'request': request}
return templates.TemplateResponse('translates.html', data)


class variable(BaseModel):
Input_text: str
trans: str

#def translator(request):
@app.post('/',response_model=variable)
async def trans(request: Request, form: variable ):

text = request.get('Input_text')
lang = request.get('trans')
# print('text:',text,'lang:',lang)

# connect the translator
translator = Translator(service_urls=['translate.googleapis.com'])

# detect langguage
dt = translator.detect(text)
dt2 = dt.lang

# translate the text
translated = translator.translate(text, lang)
tr = translated.text
data = {
'request': request,
'translated': tr
, 'u_lang': dt2
, 't_lang': lang}

return templates.TemplateResponse(data, "translates.html",)


if __name__=="__main__":
uvicorn.run(app,host="127.0.0.1",port=8000)
然后是 HTML 代码
translate.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Translate</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">
<script src="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.js"></script>

</head>
<body>
<div class="ui container">
<h2>Translation</h2>

<form action="" method="post">
<br>

<div class="form-input">
<center><label for="TextareaInput">Enter Text </label></center>
<center><textarea class="form-control" name="Input_text" id="TextareaInput" rows="3"></textarea></center>
</div>
<div class="ui divider"></div>

<div class="selection list">
<center><label for="languages">Choose Langguage:</label></center>
<center><select name="trans" id="languages">
<option value="en">English</option>
<option value="ms">Malay</option>
<option value="zh-cn">Mandarin</option>
<option value="ko">Korean</option>
<option value="ja">Japanese</option>
<option value="vi">Vietnamese</option>
<option value="th">Thailand</option>
</select></center>
</div>
<div class="ui divider"></div>

<div>
<center> <button type="Submit" class="button">Translate</button></center>
</div>
<div class="ui divider"></div>

<div class="form-output">
<!---<center><textarea class="form-control" id="TextareaOutput" rows="3" value={{translated}} placeholder="Translate..."></textarea></center>-->

<div class="Output Translation">

<br><br>
<h1>Text translated {{u_lang}} from {{t_lang}}</h1>
<center>
<h1>{{translated}}</h1>
</center>
</div>
</div>
</form>

</div>

</body>
</html>
当我尝试按钮提交时,这些会发生 ->
{
"detail": [
{
"loc": [
"body",
0
],
"msg": "Expecting value: line 1 column 1 (char 0)",
"type": "value_error.jsondecode",
"ctx": {
"msg": "Expecting value",
"doc": "Input_text=hi&trans=zh-cn",
"pos": 0,
"lineno": 1,
"colno": 1
}
}
]
}
很确定错误发生在我的 BaseModel 参数上,但我似乎无法纠正它,已经在互联网上搜索了。

最佳答案

当您使用 pydantic 模型作为请求体参数时,FastAPI interprets 它们作为 json 对象:

With just that Python type declaration, FastAPI will:

  • Read the body of the request as JSON.
  • Convert the corresponding types (if needed).
  • Validate the data...

但是 HTML 表单不是以 json 的形式发送到服务器,而是以特殊的 x-www-form-urlencoded 格式(更多信息 here ),因此要读取表单值,您需要使用 Form 参数,如下所示:
@app.post("/")
async def path_operation(Input_text: str = Form(...), trans: str = Form(...)):
return {"Input_text": Input_text, "trans": trans}

关于Python FastAPI "Post Unprocessable Entity"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65120116/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com