単一の 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: 個別のエンドポイントを定義する

もう 1 つのオプションは、単一のエンドポイントを使用し、ファイルおよび/またはフォーム データ パラメーターをオプションとして定義することです。いずれかのパラメータに値が渡されている場合は、リクエストが 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 または / に再ルーティングすることもできます。 submitForm エンドポイント。リクエストの Content-Type に応じて異なります。

<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 中国語 Web サイトの他の関連記事を参照してください。

ソース:php.cn
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!