繁体   English   中英

工作 10-15 秒后烧瓶关闭

[英]Flask shutdown after working 10-15 sec

我正在使用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 开发人员,只是将它用于我在其他平台上找不到的 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,或者任何其他这样的服务器。 请参阅Flask 文档部署一章

使用Gunicorn和 Flask 来管理 WSGI 请求。 下面是一些小脚本,它们可以帮助您启动和停止与 Gunicorn 一起运行的 Flask 服务器。 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"

您可以将 Waitress 与 Flask 一起使用,Flash 是仅用于测试的基本 WSGI 服务

https://github.com/Pylons/waitres

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM