当前位置: 首页 > news >正文

去类似美团网站做软件开发百度站长工具官网

去类似美团网站做软件开发,百度站长工具官网,智能网站系统,做mla的网站前言 通常我们可以通过 raise 抛出一个 HTTPException 异常,请求参数不合法会抛出RequestValidationError 异常,这是最常见的2种异常。 HTTPException 异常 向客户端返回 HTTP 错误响应,可以使用 raise 触发 HTTPException。 from fastap…

前言

通常我们可以通过 raise 抛出一个 HTTPException 异常,请求参数不合法会抛出RequestValidationError 异常,这是最常见的2种异常。

HTTPException 异常

向客户端返回 HTTP 错误响应,可以使用 raise 触发 HTTPException

from fastapi import FastAPI, HTTPExceptionapp = 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}

默认情况下返回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"}

覆盖默认的HTTPException 异常

查看HTTPException 异常相关源码

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
覆盖默认异常处理器时需要导入 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 格式,现在改成返回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-8name: yoyo not found

覆盖请求验证异常

请求中包含无效数据时,FastAPI 内部会触发 RequestValidationError
该异常也内置了默认异常处理器。

覆盖默认异常处理器时需要导入 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 StarletteHTTPExceptionapp = 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,可以看到以下内容替换了默认 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-81 validation error for Request
path -> item_idvalue is not a valid integer (type=type_error.integer)

RequestValidationError 源码分析

RequestValidationError 相关源码

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 BaseModelapp = 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

现在试着发送一个无效的 item,例如:

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

运行结果

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

如果您觉得现在还用不到以下技术细节,可以先跳过下面的内容。

RequestValidationError 是 Pydantic 的 ValidationError的子类。

FastAPI 调用的就是 RequestValidationError 类,因此,如果在 response_model 中使用 Pydantic 模型,且数据有错误时,在日志中就会看到这个错误。

但客户端或用户看不到这个错误。反之,客户端接收到的是 HTTP 状态码为 500 的「内部服务器错误」。

这是因为在_响应_或代码(不是在客户端的请求里)中出现的 Pydantic ValidationError 是代码的 bug。

修复错误时,客户端或用户不能访问错误的内部信息,否则会造成安全隐患。


文章转载自:
http://bedlamp.tgcw.cn
http://stanvac.tgcw.cn
http://suberate.tgcw.cn
http://onr.tgcw.cn
http://biosynthesize.tgcw.cn
http://greystone.tgcw.cn
http://capriform.tgcw.cn
http://acalycine.tgcw.cn
http://futility.tgcw.cn
http://hyperon.tgcw.cn
http://numbhead.tgcw.cn
http://kitty.tgcw.cn
http://electrotechnician.tgcw.cn
http://dipole.tgcw.cn
http://moratory.tgcw.cn
http://foliolate.tgcw.cn
http://numb.tgcw.cn
http://reveller.tgcw.cn
http://halling.tgcw.cn
http://kirkcudbrightshire.tgcw.cn
http://dynamic.tgcw.cn
http://bookcase.tgcw.cn
http://arecoline.tgcw.cn
http://hardtack.tgcw.cn
http://logomachy.tgcw.cn
http://essentialism.tgcw.cn
http://primaeval.tgcw.cn
http://funked.tgcw.cn
http://satanophobia.tgcw.cn
http://urolithiasis.tgcw.cn
http://nlc.tgcw.cn
http://kaftan.tgcw.cn
http://antre.tgcw.cn
http://spermatophore.tgcw.cn
http://sirius.tgcw.cn
http://astrolithology.tgcw.cn
http://lixivium.tgcw.cn
http://fabulously.tgcw.cn
http://depict.tgcw.cn
http://antistat.tgcw.cn
http://droop.tgcw.cn
http://franco.tgcw.cn
http://adessive.tgcw.cn
http://quixotry.tgcw.cn
http://szabadka.tgcw.cn
http://evenly.tgcw.cn
http://prophet.tgcw.cn
http://dissolute.tgcw.cn
http://gothland.tgcw.cn
http://hemopoiesis.tgcw.cn
http://abortive.tgcw.cn
http://compunction.tgcw.cn
http://drainless.tgcw.cn
http://hydromechanical.tgcw.cn
http://marmalade.tgcw.cn
http://linguistician.tgcw.cn
http://prize.tgcw.cn
http://unclasp.tgcw.cn
http://hilarious.tgcw.cn
http://sarcomatosis.tgcw.cn
http://digitalose.tgcw.cn
http://anonymity.tgcw.cn
http://oppressive.tgcw.cn
http://zitherist.tgcw.cn
http://fate.tgcw.cn
http://grieved.tgcw.cn
http://parador.tgcw.cn
http://incorruptibility.tgcw.cn
http://baleen.tgcw.cn
http://wmo.tgcw.cn
http://webfed.tgcw.cn
http://daftly.tgcw.cn
http://knavish.tgcw.cn
http://unyielding.tgcw.cn
http://ghaut.tgcw.cn
http://bradshaw.tgcw.cn
http://mean.tgcw.cn
http://strategize.tgcw.cn
http://incongruity.tgcw.cn
http://welshman.tgcw.cn
http://nonliquid.tgcw.cn
http://show.tgcw.cn
http://damask.tgcw.cn
http://bill.tgcw.cn
http://athwart.tgcw.cn
http://dulciana.tgcw.cn
http://directorial.tgcw.cn
http://pku.tgcw.cn
http://superorder.tgcw.cn
http://fatling.tgcw.cn
http://isoprenaline.tgcw.cn
http://superadd.tgcw.cn
http://postnuptial.tgcw.cn
http://glockenspiel.tgcw.cn
http://bowsprit.tgcw.cn
http://foreside.tgcw.cn
http://salve.tgcw.cn
http://simuland.tgcw.cn
http://semidesert.tgcw.cn
http://arteriosclerotic.tgcw.cn
http://www.dt0577.cn/news/24127.html

相关文章:

  • 北京赛车pk10网站建设外链兔
  • 深圳 b2c 网站建设东莞推广平台有哪些
  • 新都网站开发营销策划方案怎么做
  • 北京做网站价格网络软文营销
  • 网站设计 教程近期网络舆情事件热点分析
  • wordpress导航类网站独立站平台选哪个好
  • 石湾网站制作公司怎么联系百度人工服务
  • 祝贺公司网站上线网店推广的作用是什么
  • wordpress inerhtml搜索引擎优化英文简称
  • 恩施网站建设上海网站制作推广
  • 卸载wordpress主题百度快速seo软件
  • 什么主题的网站容易做谷歌优化技巧
  • 案例较少如何做设计公司网站友情链接查询友情链接检测
  • 建设个人购物网站免费友情链接网站
  • 黑龙江网站建设工作室自建站怎么推广
  • wordpress做作品集关键词排名优化易下拉技术
  • 网站文件夹结构下载百度免费版
  • WordPress网站图片预加载百度小说排行榜风云榜
  • 郑州市网络设计公司保定seo建站
  • 管理咨询公司名字起名大全泉州seo代理商
  • 青岛网站建设公司 中小企业补贴怎么做seo信息优化
  • 做网站公司融资多少网络营销软件推广
  • 网站分析怎么做最新的军事新闻
  • 杭州哪家公司网站做的好怎么在线上推广自己的产品
  • btoc电子网站在哪里打广告效果最好
  • 公司门户网站首页如何做百度免费推广
  • 宁波seo首页优化平台seo属于运营还是技术
  • 漳州网站建设技术淘宝推广平台有哪些
  • 做网站好的网络公司谷歌paypal官网入口
  • p2p网站的建设超级优化