在FastAPI中改變響應(yīng)狀態(tài)碼的兩種方法
引言
FastAPI,顧名思義,是一個快速、現(xiàn)代、高性能的web框架,用于用Python構(gòu)建后端api。響應(yīng)狀態(tài)碼是一個三位數(shù),表示請求的結(jié)果。例如,200表示OK, 404表示未找到,500表示服務(wù)器內(nèi)部錯誤。默認(rèn)情況下,F(xiàn)astAPI將為成功請求返回200狀態(tài)碼,為驗證錯誤返回422狀態(tài)碼。
但是,有時你可能希望更改狀態(tài)碼以指示不同的結(jié)果。例如,你可能希望為創(chuàng)建新資源的成功POST請求返回201狀態(tài)碼,或者為無法找到所請求資源的GET請求返回404狀態(tài)碼。在這篇簡明的基于示例的博文中,我將向你展示在FastAPI中更改響應(yīng)狀態(tài)代碼的兩種不同方法。
使用路由裝飾器的status_code參數(shù)
要更改FastAPI中的響應(yīng)狀態(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模塊中導(dǎo)入了常量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,這樣更具描述性和清晰度。
運(yùn)行下面命令重啟服務(wù):
uvicorn main:app --reload
然后去http://localhost:8000/docs, 可以看到文檔中code的值與我們配置的一致,方便用戶調(diào)試程序。
使用響應(yīng)對象
在這種方法中,我們使用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中的響應(yīng)狀態(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中更改響應(yīng)狀態(tài)代碼:路由裝飾器中的status_code參數(shù)和函數(shù)體中的response對象。你可以根據(jù)自己的需要和偏好使用任何一種方法。更改響應(yīng)狀態(tài)碼可以幫助您更清楚地與客戶端進(jìn)行通信,并遵循RESTful API設(shè)計的最佳實踐。
以上就是在FastAPI中改變響應(yīng)狀態(tài)碼的兩種方法的詳細(xì)內(nèi)容,更多關(guān)于FastAPI改變響應(yīng)狀態(tài)碼的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python中的魔術(shù)方法Magic?Methods使用實例全面指南
在Python中,魔術(shù)方法Magic?Methods是一種特殊的方法,它們以雙下劃線開頭和結(jié)尾,如__init__、__str__等,這些方法允許定制類的行為,使得對象更具有靈活性和可定制性,本文將深入探討Python中一些常用的魔術(shù)方法,以及如何使用它們來定制類與對象2024-01-01Python實現(xiàn)單例模式的多種方法總結(jié)
單例模式是最常使用的一種設(shè)計模式,該模式的目的是確保在一個系統(tǒng)中,一個類只有一個實例,本文給大家介紹了Python實現(xiàn)單例模式的完整指南:原理、方法與最佳實踐,需要的朋友可以參考下2025-04-04