【问题标题】:How to return a response with a line break using FastAPI?如何使用 FastAPI 返回带有换行符的响应?
【发布时间】:2021-07-06 22:50:14
【问题描述】:
@app.get('/status')
def get_func(request: Request):
  output = 'this output should have a line break'
  return output

我尝试过的事情:

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

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

【问题讨论】:

    标签: python python-3.x fastapi


    【解决方案1】:

    只有当响应是 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

    【讨论】:

      【解决方案2】:

      使用 response_class=PlainTextResponse

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

      【讨论】:

        猜你喜欢
        • 2022-01-01
        • 2020-07-23
        • 2022-08-02
        • 2021-03-25
        • 2019-08-25
        • 1970-01-01
        • 2018-02-22
        • 2016-06-05
        • 2022-10-02
        相关资源
        最近更新 更多