如何使用Flask拒绝回复?

问题描述 投票:0回答:1

我正在使用 Flask 来实现 Web 服务。

@app.route('/myservice',methods=['POST'])
def myservice():
    if abnormal_activity_detected():
       refuse to make any response.

我想知道如何正确拒绝服务器端的响应。

提前谢谢您!

python flask web service
1个回答
0
投票

实现此目的的一种方法是简单地关闭连接而不发送任何响应。这可以通过直接操作底层套接字来完成。

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
© www.soinside.com 2019 - 2024. All rights reserved.