FastAPI 定制返回Response

返回自定义的 XML 内容

from fastapi import FastAPI,Response
@app.get("/legacy/")
def get_legacy_data():
    data = """<?xml version="1.0"?>
    <shampoo>
    <Header>
        Apply shampoo here.
    </Header>
    <Body>
        You'll have to use soap here.
    </Body>
    </shampoo>
    """
    return Response(content=data, media_type="application/xml")
if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=8000)

自定义返回 Header 信息

@app.get("/legacy/")
def get_legacy_data():
    headers = {"X-Cat": "leizi", "Content-Language": "en-US"}
    data = """<?xml version="1.0"?>
    <shampoo>
    <Header>
        Apply shampoo here.
    </Header>
    <Body>
        You'll have to use soap here.
    </Body>
    </shampoo>
    """
    return Response(content=data, media_type="application/xml",
                    headers=headers)
@app.get("/legacy/")
def get_legacy_data(response: Response):
    headers = {"X-Cat": "leizi", "Content-Language": "en-US"}
    data = """<?xml version="1.0"?>
    <shampoo>
    <Header>
        Apply shampoo here.
    </Header>
    <Body>
        You'll have to use soap here.
    </Body>r
    </shampoo>
    """
    response.set_cookie(key="message", value="hello")
    return Response(content=data, media_type="application/xml",
                    headers=headers)

Last updated