只有当响应是 HTML 响应(即 HTML 页面)时,换行才有意义。 \n 不能正确呈现为新行或换行符,您必须使用 <br> 或 HTML template + some CSS styling to preserve line breaks。
FastAPI 默认返回JSONResponse type。
获取一些数据并返回一个application/json 编码响应。
这是 FastAPI 中使用的默认响应,如您在上面阅读的那样。
但是你可以告诉use an HTMLResponse type using the response_class parameter:
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
app = FastAPI()
@app.get('/status', response_class=HTMLResponse)
def get_func():
output = 'this output should <br> have a line break'
return output
或者,为了更好地控制,使用实际的 HTML 模板。 FastAPI 支持 Jinja2 模板,请参阅FastAPI Templates 部分。
proj/templates/output.html
<html>
<head>
</head>
<body>
<p>This output should have a <br>line break.</p>
<p>Other stuff: {{ stuff }}</p>
</body>
</html>
proj/main.py
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.get('/status', response_class=HTMLResponse)
def get_func(request: Request):
return templates.TemplateResponse("output.html", {"request": request, "stuff": 123})
有了 HTML 模板,您就可以使用CSS styling to preserve line breaks。