国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

FastAPI學(xué)習(xí)-23.異常處理器 exception_handler

這篇具有很好參考價值的文章主要介紹了FastAPI學(xué)習(xí)-23.異常處理器 exception_handler。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

前言

通常我們可以通過 raise 拋出一個 HTTPException 異常,請求參數(shù)不合法會拋出RequestValidationError 異常,這是最常見的2種異常。

HTTPException 異常

向客戶端返回 HTTP 錯誤響應(yīng),可以使用?raise 觸發(fā)?HTTPException。

from fastapi import FastAPI, HTTPException

app = FastAPI()


@app.get("/path/{name}")  
async def read_unicorn(name: str):  
    if name == "yoyo":  
        raise HTTPException(404, detail=f"name: {name} not found")  
    return {"path_name": name}

默認(rèn)情況下返回json格式

HTTP/1.1 404 Not Found
date: Wed, 27 Sep 2023 02:07:07 GMT
server: uvicorn
content-length: 22
content-type: application/json

{"detail":"Not Found"}

覆蓋默認(rèn)的HTTPException 異常

查看HTTPException 異常相關(guān)源碼

from starlette.exceptions import HTTPException as StarletteHTTPException  
  
  
class HTTPException(StarletteHTTPException):  
    def __init__(  
        self,  
        status_code: int,  
        detail: Any = None,  
        headers: Optional[Dict[str, Any]] = None,  
    ) -> None:  
        super().__init__(status_code=status_code, detail=detail, headers=headers)

HTTPException 異常是繼承的 starlette 包里面的 HTTPException
覆蓋默認(rèn)異常處理器時需要導(dǎo)入?from starlette.exceptions import HTTPException as StarletteHTTPException,并用?@app.excption_handler(StarletteHTTPException)?裝飾異常處理器。

from fastapi import FastAPI, Request  
from fastapi.exceptions import HTTPException  
from fastapi.responses import PlainTextResponse, JSONResponse  
from starlette.exceptions import HTTPException as StarletteHTTPException  
  
  
app = FastAPI()  
  
  
# # 捕獲 HTTPException 異常  
@app.exception_handler(StarletteHTTPException)  
def http_error(request, exc):  
    print(exc.status_code)  
    print(exc.detail)  
    # return JSONResponse({'error_msg': exc.detail}, status_code=exc.status_code)  
    return PlainTextResponse(content=exc.detail, status_code=exc.status_code)  
  
  
@app.get("/path/{name}")  
async def read_unicorn(name: str):  
    if name == "yoyo":  
        raise HTTPException(404, detail=f"name: {name} not found")  
    return {"path_name": name}

這樣原來的 HTTPException 返回 json 格式,現(xiàn)在改成返回text/plain 文本格式了。

HTTP/1.1 404 Not Found
date: Wed, 27 Sep 2023 07:24:58 GMT
server: uvicorn
content-length: 20
content-type: text/plain; charset=utf-8

name: yoyo not found

覆蓋請求驗證異常

請求中包含無效數(shù)據(jù)時,FastAPI?內(nèi)部會觸發(fā)?RequestValidationError
該異常也內(nèi)置了默認(rèn)異常處理器。

覆蓋默認(rèn)異常處理器時需要導(dǎo)入?RequestValidationError,并用?@app.excption_handler(RequestValidationError)?裝飾異常處理器。

這樣,異常處理器就可以接收?Request?與異常。

from fastapi import FastAPI, HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.responses import PlainTextResponse
from starlette.exceptions import HTTPException as StarletteHTTPException

app = FastAPI()


@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
    return PlainTextResponse(str(exc), status_code=400)


@app.get("/items/{item_id}")
async def read_item(item_id: int):
    if item_id == 3:
        raise HTTPException(status_code=418, detail="Nope! I don't like 3.")
    return {"item_id": item_id}

訪問?/items/foo,可以看到以下內(nèi)容替換了默認(rèn) JSON 錯誤信息:

{
    "detail": [
        {
            "loc": [
                "path",
                "item_id"
            ],
            "msg": "value is not a valid integer",
            "type": "type_error.integer"
        }
    ]
}

以下是文本格式的錯誤信息:

HTTP/1.1 400 Bad Request
date: Wed, 27 Sep 2023 07:30:38 GMT
server: uvicorn
content-length: 103
content-type: text/plain; charset=utf-8

