fastapi报错TypeError("'numpy.int64' object is not iterable"解决

 

目录

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<code>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)
 
</code>

1.2start.sh?

1
<code>uvicorn main:app --host 0.0.0.0 --port 8091</code>

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

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

 

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<code>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')]
</code>

[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",

1
2
3
4
5
6
7
8
9
10
11
<code>{
    "detail": [
        {
            "loc": [
                "body"
            ],
            "msg": "value is not a valid dict",
            "type": "type_error.dict"
        }
    ]
}</code>

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

 

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

posted @ 2023-05-18 12:19  海_纳百川  阅读(1419)  评论(0编辑  收藏  举报
本站总访问量