FastAPI를 사용하여 JSON 형식으로 데이터를 반환하는 방법은 무엇입니까?
FastAPI를 사용하여 JSON 형식으로 데이터를 반환하려면 jsonable_encoder 인코더를 사용하여 Python 데이터 구조를 JSON 호환 데이터로 변환합니다. 이는 다음 옵션 중 하나를 사용하여 달성할 수 있습니다.
옵션 1: jsonable_encoder를 자동으로 사용
평소와 같이 데이터를 반환하면 FastAPI가 자동으로 JSON 변환을 처리합니다. FastAPI는 내부적으로 jsonable_encoder를 사용하여 데이터를 JSON 호환 형식으로 변환합니다. jsonable_encoder는 datetime 객체와 같은 지원되지 않는 객체가 문자열로 변환되도록 보장합니다. 그런 다음 FastAPI는 클라이언트가 JSON 응답으로 수신하는 application/json 미디어 유형을 사용하여 JSONResponse 객체에 데이터를 래핑합니다.
from fastapi.encoders import jsonable_encoder from fastapi.responses import JSONResponse def return_dict(): data_dict = {"name": "John Doe", "age": 30} return JSONResponse(content=jsonable_encoder(data_dict))
옵션 2: 수동 JSON 변환
사용자 정의 JSON 변환을 수행해야 하는 경우 media_type이 'application/json'으로 설정되고 콘텐츠가 JSON으로 인코딩된 데이터. 지원되지 않는 개체가 JSON으로 인코딩되기 전에 문자열로 변환되도록 하려면 default=str 인수와 함께 json.dumps() 함수를 사용하는 것을 잊지 마세요.
import json from fastapi import Response def return_response(): data_dict = {"name": "John Doe", "age": 30} json_data = json.dumps(data_dict, default=str) return Response(content=json_data, media_type="application/json")
추가 참고 사항:
- 기본적으로 FastAPI는 Content-Length 및 Content-Type 헤더를
- Response 또는 JSONResponse 객체의 status_code 속성을 설정하여 응답에 대한 사용자 정의 상태 코드를 지정할 수 있습니다.
위 내용은 FastAPI에서 JSON 데이터를 반환하는 방법: 자동 변환과 수동 변환?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

Pythonusesahybridmodelofilationandlostretation : 1) ThePyThoninterPretreCeterCompileSsourcodeIntOplatform-IndependentBecode.

Pythonisbothingretedandcompiled.1) 1) it 'scompiledtobytecodeforportabilityacrossplatforms.2) thebytecodeisthentenningreted, withfordiNamictyTeNgreted, WhithItmayBowerShiledlanguges.

forloopsareusedwhendumberofitessiskNowninadvance, whilewhiloopsareusedwhentheationsdepernationsorarrays.2) whiloopsureatableforscenarioScontiLaspecOndCond

pythonisnotpurelynlogreted; itusesahybrideprophorfbyodecodecompilationandruntime -INGRETATION.1) pythoncompilessourcecodeintobytecode, thepythonVirtualMachine (pvm)

ToconcatenatelistsinpythonwithesameElements, 사용 : 1) OperatorTokeEpduplicates, 2) asettoremovedUplicates, or3) listComperensionForControlOverDuplicates, 각 methodHasDifferentPerferformanCeanDorderImpestications.

PythonisancerpretedLanguage, 비판적 요소를 제시하는 PytherfaceLockelimitationsIncriticalApplications.1) 해석 된 언어와 같은 thePeedBackandbackandrapidProtoTyping.2) CompilledlanguagesLikec/C transformt 해석

useforloopswhhenmerfiterationsiskNownInAdvance 및 WhileLoopSweHeniTesslationsDepoyConditionismet whilEroopsSuitsCenarioswhereTheLoopScenarioswhereTheLoopScenarioswhereTheLoopScenarioswhereTherInatismet, 유용한 광고 인 푸트 gorit


핫 AI 도구

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

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

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

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

Dreamweaver Mac版
시각적 웹 개발 도구

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

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경