如何在Flask中拒绝响应?
我正在使用Flask来实现一个网络服务。
@app.route('/myservice',methods=['POST'])
def myservice():
if abnormal_activity_detected():
refuse to make any response.
我想知道如何在服务器端正确地拒绝做出响应。
提前谢谢你们!
1 个回答
1
实现这个目标的一种方法就是直接关闭连接,而不发送任何响应。你可以通过直接操作底层的套接字来做到这一点。
from flask import Flask, request
app = Flask(__name__)
@app.route('/myservice', methods=['POST'])
def myservice():
if abnormal_activity_detected():
# Get the underlying WSGI environment
environ = request.environ
# Access the underlying socket
socket = environ.get('werkzeug.server.shutdown_socket')
if socket:
# Close the connection without sending any response
socket.close()
return ''
else:
# Fallback to aborting the request if the socket is not available
abort(403)
else:
# Your normal processing code here
return "Your response here"
if __name__ == '__main__':
app.run(debug=True)
输出:
* Serving Flask app 'main'
* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:5000
Press CTRL+C to quit
* Restarting with stat
* Debugger is active!
* Debugger PIN: 420-940-029