脚本终止时释放Python Flask端口

时间:2014-08-27 20:01:29

标签: python flask

我有一个使用HTTPS的Python Flask服务器。当我按CTRL-C终止时,列表器仍然在运行(我必须在shell中运行:sudo fuser 8080/tcp -k来杀死它)。我想要一种更好的释放方式。有人知道使用正确的Flask代码吗?

import sys
import os
import signal
from flask import Flask, render_template, url_for, current_app, request
from OpenSSL import SSL

# Clean-up when press CTRL+C
def signal_handler(signal, frame):
        # I want to release the port here
        print('Clean-up')
        sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)

context = SSL.Context(SSL.SSLv23_METHOD)
context.use_privatekey_file('server.key')
context.use_certificate_file('server.crt')

app = Flask(__name__)

@app.route("/<arg1>")
def route1(arg1):
    return render_template("flask_page1.html", var1=arg1)

app.run(host="0.0.0.0", port=8080, debug=False, ssl_context=context)

Python 2.7,运行Raspbian的Raspberry Pi

1 个答案:

答案 0 :(得分:3)

我确实遇到了与瓶子相同的问题,最后我最终修补了socket模块本身。在导入后添加:

# patch socket module
socket.socket._bind = socket.socket.bind
def my_socket_bind(self, *args, **kwargs):
    self.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    return socket.socket._bind(self, *args, **kwargs)
socket.socket.bind = my_socket_bind

我没有找到任何其他方式。