POST 请求结果在 "internal server error",大多数情况下但不是全部(!?)

POST request results in "internal server error", most of the times but not all (!?)

编辑:

tl;博士:

如何使用 python 向可以使用 openCV 操作的 Flask 应用程序请求 post 图像?

问题的长版和我试过的内容:

我正在尝试 POST 从一个 Python Flask 应用程序到另一个应用程序的图像。我面临的问题是它有时似乎有效,但通常无效。

接收数据的应用:

@app.route("/post", methods=['GET', 'POST'])
def post():
    print "in post"
    req = request.files['file']
    #    req = open('pug.jpg', 'r+b')
    arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
    img = cv2.imdecode(arr,-1) # 'load it as it is'
    print img
    cv2.imwrite('result.png',img)
    return "Hello"

发送数据的应用:

def hello():
    url = 'http://IP_ADDRESS/post'
    #This image will not work
    image = open('PATH/TO/IMAGE/pug.jpg', 'r+b')
    #But with this image it will work!?
    #image = open('PATH/TO/IMAGE/res_tile.png', 'r+b')
    files = {'file': image}
    r = requests.post(url, files=files)
    image.close()
    return 'Hello World!'

我尝试过的:

所以,我做 POST 的方式肯定有问题;但它适用于其他图像。真奇怪。

如有任何帮助,我们将不胜感激!

编辑: 我现在尝试了几种额外的方法,包括接收和发送 POST 请求,但仍然没有成功。我发现了更多有效的图像和更多无效的图像。令人费解且非常恼人。请参阅下面的更多代码。

接收数据的应用:

def post():
    print "in post"
    photo = request.files['file']
    in_memory_file = io.BytesIO()
    photo.save(in_memory_file)
    data = np.fromstring(in_memory_file.getvalue(), dtype=np.uint8)
    color_image_flag = 1
    img = cv2.imdecode(data, color_image_flag)
    print img
    cv2.imwrite('result.png',img)
    return "Hello"

发送数据的应用:

def hello():
    url = 'http://IPADDRESS/post'
    image = open('../PATH/TO/IMAGE/pug2.png', 'r+b')
    files = {'file': ('hej.png', image, 'image/png')}
    r = requests.post(url, files=files, stream=True)
    image.close()
    print r.content
    return 'Hello World!'

仍然没有运气。

编辑:

现在我也尝试了 "Multipartencoder" 和 requests_toolbelt,但我仍然面临同样的问题。在某些图像上它有效。对其他人没有。有没有人知道我做错了什么?

发送请求的应用:

def hello():
        m = MultipartEncoder(
            fields={'field0': 'value', 'field1': 'value',
                    'field2': ('filename', open('../PATH/TO/IMG', 'rb'), 'image/png')}
        )
        print m.fields['field0']
        r = requests.post('http://192.168.0.3/post', data=m,
                  headers={'Content-Type': m.content_type})

接收请求的应用程序与以前相同,只是更改了所以我访问了文件的正确字段("req = request.files['field2']")

欢迎任何tips/hits/ideas!

是"solved"。或者更确切地说,我找到了解决方法。

两个应用程序(接收和发送图像)都在我的机器上 运行 本地。将我的接收应用程序推送到 AWS 并将我的发送应用程序保留在我的机器接缝上以解决问题(至少从我在初始测试中看到的)。我想在本地同时拥有两者以便于开发,但现在它接缝我需要在非本地拥有一个应用程序 运行。

如果你们中的任何人知道为什么这现在有效...我洗耳恭听。