当前位置 博文首页 > cumtchw:python封装http接口——FastApi

    cumtchw:python封装http接口——FastApi

    作者:[db:作者] 时间:2021-07-28 15:11

    目录

    1.代码

    1.1main.py

    1.2start.sh?

    bug1------[TypeError("'numpy.int64' object is not iterable")

    bug2------"msg": "value is not a valid dict",


    1.代码

    1.1main.py

    import os
    import sys
    import uvicorn
    import numpy as np
    import cv2
    import glob
    import datetime
    import json
    import shutil
    
    
    from eval import *
    
    
    from pydantic import BaseModel
    from fastapi import FastAPI
    
    
    #args = ret_args()
    args.image = "00000.jpg:0.png"
    
    with torch.no_grad():
        if not os.path.exists('results'):
            os.makedirs('results')
    
        if args.cuda:
            cudnn.fastest = True
            torch.set_default_tensor_type('torch.cuda.FloatTensor')
        else:
            torch.set_default_tensor_type('torch.FloatTensor')
    
        if args.resume and not args.display:
            with open(args.ap_data_file, 'rb') as f:
                ap_data = pickle.load(f)
            calc_map(ap_data)
            exit()
    
        if args.image is None and args.video is None and args.images is None:
            dataset = COCODetection(cfg.dataset.valid_images, cfg.dataset.valid_info,
                                    transform=BaseTransform(), has_gt=cfg.dataset.has_gt)
            prep_coco_cats()
        else:
            dataset = None        
    
        print('Loading model...', end='')
        global net
        net = Yolact()
        net.load_weights(args.trained_model)
        net.eval()
        print(' Done.')
    
        if args.cuda:
            net = net.cuda()
    
    '''
    with torch.no_grad():
        args.image = "00000.jpg:0.png"
        print("args.image:::", args.image)
        evaluate(net, dataset)
    '''
    
    
    app = FastAPI()
    
    
    class Item_setmentation(BaseModel):
        img_url: str = None
    
    
    
    @app.post('/LABEL/segmentation')
    def label(request_data: Item_setmentation):
        print("coming into /AIPEX/labelimg !!!")
        img_url = request_data.img_url
        print(img_url)
        
        seg_res = {}
        with torch.no_grad():
            args.image = img_url + ":0.png"
            print("args.image:::", args.image)
            seg_res = evaluate(net, dataset)
            
            print("seg_res in post api::::", seg_res)
       
        return seg_res
    
    if __name__ == '__main__':
        uvicorn.run(app=app,
                    host="0.0.0.0",
                    port=8091,
                    workers=1)
    
    

    1.2start.sh?

    uvicorn main:app --host 0.0.0.0 --port 8091

    bug1------[TypeError("'numpy.int64' object is not iterable")

    上面的代码我打印出来seg_res内容如下:

    看着是没问题的,但是我用postman调试之后发现http服务返回错误,错误提示如下:

    INFO:     172.31.8.112:33098 - "POST /LABEL/segmentation HTTP/1.1" 500 Internal Server Error
    ERROR:    Exception in ASGI application
    Traceback (most recent call last):
      File "/root/anaconda3/envs/yolat_seg_chw/lib/python3.7/site-packages/uvicorn/protocols/http/h11_impl.py", line 396, in run_asgi
        result = await app(self.scope, self.receive, self.send)
      File "/root/anaconda3/envs/yolat_seg_chw/lib/python3.7/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
        return await self.app(scope, receive, send)
      File "/root/anaconda3/envs/yolat_seg_chw/lib/python3.7/site-packages/fastapi/applications.py", line 199, in __call__
        await super().__call__(scope, receive, send)
      File "/root/anaconda3/envs/yolat_seg_chw/lib/python3.7/site-packages/starlette/applications.py", line 112, in __call__
        await self.middleware_stack(scope, receive, send)
      File "/root/anaconda3/envs/yolat_seg_chw/lib/python3.7/site-packages/starlette/middleware/errors.py", line 181, in __call__
        raise exc from None
      File "/root/anaconda3/envs/yolat_seg_chw/lib/python3.7/site-packages/starlette/middleware/errors.py", line 159, in __call__
        await self.app(scope, receive, _send)
      File "/root/anaconda3/envs/yolat_seg_chw/lib/python3.7/site-packages/starlette/exceptions.py", line 82, in __call__
        raise exc from None
      File "/root/anaconda3/envs/yolat_seg_chw/lib/python3.7/site-packages/starlette/exceptions.py", line 71, in __call__
        await self.app(scope, receive, sender)
      File "/root/anaconda3/envs/yolat_seg_chw/lib/python3.7/site-packages/starlette/routing.py", line 580, in __call__
        await route.handle(scope, receive, send)
      File "/root/anaconda3/envs/yolat_seg_chw/lib/python3.7/site-packages/starlette/routing.py", line 241, in handle
        await self.app(scope, receive, send)
      File "/root/anaconda3/envs/yolat_seg_chw/lib/python3.7/site-packages/starlette/routing.py", line 52, in app
        response = await func(request)
      File "/root/anaconda3/envs/yolat_seg_chw/lib/python3.7/site-packages/fastapi/routing.py", line 218, in app
        is_coroutine=is_coroutine,
      File "/root/anaconda3/envs/yolat_seg_chw/lib/python3.7/site-packages/fastapi/routing.py", line 137, in serialize_response
        return jsonable_encoder(response_content)
      File "/root/anaconda3/envs/yolat_seg_chw/lib/python3.7/site-packages/fastapi/encoders.py", line 96, in jsonable_encoder
        sqlalchemy_safe=sqlalchemy_safe,
      File "/root/anaconda3/envs/yolat_seg_chw/lib/python3.7/site-packages/fastapi/encoders.py", line 113, in jsonable_encoder
        sqlalchemy_safe=sqlalchemy_safe,
      File "/root/anaconda3/envs/yolat_seg_chw/lib/python3.7/site-packages/fastapi/encoders.py", line 96, in jsonable_encoder
        sqlalchemy_safe=sqlalchemy_safe,
      File "/root/anaconda3/envs/yolat_seg_chw/lib/python3.7/site-packages/fastapi/encoders.py", line 141, in jsonable_encoder
        raise ValueError(errors)
    ValueError: [TypeError("'numpy.int64' object is not iterable"), TypeError('vars() argument must have __dict__ attribute')]
    

    [TypeError("'numpy.int64' object is not iterable"),最终发现是因为python3中没有int64类型,只有int类型,而上面截图中?{'id': 0, 'type': 21中的0和21都是int64类型的,解决方法就是把这两个转换成int类型,然后错误解决。

    bug2------"msg": "value is not a valid dict",

    {
        "detail": [
            {
                "loc": [
                    "body"
                ],
                "msg": "value is not a valid dict",
                "type": "type_error.dict"
            }
        ]
    }

    这是因为测试时的postman发送的时候选择了text格式,没有选择json格式.

    参考文献:python FastApi 快速做api接口? ??https://blog.csdn.net/weixin_37254196/article/details/108143652

    cs