我正在使用pymessenger的包装器开发一个python messenger Bot。它在本地工作,但在生产中它会破裂。每秒都需要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开发人员,只是将它用于一个我无法在其他平台上找到信息库的库。
以下是错误日志:
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
答案 0 :(得分:4)
您正在使用Flask附带的内置服务器。不要这样做,它只是为了方便开发而设计的。它无法处理真实的生产边缘。
发生的事情是服务器发送响应的远程客户端已经提前关闭了连接。这种情况经常发生,并不是它应该如何运作,但这对你来说就是互联网。在开发应用程序时,这不是您需要关注的事情,因此内置服务器无法处理此边框。
相反,您需要在生产质量的WSGI服务器上部署Flask。这可以是带有mod_wsgi
,或Gunicorn,或uWSGI或任何其他此类服务器的Apache。请参阅Deploying chapter of the Flask documentation。
答案 1 :(得分:1)
在Flask中使用Gunicorn来管理WSGI请求。以下是可以帮助您启动和停止与Gunicorn一起运行的Flask Server的小脚本。 Flask的内置服务器不能用于生产。它随着时间而崩溃。因此,看看Gunicorn:
启动脚本:
#!/bin/bash
stat=0
COUNTER=0
swait()
{
echo -ne "Waiting for service to start"
until [[ $stat -ge 1 ]]
do
stat=$(netstat -lnt | awk '$4 ~ /:5001$/' |wc -l)
COUNTER=$((COUNTER+1))
if [ $COUNTER == 5 ] ; then
echo -e '\nError-Service start failed'
exit;
fi
echo -ne "."
sleep 2
done
}
service_start()
{
echo "Starting Service"
/<project_path>/venv/bin/gunicorn --reload -b 0.0.0.0:5001 api:app --access-logfile=/var/log/<project_name>.log --error-logfile=/var/log/<project_name>_error.log -D -w 2 --access-logformat='%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" %(L)s' --log-level=info
}
service_start
swait
echo -e "\nService started Successfully"
停止脚本
#!/bin/bash
echo "Stopping Service"
stat=1
COUNTER=0
swait()
{
echo -ne "Waiting for service to stop"
until [[ $stat -eq 0 ]]
do
stat=$(netstat -lnt | awk '$4 ~ /:5001$/' |wc -l)
COUNTER=$((COUNTER+1))
if [ $COUNTER == 8 ] ; then
echo -e '\nService stop failed'
exit;
fi
echo -ne "."
sleep 2
done
}
service_stop()
{
for pid in `ps augx | grep gunicorn | grep -E ':5001' | grep -v grep | awk '{print $2}'`;
do
echo "Killing PID" $pid
kill $pid
done
}
service_stop
swait
echo -e "\nService Stopped Successfully"
答案 2 :(得分:0)
您可以将Waitress与Flask一起使用,Flash是基本的WSGI服务,仅用于测试