단일 FastAPI 엔드포인트에서 양식과 JSON 데이터를 모두 처리하는 방법은 무엇입니까?
양식 또는 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("http") 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Fiddlerevery Where를 사용할 때 Man-in-the-Middle Reading에 Fiddlereverywhere를 사용할 때 감지되는 방법 ...

Linux 터미널에서 Python 사용 ...

10 시간 이내에 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법은 무엇입니까? 컴퓨터 초보자에게 프로그래밍 지식을 가르치는 데 10 시간 밖에 걸리지 않는다면 무엇을 가르치기로 선택 하시겠습니까?

Pythonasyncio에 대해 ...

Investing.com의 크롤링 전략 이해 많은 사람들이 종종 Investing.com (https://cn.investing.com/news/latest-news)에서 뉴스 데이터를 크롤링하려고합니다.

Python 3.6에 피클 파일 로딩 3.6 환경 오류 : ModulenotFounderRor : nomodulename ...

SCAPY 크롤러를 사용할 때 파이프 라인 파일을 작성할 수없는 이유에 대한 논의 지속적인 데이터 저장을 위해 SCAPY 크롤러를 사용할 때 파이프 라인 파일이 발생할 수 있습니다 ...
