脚本终止时释放Python Flask端口 [英] Release Python Flask port when script is terminated
问题描述
sudo fuser 8080 / tcp -k
来杀死它)。我想要一个更好的方式来释放它。任何人都知道使用正确的Flask代码? 导入sys
导入os
从flask导入信号
导入Flask,render_template,url_for ,current_app,从OpenSSL请求
导入SSL
#按CTRL + C
def signal_handler(信号,帧)清理:
#我要释放
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,Raspberry Pi运行Raspbian
我结束了猴子修补套接字
模块本身。在导入之后添加:
$ p $ #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)
返回socket.socket._bind(self,* args, ** kwargs)
socket.socket.bind = my_socket_bind
我没有找到任何其他方式。
I have a Python Flask server that uses HTTPS. When I press CTRL-C to terminate, the listner is still running (I have to run in the shell: sudo fuser 8080/tcp -k
to kill it). I want a better way of releasing it. Anyone know the correct Flask code to use?
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, Raspberry Pi running Raspbian
I exactly had the same problem with bottle, finally I ended up monkey-patching the socket
module itself. Add this after your imports:
# 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
I didn't find any other way.
这篇关于脚本终止时释放Python Flask端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!