我正在使用来自 pymessenger 的包装器开发一个 python 信使机器人.它在本地工作,但在生产中它会中断。就像每一秒都有 15-20 个请求。我正在使用 Pm2 在关闭/关闭时重新启动进程。当我启动应用程序时,它运行了 10-20 秒,按预期工作,但突然显示该错误并重新启动。如果有人能帮助我,我将不胜感激。
代码如下:
# 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)
我不是 python 开发人员,只是将它用于我在其他平台上找不到的用于 Messenger Bot 的库。
这是错误日志:
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
请您参考如下方法:
您正在生产中使用 Flask 附带的内置服务器。不要那样做,它只是为了方便开发而设计的。它无法处理现实生活中的生产边缘情况。
发生的事情是服务器向其发送响应的远程客户端提前关闭了连接。这种情况时有发生,并不是它应该如何工作,但这就是适合您的互联网。这不是您在开发应用程序时需要关心的事情,因此内置服务器不会处理这种边缘情况。
相反,您需要在生产质量的 WSGI 服务器上部署 Flask。这可以是带有 mod_wsgi 的 Apache,或 Gunicorn,或 uWSGI,或任何其他此类服务器。查看Deploying chapter of the Flask documentation .
