简体   繁体   中英

How to return a response with a line break using FastAPI?

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

Things I've tried:

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

The text itself is returned and I don't get the line break.

Use response_class=PlainTextResponse

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

A line break only makes sense if the response is an HTML response (ie an HTML page). And a \n does not render properly as new lines or line breaks, you have to use <br> or an HTML template + some CSS styling to preserve line breaks .

FastAPI returns, by default, a JSONResponse type .

Takes some data and returns an application/json encoded response.

This is the default response used in FastAPI , as you read above.

But you can tell it to 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

使用纯字符串 + HTMLResponse 输出

Or, for better control, use an actual HTML template. FastAPI supports Jinja2 templates, see section on 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 模板 + HTMLResponse 输出

With HTML templates, you can then use CSS styling to preserve line breaks .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM