原则:
输入输出都基于BaseModel依靠JSONResponse制定返回错误的json信息依靠装饰器中@app.post制定responses字典从而让docs文档更丰富 import uvicornfrom pydantic import BaseModel, Fieldfrom fastapi import FastAPI, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom transformers import BlipProcessor, BlipForConditionalGenerationfrom fastapi.responses import JSONResponsefrom PIL import Imageimport ioimport base64class UpscalerRequest(BaseModel):base64_image: str = Field(...,title="Base64 Encoded Image",description="The base64-encoded image that you want to upscale.")outscale: float = Field(...,ge=1.0, # 大于等于1.0le=5.0, # 小于等于5.0title="Upscale Factor",description="The scaling factor for image upscaling. Should be between 1.0 and 5.0.")class UpscalerResponse(BaseModel):base64_image_out: str = Field(...,title="Base64 Encoded Upscaled Image",description="The base64-encoded image after upscaling.")class CustomErrorResponse:def __init__(self, description: str, error_code: int, detail: str):self.description = descriptionself.error_code = error_codeself.detail = detaildef to_response_dict(self):return {"description": self.description,"content": {"application/json": {"example": {"error_code": self.error_code, "detail": self.detail}}},}def __call__(self, extra_detail=None):if extra_detail is not None:self.detail = f"detail:{self.detail}, extra_detail:{extra_detail}"return JSONResponse(content={"error_code": self.error_code, "detail": self.detail}, status_code=self.error_code)image_upscaler_CustomErrorResponse = CustomErrorResponse("超分执行错误", 501, "upscale error")@app.post("/image_upscaler", response_model=UpscalerResponse, summary="Image Upscaler",responses={501: image_upscaler_CustomErrorResponse.to_response_dict()})def image_upscaler(request: UpscalerRequest):"""Image Upscaler.Parameters:- `base64_image`: The base64-encoded image.- `outscale`: The scaling factor for image upscaling (between 1.0 and 5.0).Returns:- `output`: The base64-encoded upscaled image.Example:```pythonimport requestsimport base64from PIL import Imagefrom io import BytesIO# 1. 读取图像文件并转换为base64字符串image_path = "car.png"with open(image_path, "rb") as image_file:base64_image = base64.b64encode(image_file.read()).decode("utf-8")# 2. 构造请求数据outpainting_request = {"base64_image": base64_image,"outscale": 3,}# 3. 发送HTTP POST请求api_url = "http://home.elvisiky.com:7862/image_upscaler"response = requests.post(api_url, json=outpainting_request)# 4. 处理响应if response.status_code == 200:result_data = response.json()# 5. 保存base64编码的图像为文件detected_map_base64 = result_data["base64_image_out"]detected_map_image = Image.open(BytesIO(base64.b64decode(detected_map_base64)))detected_map_image.save("base64_image_out.png")print("图像保存成功!")else:print(f"API调用失败,HTTP状态码:{response.status_code}")print(response.json())```"""try:base64_image = request.base64_imagelogging.info(f"image_upscaler, image length {len(base64_image)}")img = decode_image_from_base64(base64_image)img_cv2 = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)output = enhance_image(img_cv2, outscale=request.outscale)if output is None:return image_upscaler_CustomErrorResponse()else:output_base64 = base64.b64encode(cv2.imencode('.png', output)[1]).decode('utf-8')return {"base64_image_out": output_base64}except Exception as e:return image_upscaler_CustomErrorResponse(str(e))if __name__ == '__main__':uvicorn.run(f'{os.path.basename(__file__).split(".")[0]}:app',host='0.0.0.0',port=7862,reload=False,workers=1)【python FastAPI】fastapi中如何限制输入参数,如何让docs更好看,如何自定义错误码json返回,智器v5
0evadmin
编程语言
2
文件名:【python FastAPI】fastapi中如何限制输入参数,如何让docs更好看,如何自定义错误码json返回,智器v5
【python FastAPI】fastapi中如何限制输入参数,如何让docs更好看,如何自定义错误码json返回
同类推荐
-

【Python CheckiO 题解】Sort Array by Element Frequency,赛扬d2.66
查看 -

【Python 千题 —— 基础篇】学生名单,x32u
查看 -

【Python3 SelectKBest 调用personer出现的错误】,k750i
查看 -

【Python3】【力扣题】268. 丢失的数字,幻想曲手机报价
查看 -

【Python_PySide2学习笔记(十八)】勾选按钮QCheckBox类的基本用法,漫步者m12
查看 -

【Python】Python读Excel文件生成xml文件,vivo x1st
查看 -

【Python】SqlmapAPI调用实现自动化SQL注入安全检测,htc p860
查看 -

【Python】urllib爬取动漫图片,推荐几个安全没封的网站2021(python爬取动态网页图片)
查看 -

【Python】一文带你掌握数据容器之集合,字典,康佳梵高手机
查看
控制面板
网站分类
搜索
最新留言
文章归档
网站收藏
友情链接