如何在python-eve应用程序中返回更有意义的500错误

我在python-eve应用程序中有一些代码,它从设备检索一些数据,并在第一次请求该资源时填充资源.有时代码无法成功连接到设备.在这种情况下,我想返回一条更好地解释这一点的错误消息,而不仅仅是一个普通的500错误.这是on_fetch_item钩子:

def before_returning_item(resource, _id, document):
if resource == "switches":
    if "interfaces" not in document.keys():
        # retrieve and store switch config if it hasn't been stored yet
        r = app.data.driver.db[resource]
        try:
            switch = prepare_switch_from_document(document)
        except socket.timeout:
            # raise some more meaningful error with message
            pass
        interface_list = switch.get_formatted_interfaces()
        r.update({'_id': _id}, {'interfaces': interface_list})
        document['interfaces'] = interface_list

app.on_fetch_item += before_returning_item

提前致谢.

解决方法:

您所要做的就是利用Flask的中止方法:

from flask import abort

def before_returning_item(resource, _id, document):
    if resource == "switches":
        if "interfaces" not in document.keys():
            # retrieve and store switch config if it hasn't been stored yet
            r = app.data.driver.db[resource]
            try:
                switch = prepare_switch_from_document(document)
            except socket.timeout:
                # raise some more meaningful error with message
                abort(500)
            interface_list = switch.get_formatted_interfaces()
            r.update({'_id': _id}, {'interfaces': interface_list})
            document['interfaces'] = interface_list

    app.on_fetch_item += before_returning_item

如果要添加自定义说明:

abort(500, description='My custom abort description')
上一篇:使用layer弹出层js方式提交表单重复2次问题


下一篇:python – 端点查询字符串参数中的多个“where子句”