【flask】已解决:使用flask-restful后errorhandler中间件无法拦截报错

使用flask-restful后errorhandler中间件无法拦截报错


找了半天源码,终于在Api类里这找到一句:

    def handle_error(self, e):
        """Error handler for the API transforms a raised exception into a Flask
        response, with the appropriate HTTP status code and body.

        :param e: the raised Exception object
        :type e: Exception

        """
        got_request_exception.send(current_app._get_current_object(), exception=e)

        if not isinstance(e, HTTPException) and current_app.propagate_exceptions:
            exc_type, exc_value, tb = sys.exc_info()
            if exc_value is e:
                raise
            else:
                raise e

所以不是HttpException实例的错误只能在app config的propagate_exceptions是True的时候才能抛出。
于是在配置文件中加上

PROPAGATE_EXCEPTIONS = True

这文档我是翻遍了,真找不着这属性的介绍,我真麻了

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,以下是使用 Flask-RESTfulFlask-SocketIO 构建前后端分离的聊天程序的示例代码: 后端代码: ```python from flask import Flask, request from flask_restful import Resource, Api from flask_cors import CORS from flask_socketio import SocketIO, send, emit app = Flask(__name__) api = Api(app) CORS(app) socketio = SocketIO(app, cors_allowed_origins='*') class Chat(Resource): def get(self): return {'message': 'Welcome to the chat app!'} def post(self): data = request.get_json() message = data['message'] emit('message', message, broadcast=True) return {'message': message} api.add_resource(Chat, '/chat') if __name__ == '__main__': socketio.run(app, debug=True) ``` 前端代码: ```html <!DOCTYPE html> <html> <head> <title>Chat App</title> </head> <body> <h1>Chat App</h1> <div id="messages"></div> <form> <input id="message" type="text"> <button type="submit" id="send">Send</button> </form> <script src="https://cdn.socket.io/socket.io-3.1.0.min.js"></script> <script> const socket = io('http://localhost:5000'); socket.on('message', function (data) { const messages = document.getElementById('messages'); messages.innerHTML += '<p>' + data + '</p>'; }); const form = document.querySelector('form'); form.addEventListener('submit', function (event) { event.preventDefault(); const input = document.getElementById('message'); const message = input.value; socket.emit('message', message); input.value = ''; }); </script> </body> </html> ``` 在这个示例中,我们创建了一个名为 Chat 的资源,其中 GET 请求将返回欢迎消息,而 POST 请求将广播收到的消息。我们使用 Flask-SocketIO 在后端处理 WebSocket 连接,并使用 emit 函数将消息发送给所有连接的客户端。前端代码使用 Socket.IO 客户端库来建立 WebSocket 连接,并使用 emit 函数将用户输入的消息发送到服务器。收到服务器发送的消息时,前端代码将其显示在页面上。 要运行此示例,请确保已安装 FlaskFlask-RESTfulFlask-Cors 和 Flask-SocketIO,并在终端中运行以下命令: ``` $ export FLASK_APP=app.py $ flask run ``` 然后在浏览器中打开 http://localhost:5000/,即可开始聊天。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值