단일 FastAPI 엔드포인트에서 양식과 JSON 데이터를 모두 처리하는 방법은 무엇입니까?

Patricia Arquette
풀어 주다: 2024-10-26 23:22:30
원래의
663명이 탐색했습니다.

How to Handle Both Form and JSON Data in a Single FastAPI Endpoint?

양식 또는 JSON 본문을 허용하는 FastAPI 엔드포인트를 생성하는 방법은 무엇입니까?

FastAPI에서는 양식 또는 JSON 본문을 허용하는 엔드포인트를 생성할 수 있습니다. 다른 방법을 사용합니다. 다음은 몇 가지 옵션입니다.

옵션 1: 종속성 함수 사용

이 옵션에는 Content-Type 요청 헤더의 값을 확인하고 Starlette의 메서드를 사용하여 본문을 구문 분석하는 종속성 함수 생성이 포함됩니다.

<code class="python">from fastapi import FastAPI, Depends, Request
from starlette.datastructures import FormData

app = FastAPI()

async def get_body(request: Request):
    content_type = request.headers.get('Content-Type')
    if content_type is None:
        raise HTTPException(status_code=400, detail='No Content-Type provided!')
    elif content_type == 'application/json':
        return await request.json()
    elif (content_type == 'application/x-www-form-urlencoded' or
          content_type.startswith('multipart/form-data')):
        try:
            return await request.form()
        except Exception:
            raise HTTPException(status_code=400, detail='Invalid Form data')
    else:
        raise HTTPException(status_code=400, detail='Content-Type not supported!')

@app.post('/')
def main(body = Depends(get_body)):
    if isinstance(body, dict):  # if JSON data received
        return body
    elif isinstance(body, FormData):  # if Form/File data received
        msg = body.get('msg')
        items = body.getlist('items')
        return msg</code>
로그인 후 복사

옵션 2: 별도의 끝점 정의

또 다른 옵션은 단일 끝점을 갖고 파일 및/또는 양식 데이터 매개 변수를 선택 사항으로 정의하는 것입니다. 매개변수에 전달된 값이 있으면 요청이 application/x-www-form-urlencoded 또는 multipart/form-data라는 의미입니다. 그렇지 않으면 JSON 요청일 가능성이 높습니다.

<code class="python">from fastapi import FastAPI, UploadFile, File, Form
from typing import Optional, List

app = FastAPI()

@app.post('/')
async def submit(items: Optional[List[str]] = Form(None),
                    files: Optional[List[UploadFile]] = File(None)):
    # if File(s) and/or form-data were received
    if items or files:
        filenames = None
        if files:
            filenames = [f.filename for f in files]
        return {'File(s)/form-data': {'items': items, 'filenames': filenames}}
    else:  # check if JSON data were received
        data = await request.json()
        return {'JSON': data}</code>
로그인 후 복사

옵션 3: 미들웨어 사용

또한 미들웨어를 사용하여 들어오는 요청을 확인하고 /submitJSON 또는 /로 경로를 변경할 수도 있습니다. 요청의 Content-Type에 따라 submitForm 엔드포인트.

<code class="python">from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

app = FastAPI()

@app.middleware(&quot;http&quot;)
async def some_middleware(request: Request, call_next):
    if request.url.path == '/':
        content_type = request.headers.get('Content-Type')
        if content_type is None:
            return JSONResponse(
                content={'detail': 'No Content-Type provided!'}, status_code=400)
        elif content_type == 'application/json':
            request.scope['path'] = '/submitJSON'
        elif (content_type == 'application/x-www-form-urlencoded' or
              content_type.startswith('multipart/form-data')):
            request.scope['path'] = '/submitForm'
        else:
            return JSONResponse(
                content={'detail': 'Content-Type not supported!'}, status_code=400)

    return await call_next(request)

@app.post('/')
def main():
    return

@app.post('/submitJSON')
def submit_json(item: Item):
    return item

@app.post('/submitForm')
def submit_form(msg: str = Form(...), items: List[str] = Form(...),
                    files: Optional[List[UploadFile]] = File(None)):
    return msg</code>
로그인 후 복사

옵션 테스트

Python의 요청 라이브러리를 사용하여 위 옵션을 테스트할 수 있습니다:

<code class="python">import requests

url = 'http://127.0.0.1:8000/'
files = [('files', open('a.txt', 'rb')), ('files', open('b.txt', 'rb'))]
payload ={'items': ['foo', 'bar'], 'msg': 'Hello!'}
 
# Send Form data and files
r = requests.post(url, data=payload, files=files)  
print(r.text)

# Send Form data only
r = requests.post(url, data=payload)              
print(r.text)

# Send JSON data
r = requests.post(url, json=payload)              
print(r.text)</code>
로그인 후 복사

위 내용은 단일 FastAPI 엔드포인트에서 양식과 JSON 데이터를 모두 처리하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!