Q:

Flask shutdown after working 10-15 sec

I am developing a python messenger Bot using a wrapper from pymessenger. It works locally but in production it breaks.Like in every sec there are 15-20 req. I am using Pm2 to restart the process when shutdown/close. When i start the app it run for 10-20 sec, works as expected but suddenly show that error and restart. i would really appreciate if anybody can help me.
Here is the code:
# encoding=utf8
import sys
reload(sys)
sys.setdefaultencoding('utf8')

import os
import emoji
from flask import Flask, request
from pymessenger.bot import Bot    
app = Flask(__name__)

bot = Bot(ACCESS_TOKEN)

@app.route("/webhook", methods=['GET', 'POST'])
def hello():
    if request.method == 'GET':
        if request.args.get("hub.verify_token") == VERIFY_TOKEN:
            return request.args.get("hub.challenge")
        else:
            return 'Invalid verification token'
    try:
        if request.method == 'POST':
            output = request.get_json()
            for event in output['entry']:
                if event.get("messaging"):
                    messaging = event['messaging']
                    for x in messaging:
                        if x.get('message'):
                            recipient_id = x['sender']['id']
                            if x['message'].get('text'):
                                message = emoji.demojize(x['message']['text'])

#-----------------------some other code ------------------
#-------------------------------------------------------
                                bot.send_text_message(
                                    recipient_id, "replay")
                            if x['message'].get('attachments'):
                                bot.send_text_message(
                                    recipient_id, "No result!!")
                        else:
                            pass
                return "Success"
        return "Success"
    except IOError as (errno, strerror):
        print "I/O error({0}): {1}".format(errno, strerror)
    except ValueError:
        print "Could not convert data to an integer."
    except:
        print "Unexpected error:", sys.exc_info()[0]
        raise

    if __name__ == "__main__":
       app.run(port=5000, debug=False)

I am not a python developer,just using it for a library i can't find in other platform for messenger Bot. 
Here is Error log:
  File "/usr/lib/python2.7/SocketServer.py", line 290, in _handle_request_noblock
    self.process_request(request, client_address)
  File "/usr/lib/python2.7/SocketServer.py", line 318, in process_request
   self.finish_request(request, client_address)
  File "/usr/lib/python2.7/SocketServer.py", line 331, in finish_request
    self.RequestHandlerClass(request, client_address, self)
   File "/usr/lib/python2.7/SocketServer.py", line 654, in __init__
     self.finish()
   File "/usr/lib/python2.7/SocketServer.py", line 713, in finish
     self.wfile.close()
   File "/usr/lib/python2.7/socket.py", line 283, in close
     self.flush()
  File "/usr/lib/python2.7/socket.py", line 307, in flush
    self._sock.sendall(view[write_offset:write_offset+buffer_size])
 socket.error: [Errno 32] Broken pipe

A:

You are using the built-in server that comes with Flask, in production. Don't do that, it was only ever designed as a convenience to make developing easy. It can't handle real-life production edgecases.
What's happening is that the remote client the server was sending a response to, has closed the connection early. This happens from time to time, is not quite how it is supposed to work, but that's the internet for you. This is not something you need to care about when developing your app, so the built-in server doesn't handle this edgecase.
Instead, you need to deploy Flask on a production-quality WSGI server. That can be Apache with mod_wsgi, or Gunicorn, or uWSGI, or any other such server. See the Deploying chapter of the Flask documentation.

