0

I have enabled threaded in the Flask dev server but it seems that it doesn't fix the "Broken pipe" error described in Flask broken pipe with requests.

from flask import Flask, request
import requests

app = Flask(__name__)

@app.route('/compare', methods=['POST'])
def compare():
    data = request.get_json()
    img = data['img']
    imgdata = requests.get(img).content  # Error is from here
    filename = 'hello.jpg'

    with open(filename, 'wb') as f:
        f.write(imgdata)

    return 'Yes'

if __name__ == '__main__':
    app.run(threaded=True, host='0.0.0.0', port=80)
Traceback (most recent call last):
  File "/usr/lib/python2.7/SocketServer.py", line 593, in process_request_thread
    self.finish_request(request, client_address)
  File "/usr/lib/python2.7/SocketServer.py", line 334, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/usr/lib/python2.7/SocketServer.py", line 651, in __init__
    self.finish()
  File "/usr/lib/python2.7/SocketServer.py", line 710, in finish
    self.wfile.close()
  File "/usr/lib/python2.7/socket.py", line 279, in close
    self.flush()
  File "/usr/lib/python2.7/socket.py", line 303, in flush
    self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe
davidism
  • 121,510
  • 29
  • 395
  • 339
AspiringMat
  • 2,161
  • 2
  • 21
  • 33

1 Answers1

0

It may be because the connection is being prematurely closed or the file is too large. Try this:

import requests, shutil
from requests.exceptions import ReadTimeout, ConnectionError

img_url = data['img']
filename = 'hello.jpg'

try:
    response = requests.get(img_url, stream=True)

    with open(filename, 'wb') as img_file:
        shutil.copyfileobj(response.raw, img_file)

except ReadTimeout:
    print("Connection timeout")
except ConnectionError:
    print("Connection refused")
darksky
  • 1,955
  • 16
  • 28
  • File "app.py", line 3, in from requests.exceptions import ReadTimeout, ConnectionError ImportError: cannot import name ReadTimeout – Sheshank S. Jul 01 '18 at 23:21
  • Look at the documentation of the requests library. Depending on the version of python you are using it may be `from requests import ReadTimeout` or `from requests.exceptions import ReadTimeout` – darksky Jul 03 '18 at 21:21