【发布时间】:2020-12-26 20:36:20
【问题描述】:
最近我对 API 开发很感兴趣,我尝试使用邮递员将图像发送到我的 API,它可以工作,但是当我尝试使用 pythons 请求模块发送 API 请求时,我的 API 无法正常工作,而且我的请求代码是在下面谢谢你
=========================Api====================== ===============
class UploadImage(Resource):
def post(self):
parse = reqparse.RequestParser()
parse.add_argument('key', type=str)
parse.add_argument('mode', type=str)
parse.add_argument('image', type=werkzeug.datastructures.FileStorage, location='files', required=True, help='file that you want to send to the API')
args = parse.parse_args()
key= args['key']
mode = args['mode']
if key == 'YourApiKey':
image_file = args['image']
file_name = np.random.randint(1,10000000) # picking a random number for image
image_file.save(f"{file_name}.jpg") # saving the image
if mode == 'label':
data = objectDetection(str(file_name) + '.jpg',mode=mode) # detecting the objects in the image
os.remove(f"{file_name}.jpg") #removing to original image
img = Image.fromarray(data, 'RGB')
img.save('img.jpg')
return send_file('img.jpg') # {'status' : 'success'}, 201
if mode == 'classes':
data = objectDetection(str(file_name) + '.jpg',mode=mode) # detecting the objects in the image
os.remove(f"{file_name}.jpg") #removing to original image
return {'status' : data}
else:
return {'status' : 'Unauthorized'}, 401
====================================请求=========== =======================
import requests
import json
url = 'http://127.0.0.1:5000/upload?key=YourApiKey&mode=label'
data = open('car.jpg','rb').read()
payload = json.dumps({'image': data})
x = requests.post(url, data = payload)
print(x.text)
【问题讨论】:
标签: python api flask post request