[FastAPI-41]文本相关的Response-PlainTextResponse-HTMLResponse

发布时间 2023-03-30 14:25:36作者: LeoShi2020

1.PlainTextResponse用来响应纯文本的数据

from fastapi import FastAPI
from fastapi.responses import PlainTextResponse

app = FastAPI()


@app.get("/", response_class=PlainTextResponse)
def main():
    return "Hello World"

2.HTMLResponse用来响应HTML页面

from fastapi import FastAPI
from fastapi.responses import HTMLResponse

app = FastAPI()


@app.get("/")
def index():
    html_content = """
    <html>
        <head>
            <title>Some HTML in here</title>
        </head>
        <body>
            <h1>Look ma! HTML!</h1>
        </body>
    </html>
    """
    return HTMLResponse(content=html_content, status_code=200)