前言
上一篇我们分享了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)
那么我们请求下看下接口的实际返回。
那么我们看下返回类型是xml格式的。
在返回的时候,有时候我们需要在返回的headers。我们应该如何实现呢
@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)
其实很简单。我们可以请求下
对应的接口可以正常返回,对应的Headers返回正常。
要想设置cookie也很简单
@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)
我们看下结果
接口可以正常返回我们设置的cookie,headers也可以正常返回。
后记
发现问题,解决问题。遇到问题,慢慢解决问题即可。
欢迎关注雷子说测试开发,后续将会持续为大家分享更多的技术知识