Condivisione della tecnologia

FastAPI Learning Road (41) Risposta di reso personalizzata

2024-07-12

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

Restituisce il contenuto in formato xml nell'interfaccia

  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")

Diamo un’occhiata al rendimento effettivo:

Il tipo restituito è in formato xml, a indicare che la restituzione ha avuto esito positivo.

Intestazioni personalizzate nell'interfaccia restituita

  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)

Diamo un’occhiata al rendimento effettivo

L'interfaccia corrispondente può restituire normalmente e le intestazioni corrispondenti possono restituire normalmente.

Imposta i 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

Diamo un’occhiata al rendimento effettivo

L'interfaccia può restituire i cookie che impostiamo normalmente e anche le intestazioni possono essere restituite normalmente.