使用Fastapi封装模型

本文介绍了如何使用FastAPI构建一个API服务,封装TensorFlow的图片分类模型。服务包括一个接收图片进行预测的POST接口和一个健康检查接口,ASGI服务器使用uvicorn。此外,还展示了文件夹结构和调试接口。
摘要由CSDN通过智能技术生成

fastapi封装模型

FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 3.6+ 并基于标准的 Python 类型提示
百度网盘:
链接:https://pan.baidu.com/s/1WsdHNxd9dzV-q_kKmSlRrg
提取码:l2w7

安装

pip install fastapi

ASGI 服务器可以使用uvicorn:

pip install uvicorn[standard]

封装的服务

实现使用fastapi封装tensorflow框架的图片分类模型

具体介绍:

# 使用Fastapi框架
app = FastAPI(title='Tensorflow FastAPI Starter Pack', description=app_desc)

# 定义get请求
@app.get("/", include_in_schema=False)
async def index():
    return RedirectResponse(url="/docs")

# 定义post请求
@app.post("/predict/image")
async def predict_api(file: UploadFile = File(...)):
    extension = file.filename.split(".")[-1] in ("jpg", "jpeg", "png")
    if not extension:
        return "Image must be jpg or png format!"
    image = read_imagefile(await file.read())
    # 获得预测代码及模型
    prediction = predict(image)
	# 返回模型结果
    return prediction

# 第二个post请求
@app.post("/api/covid-symptom-check")
def check_risk(symptom: Symptom):
    return symptom_check.get_risk_level(symptom)

# 平台要求定时获取服务状态
@app.route("/health", methods=["GET"])
def health_check():
    return jsonify({"health": True})

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8080)

文件夹结构说明:

tensorflow-fastapi-starter-pack-master
	|-- components
		|-- prediction
			|-- serve_model.py      # 对应模型文件
			|-- symptom_check.py
		|-- __init__.py
	|-- server
		|-- main.py
	|-- __init__.py
	|-- main.py              # 服务执行文件
	|-- schema.py

以上文件夹可扩展,可以新建对应文件夹,例如模型保存文件夹等

调试接口

http://ip:端口/docs/
在这里插入图片描述

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值