1 validation error for Request
path -> item_id
  value is not a valid integer (type=type_error.integer)

RequestValidationError 源碼分析

RequestValidationError 相關(guān)源碼

class RequestValidationError(ValidationError):  
    def __init__(self, errors: Sequence[ErrorList], *, body: Any = None) -> None:  
        self.body = body  
        super().__init__(errors, RequestErrorModel)

使用示例

from fastapi import FastAPI, Request, status
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel

app = FastAPI()


@app.exception_handler(RequestValidationError)  
async def validation_exception_handler(request: Request, exc: RequestValidationError):  
    print(exc.json())  
    print(exc.errors())  
    print(exc.body)   # 請求body  
    return JSONResponse(  
        status_code=400,  
        content=jsonable_encoder({"detail": exc.errors(), "body": exc.body}),  
    )  
  
  
class Item(BaseModel):  
    title: str  
    size: int  
  
  
@app.post("/items/")  
async def create_item(item: Item):  
    return item

現(xiàn)在試著發(fā)送一個無效的?item,例如:

{
  "title": "towel",
  "size": "XL"
}

運行結(jié)果

HTTP/1.1 400 Bad Request
date: Wed, 27 Sep 2023 07:51:36 GMT
server: uvicorn
content-length: 138
content-type: application/json

{"detail":[{"loc":["body","size"],"msg":"value is not a valid integer","type":"type_error.integer"}],"body":{"title":"towel","size":"XL"}}

RequestValidationError?和?ValidationError

如果您覺得現(xiàn)在還用不到以下技術(shù)細(xì)節(jié),可以先跳過下面的內(nèi)容。

RequestValidationError?是 Pydantic 的?ValidationError的子類。

FastAPI?調(diào)用的就是?RequestValidationError?類,因此,如果在?response_model?中使用 Pydantic 模型,且數(shù)據(jù)有錯誤時,在日志中就會看到這個錯誤。

但客戶端或用戶看不到這個錯誤。反之,客戶端接收到的是 HTTP 狀態(tài)碼為?500?的「內(nèi)部服務(wù)器錯誤」。

這是因為在_響應(yīng)_或代碼(不是在客戶端的請求里)中出現(xiàn)的 Pydantic?ValidationError?是代碼的 bug。

修復(fù)錯誤時,客戶端或用戶不能訪問錯誤的內(nèi)部信息,否則會造成安全隱患。文章來源地址http://www.zghlxwxcb.cn/news/detail-727778.html

