如何使用 FastAPI 返回带换行符的响应?

Pet*_*ter 6 python python-3.x fastapi

@app.get('/status')
def get_func(request: Request):
  output = 'this output should have a line break'
  return output
Run Code Online (Sandbox Code Playgroud)

我尝试过的事情:

  • output = this output should \n have a line break
  • output = this output should <br /> have a line break

文本本身被返回,但我没有得到换行符。

小智 9

使用response_class=PlainTextResponse

from fastapi.responses import PlainTextResponse
@app_fastapi.get("/get_log", response_class=PlainTextResponse)
async def get_log():
    return "hello\nbye\n"
Run Code Online (Sandbox Code Playgroud)


Gin*_*pin 4

仅当响应是 HTML 响应(即 HTML 页面)时,换行符才有意义。并且 a\n无法正确呈现为新行或换行符,您必须使用HTML 模板<br>+一些CSS 样式来保留换行符

默认情况下,FastAPI 返回JSONResponse类型

获取一些数据并返回application/json编码的响应。

正如您在上面所读到的,这是FastAPI中使用的默认响应。

但您可以通过参数告诉使用HTMLResponseresponse_class类型:

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
Run Code Online (Sandbox Code Playgroud)

使用纯字符串 + HTMLResponse 输出

或者,为了更好地控制,请使用实际的 HTML 模板。FastAPI 支持 Jinja2 模板,请参阅FastAPI 模板部分。

项目/模板/output.html

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
Run Code Online (Sandbox Code Playgroud)

项目/main.py

<html>
<head>
</head>
<body>
    <p>This output should have a <br>line break.</p>
    <p>Other stuff: {{ stuff }}</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

使用 HTML 模板 + HTMLResponse 输出

通过 HTML 模板,您可以使用CSS 样式来保留换行符