問題:
對方是要的訊息Hello World,不是要”Hello World”
原本的FastAPI寫法如下:
from fastapi import FastAPI
import uvicorn
app = FastAPI()
@app.get("/")
async def root():
return "Hello World"
if __name__ == "__main__":
uvicorn.run("main:app", host="127.0.0.1", port=8000)
可以看到最常見的postman發的請求得到是”Hello World”
解決方式:
使用:PlainTextResponse
from fastapi import FastAPI
import uvicorn
from fastapi.responses import PlainTextResponse
app = FastAPI()
@app.get("/", response_class=PlainTextResponse)
async def root():
return "Hello World"
if __name__ == "__main__":
uvicorn.run("main:app", host="127.0.0.1", port=8000)
可以看到還滿順利的出現了單純只有文字的Hello World
不一定要放在response_class,以下方式也能成功:
from fastapi import FastAPI
import uvicorn
from fastapi.responses import PlainTextResponse
app = FastAPI()
def get_text(parameters):
text = PlainTextResponse(parameters)
return text
@app.get("/")
async def root():
op = get_text('hello bocky')
return op
if __name__ == "__main__":
uvicorn.run("main:app", host="127.0.0.1", port=8000)