기술나눔

FastAPI Learning Road (41) 맞춤형 반환 응답

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

인터페이스에서 xml 형식 콘텐츠 반환

  1. from fastapi import FastAPI, Response
  2. app = FastAPI()
  3. # ① xml
  4. @app.get("/legacy")
  5. def get_legacy_data():
  6. data = """<?xml version="1.0"?>
  7. <shampoo>
  8. <Header>
  9. Apply shampoo here.
  10. </Header>
  11. <Body>
  12. You'll have to use soap here.
  13. </Body>
  14. </shampoo>
  15. """
  16. return Response(content=data, media_type="application/xml")

실제 수익을 살펴보겠습니다.

반환된 유형은 반환이 성공했음을 나타내는 xml 형식입니다.

인터페이스 반환의 사용자 정의 헤더

  1. @app.get("/legacy_with_headers")
  2. def get_legacy_with_headers_data():
  3. headers = {"X-Xtoken": "LC", "Content-Language": "en-US"}
  4. data = """<?xml version="1.0"?>
  5. <shampoo>
  6. <Header>
  7. Apply shampoo here.
  8. </Header>
  9. <Body>
  10. You'll have to use soap here.
  11. HERE SOMETHING HEADER YOU DEFINED
  12. </Body>
  13. </shampoo>
  14. """
  15. return Response(content=data, media_type="application/xml", headers=headers)

실제 수익률을 살펴보겠습니다

해당 인터페이스는 정상적으로 반환될 수 있고, 해당 헤더도 정상적으로 반환될 수 있습니다.

쿠키 설정

  1. @app.get("/legacy_with_header_cookie")
  2. def legacy_with_header_cookie():
  3. headers = {"X-Xtoken": "LC-1", "Content-Language": "en-US"}
  4. data = """<?xml version="1.0"?>
  5. <shampoo>
  6. <Header>
  7. Apply shampoo here.
  8. </Header>
  9. <Body>
  10. You'll have to use soap here.
  11. HERE SOMETHING HEADER YOU DEFINED AND COOKIE
  12. </Body>
  13. </shampoo>
  14. """
  15. response = Response(content=data, media_type="application/xml", headers=headers)
  16. response.set_cookie(key="cookie_key_lc", value="mrli")
  17. return response

실제 수익률을 살펴보겠습니다

인터페이스는 우리가 설정한 쿠키를 정상적으로 반환할 수 있고, 헤더도 정상적으로 반환할 수 있습니다.