技术共享

FastAPI 学习之路(四十一)定制返回Response

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格式的,说明返回成功。

接口返回中定制headers

  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)

我们看下实际返回

对应的接口可以正常返回,对应的Headers返回正常。

设置cookie

  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

我们看下实际返回

接口可以正常返回我们设置的cookie,headers也可以正常返回。