簡體   English   中英

FastAPI - 必填字段,缺少值

[英]FastAPI - Field required, missing value

當我將我的應用程序部署到 Heroku 時,我收到以下錯誤:

{
   "detail": [
      {
         "loc": [
               "body",
               "id"
         ],
         "msg": "field required",
         "type": "value_error.missing"
      }
   ]
}

並登錄控制台:

22-03-05T19:45:12.863425+00:00 heroku[router]: at=info method=GET path="/" host=wallet-reputation.herokuapp.com request_id=51780a1f-491a-4dd6-a8c0-164b41745405 fwd="95.175.20.47" dyno=web.1 connect=0ms service=4ms status=422 bytes=248 protocol=http

這是我的 Fastapi 應用程序:

@app.get("/")
def index(request: Request, id: str = Form(...)):
    return templates.TemplateResponse("main_page.html", context={"request": request})

這就是我的 HTML 文件的樣子:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.1.3/dist/css/bootstrap.min.css"
          integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

    <title>Main Page</title>
  </head>
  <body>
    <form method="get">
      <center>
      <div class="form-group col-lg-4">
        <label for="walletAdress">Natluk Coin Reputation Wallet</label>
        <input type="text" class="form-control" id="walletAdress" aria-describedby="walletlHelp"
               placeholder="Wallet address" style="text-align: center" name="id">
      </div>
      </center>
      <center>
        <a class="btn btn-primary" type="submit" role="button"
           href="https://wallet-reputation.herokuapp.com/wallet/{{ id }}">Check Wallet</a>
        <a class="btn btn-primary" type="submit" role="button"
           href="https://wallet-reputation.herokuapp.com/wallet/run/{{ id }}">Create Wallet</a>
      </center>
</html>

所以邏輯是,當我訪問我的"/"端點時,我將字符串發布到表單中,然后我單擊其中一個按鈕,它開始使用來自表單的變量運行端點。

更新

下面是一個示例,說明如何通過表單提交值,以及您的端點應該是什么樣子:

from fastapi import FastAPI, Request, status, Form
from fastapi.responses import HTMLResponse

app = FastAPI()

@app.get('/', response_class=HTMLResponse)
async def event_create_form(request: Request):
    html_content = """
    <html>
       <body>
          <form method="POST" action="/submit">
             <input type="text" name="id">
             <input type="submit" value="Create Event">
          </form>
       </body>
    </html>
    """
    return HTMLResponse(content=html_content, status_code=200)
    
@app.post('/submit')
async def event_create(id: int = Form(...)):
    return {"id": id}

原答案

您正在提交id作為path參數,但您的端點希望它是一個 body ( Form ) 參數。 因此,您應該如下所示更改端點,以便將id作為路徑參數:

@app.get("/{id}")
def index(request: Request, id: str):
    ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM