通过抛出HTTPException,你可以控制返回给客户端的HTTP状态码和响应体,使得客户端能够根据这些信息作出相应的处理。 一、简单用法 fromfastapiimportAPIRouter,HTTPException@user.get('/book')asyncdefboot():raiseHTTPException(status_code=500,detail='this is a test')# 客户端调用输出:# 状态码status_code:500# b...
asyncdefread_item(item_id: str):ifitem_idnotinitems:raiseHTTPException(status_code=404, detail="Item not found")return{"item": items[item_id]} 二、添加自定义头信息 有时候针对HTTP错误,在一些场景下,我们需要添加自定义头信息。 fromfastapiimportFastAPI, HTTPException app=FastAPI() items= {"foo"...
向客户端返回 HTTP 错误响应,可以使用HTTPException。 导入HTTPException¶ Python 3.8+ fromfastapiimportFastAPI,HTTPExceptionapp=FastAPI()items={"foo":"The Foo Wrestlers"}@app.get("/items/{item_id}")asyncdefread_item(item_id:str):ifitem_idnotinitems:raiseHTTPException(status_code=404,detail="Item...
="MinChess":returnHTTPException(status_code=404,detail="not found")return{"name":"MinChess","age":22,"Blog":"https://blog.jiumoz.com"} 从fastapi中导入HTTPException,并在路径操作函数中进行判断输出即可; 上面的代码就是当输入的id不为MinChess的时候抛出错误,错误代码为404,详细信息为not found 添加...
from fastapi import FastAPI, HTTPException exceptions = HTTPException(status_code=400, detail='请求格式错误') 从定义中可以看出,该异常的代码为HTTPException类型,状态码为 400,详细信息为“请求格式错误”。 异常处理 当遇到响应验证错误异常时,FastAPI 框架会自动创建一个响应异常类FastAPIException,该异常类继承自...
app=FastAPI()items={"test":"雷子说测试开发"}@app.get("/items/{item_id}")defread_item(item_id:str):ifitem_id notinitems:raiseHTTPException(status_code=404,detail="Item not found",headers={"X-Error":"NADOR"},)return{"item":items[item_id]}结果如下: ...
= credentials.password:raiseHTTPException(status_code=401, detail="鉴权失败")return{"message":"鉴权成功"}# 公开路由@app.get("/")asyncdefpublic_data():""" 公开路由示例 :return: 一个公开的消息,无需鉴权 """return{"message":"这是一个公开的路由,无需鉴权"}if__name__ =="__main__":...
当你在路由中,甚至在简单的业务代码中也可以raise一个HTTPException或者是派生至HTTPException的异常,从而向endpoint用户传递友好的异常信息。 当客户端请求一个不存在的item时,触发状态码为404的异常:raise HTTPException(status_code=404, detail="Item not found") ...
__init__(status_code=status_code, detail=detail) self.headers = headers 所以我们对于异常通常可以直接的使用 raise来抛出异常。 HTTPException且返回新增自定义请求头 代码语言:javascript 代码运行次数:0 运行 AI代码解释 import uvicorn from fastapi import FastAPI, HTTPException app = FastAPI() items = {"...
super().__init__(status_code=status_code, detail=detail, headers=headers) 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. HTTPException 异常是继承的 starlette 包里面的HTTPException覆盖默认异常处理器时需要导入from starlette.exceptions import HTTPException as StarletteHTTPException,并用@app.excption_hand...