到了這里,關(guān)于FastAPI學(xué)習(xí)-23.異常處理器 exception_handler的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進(jìn)行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • 【ARMv8 異常模型入門及漸進(jìn) 1 -- 處理器運行模式及EL3/EL2/EL1學(xué)習(xí)】

    【ARMv8 異常模型入門及漸進(jìn) 1 -- 處理器運行模式及EL3/EL2/EL1學(xué)習(xí)】

    下篇文章:ARMv8 異常模型入門及漸進(jìn) 2 - 通用寄存器介紹 在ARM v7架構(gòu)中的ARM核用 PL 的方式定義執(zhí)行等級。在ARMv8中ARM核的執(zhí)行等級劃分如下圖所示。 表 1-1 ARM v8中一個ARM core 運行時可能具有兩種狀態(tài):分別為 secure world normal world。 兩種狀態(tài)下都有其對應(yīng)的 EL0 , EL1 。 而 EL3 是

    2024年02月15日
    瀏覽(96)
  • SpringMVC之異常處理器

    SpringMVC提供了一個處理控制器方法執(zhí)行過程中所出現(xiàn)的異常的接口:HandlerExceptionResolver。 HandlerExceptionResolver接口的實現(xiàn)類有:DefaultHandlerExceptionResolver(默認(rèn)的)和 SimpleMappingExceptionResolver(自定義的)。 這里配置了兩個異常,出現(xiàn)其中一個異常后跳轉(zhuǎn)到error頁面。 以上就是異

    2024年02月10日
    瀏覽(24)
  • 13、SpringMVC之異常處理器

    13、SpringMVC之異常處理器

    創(chuàng)建名為spring_mvc_exception的新module,過程參考9.1節(jié)和9.5節(jié) SpringMVC 提供了一個處理控制器方法執(zhí)行異常的接口:HandlerExceptionResolver HandlerExceptionResolver 接口的實現(xiàn)類有:DefaultHandlerExceptionResolver 和 SimpleMappingExceptionResolver 實際工作中,有時使用 SimpleMappingExceptionResolver 異常解析器

    2024年02月05日
    瀏覽(25)
  • Spring MVC 異常處理器

    Spring MVC 異常處理器

    如果不加以異常處理,錯誤信息肯定會拋在瀏覽器頁面上,這樣很不友好,所以必須進(jìn)行異常處理。 系統(tǒng)的dao、service、controller出現(xiàn)都通過throws Exception向上拋出,最后由springmvc前端控制器交由異常處理器進(jìn)行異常處理,如下圖: 編寫controller 在index.jsp里面定義超鏈接

    2024年01月22日
    瀏覽(30)
  • Spring MVC配置全局異常處理器?。?!

    Spring MVC配置全局異常處理器?。?!

    為什么要使用全局異常處理器:如果不加以異常處理,錯誤信息肯定會拋在瀏覽器頁面上,這樣很不友好,所以必須進(jìn)行異常處理。 系統(tǒng)的dao、service、controller出現(xiàn)都通過throws Exception向上拋出,最后由springmvc前端控制器交由異常處理器進(jìn)行異常處理,如下圖: 結(jié)果展示: ?

    2024年01月15日
    瀏覽(16)
  • 【微服務(wù)網(wǎng)關(guān)---Gateway 的全局異常處理器】

    【微服務(wù)網(wǎng)關(guān)---Gateway 的全局異常處理器】

    Gateway網(wǎng)關(guān)統(tǒng)一全局異常處理操作 方便前端看到 這里要精細(xì)化翻譯,默認(rèn)返回用戶是看不懂的 所以需要配置一個 Gateway 的全局異常處理器 如果沒有網(wǎng)關(guān)全局異常的 會如下截圖 代碼如下: 代碼如下: 代碼如下: 以上就是今天要講的內(nèi)容,本文僅僅簡單 所以需要配置一個

    2024年02月12日
    瀏覽(19)
  • Spring Boot 如何自定義異常處理器

    Spring Boot 如何自定義異常處理器

    在Spring Boot應(yīng)用程序中,異常處理是一個非常重要的方面。如果您不處理異常,應(yīng)用程序可能會崩潰或出現(xiàn)不可預(yù)料的行為。默認(rèn)情況下,Spring Boot將未捕獲的異常返回給客戶端。這通常不是期望的行為,因為客戶端可能無法理解異常信息。在本文中,我們將介紹如何在Sprin

    2024年02月06日
    瀏覽(21)
  • SpringMVC的攔截器和異常處理器

    目錄 lerInterceptor 攔截器 1、攔截器的作用 2、攔截器的創(chuàng)建 3、攔截器的三個抽象方法 4、攔截器的配置 5、多個攔截器的執(zhí)行順序 SpringMVC的異常處理器 1、異常處理器概述 2、基于配置文件的異常處理 3、基于注解的異常處理 攔截器的作用時機(jī) SpringMVC的攔截器作用于? 控制器

    2024年02月02日
    瀏覽(41)
  • SpringMVC之?dāng)r截器和異常處理器

    學(xué)習(xí)的最大理由是想擺脫平庸,早一天就多一份人生的精彩;遲一天就多一天平庸的困擾。各位小伙伴,如果您: 想系統(tǒng)/深入學(xué)習(xí)某技術(shù)知識點… 一個人摸索學(xué)習(xí)很難堅持,想組團(tuán)高效學(xué)習(xí)… 想寫博客但無從下手,急需寫作干貨注入能量… 熱愛寫作,愿意讓自己成為更好

    2024年02月03日
    瀏覽(21)
  • [ARM 匯編]進(jìn)階篇—異常處理與中斷—2.4.2 ARM處理器的異常向量表

    [ARM 匯編]進(jìn)階篇—異常處理與中斷—2.4.2 ARM處理器的異常向量表

    異常向量表簡介 在ARM架構(gòu)中,異常向量表是一組固定位置的內(nèi)存地址,它們包含了處理器在遇到異常時需要跳轉(zhuǎn)到的處理程序的入口地址。每個異常類型都有一個對應(yīng)的向量地址。當(dāng)異常發(fā)生時,處理器會自動跳轉(zhuǎn)到對應(yīng)的向量地址,并開始執(zhí)行異常處理程序。 異常向量表

    2024年02月09日
    瀏覽(89)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包