【问题标题】:Python how to post a image to an apiPython如何将图像发布到api
【发布时间】: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


    【解决方案1】:

    您需要为Content-Type 添加标头。

    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})
    headers = {
      'Content-Type': 'image/jpg'
    }
    x = requests.post(url,headers=headers data = payload)
    
    print(x.text)
    

    您还可以从邮递员生成客户端代码。 Generating client code

    【讨论】:

    • 非常感谢您,您无法相信您对我的帮助有多大,谢谢
    猜你喜欢
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2013-05-04
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    相关资源
    最近更新 更多