본문 바로가기

개발하자

Fast API - 필드 필수, 누락된 값

반응형

Fast API - 필드 필수, 누락된 값

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}

원답

매개 변수로 제출했지만 엔드포인트에서 본문() 매개 변수로 예상합니다. 따라서 경로 매개 변수로 예상되는 엔드포인트를 아래와 같이 변경해야 합니다:

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

반응형