在FastAPI中改變響應狀態(tài)碼的兩種方法
引言
FastAPI,顧名思義,是一個快速、現(xiàn)代、高性能的web框架,用于用Python構(gòu)建后端api。響應狀態(tài)碼是一個三位數(shù),表示請求的結(jié)果。例如,200表示OK, 404表示未找到,500表示服務器內(nèi)部錯誤。默認情況下,F(xiàn)astAPI將為成功請求返回200狀態(tài)碼,為驗證錯誤返回422狀態(tài)碼。
但是,有時你可能希望更改狀態(tài)碼以指示不同的結(jié)果。例如,你可能希望為創(chuàng)建新資源的成功POST請求返回201狀態(tài)碼,或者為無法找到所請求資源的GET請求返回404狀態(tài)碼。在這篇簡明的基于示例的博文中,我將向你展示在FastAPI中更改響應狀態(tài)代碼的兩種不同方法。
使用路由裝飾器的status_code參數(shù)
要更改FastAPI中的響應狀態(tài)代碼,可以使用@app中的status_code參數(shù)。@app.get, @app.post 或其他路由裝飾器。status_code參數(shù)接受來starlette.status模塊的整數(shù)值或常量。例如,要為創(chuàng)建新用戶的POST請求返回201狀態(tài)碼,你可以如下所示:
from fastapi import FastAPI
from starlette.status import HTTP_201_CREATED
# create the FastAPI instance
app = FastAPI()
# set the status code to 201
@app.post("/users", status_code=HTTP_201_CREATED)
def create_user(name: str):
# some logic to create a new user
return {"name": name}
在上面的代碼片段中,我從starlette.status模塊中導入了常量HTTP_201_CREATED。starlette.status模塊是starlette框架的一部分,它是FastAPI的一個依賴。starlette.status模塊為常見的HTTP狀態(tài)碼提供常量,如HTTP_200_OK、HTTP_404_NOT_FOUND等。使用這些常量可以使代碼更具可讀性,并避免拼寫錯誤或錯誤。例如,我可以寫status_code=HTTP_201_CREATED,而不是寫status_code=201,這樣更具描述性和清晰度。
運行下面命令重啟服務:
uvicorn main:app --reload
然后去http://localhost:8000/docs, 可以看到文檔中code的值與我們配置的一致,方便用戶調(diào)試程序。
使用響應對象
在這種方法中,我們使用fastapi模塊中的Response對象在函數(shù)體中動態(tài)設(shè)置狀態(tài)碼。Response對象有status_code屬性,你可以從starlette.status模塊中分配整數(shù)值或常量狀態(tài)值。
下面的例子返回404狀態(tài)碼的GET請求,不能找到被請求的用戶:
from fastapi import FastAPI, Response
from starlette.status import HTTP_404_NOT_FOUND, HTTP_200_OK
app = FastAPI()
@app.get("/users/{user_id}")
def get_user(user_id: int, response: Response):
# some logic to get the user by id
user = None
if user is None:
# set the status code
response.status_code = HTTP_404_NOT_FOUND
return {"detail": "User not found"}
else:
# set the status code
response.status_code = HTTP_200_OK
return user
查看文檔,效果與上面一樣。
完整實戰(zhàn)案例
這是一個完整的代碼示例,展示了如何在不同的場景下更改FastAPI中的響應狀態(tài)代碼:
# main.py
from fastapi import FastAPI, Response
from starlette.status import HTTP_201_CREATED, HTTP_404_NOT_FOUND
app = FastAPI()
# A mock database of users
users = [
{"id": 1, "name": "Sling Academy"},
{"id": 2, "name": "Ranni the Witch"},
{"id": 3, "name": "Khue"},
]
# A helper function to get a user by id
def get_user_by_id(user_id: int):
for user in users:
if user["id"] == user_id:
return user
return None
# A POST route to create a new user and return a 201 status code
@app.post("/users", status_code=HTTP_201_CREATED)
def create_user(name: str):
# some logic to create a new user and add it to the database
new_user = {"id": len(users) + 1, "name": name}
users.append(new_user)
return new_user
# A GET route to get a user by id and return either a 200 or a 404 status code
@app.get("/users/{user_id}")
def get_user(user_id: int, response: Response):
# some logic to get the user by id from the database
user = get_user_by_id(user_id)
if user is None:
response.status_code = HTTP_404_NOT_FOUND
return {"detail": "User not found"}
else:
return user
最后總結(jié)
在本文中,我解釋了如何使用兩種方法在FastAPI中更改響應狀態(tài)代碼:路由裝飾器中的status_code參數(shù)和函數(shù)體中的response對象。你可以根據(jù)自己的需要和偏好使用任何一種方法。更改響應狀態(tài)碼可以幫助您更清楚地與客戶端進行通信,并遵循RESTful API設(shè)計的最佳實踐。
以上就是在FastAPI中改變響應狀態(tài)碼的兩種方法的詳細內(nèi)容,更多關(guān)于FastAPI改變響應狀態(tài)碼的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python機器學習pytorch自定義數(shù)據(jù)加載器
這篇文章主要為大家介紹了python機器學習pytorch自定義數(shù)據(jù)加載器使用示例學習,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-10-10
python繞過圖片滑動驗證碼實現(xiàn)爬取PTA所有題目功能 附源碼
這篇文章主要介紹了python繞過圖片滑動驗證碼實現(xiàn)爬取PTA所有題目 附源碼,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-01-01
pandas?dataframe獲取所有行名稱與列名稱方法示例
這篇文章主要給大家介紹了關(guān)于pandas?dataframe獲取所有行名稱與列名稱的相關(guān)資料,Pandas是Python中用于數(shù)據(jù)分析的非常重要的庫,它提供了多種方法來獲取列名,需要的朋友可以參考下2023-09-09
使用Python制作一個數(shù)據(jù)預處理小工具(多種操作一鍵完成)
這篇文章主要介紹了使用Python制作一個數(shù)據(jù)預處理小工具(多種操作一鍵完成),本文通過圖文實例相結(jié)合給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-02-02

