如果 eval 函数给出错误以在数据库 table 中应用计算,则将错误消息从 flask API 发送到 vue.js 前端

send error message from flask API to vue.js frontend if eval function giving error to apply calculation in database table

我有 JSON 文件包含数学运算以将其应用于数据库中的列 table,我正在使用 eval 函数转换此操作并创建一个新的数据框,有时 JSON 文件包含不在数据库中的列名 table 列名,因此它在 eval 函数中给出错误,我想向用户发送消息(您的操作无法完成,因为您输入了无效的名称 = "d/f")

JSON 文件看起来像:

{"1": "a/b", "2": "b/c", "3": "c/d","4": "d*f "}

从数据库中提取的数据框

element_df =  pd.read_sql_query("select *from table where id =5",engine)

应用求值函数

claculted_df = pd.dataframe()

   for i in calc_list
    try:
     calculated df = elemnt_df.eval(i)
    except pd.core.computation.ops.UndefinedVariableError:
     {"message":"your operation can not be done because you enter invalid name = d*f"}

然后使用报告实验室创建 pdf,最后将其发送到前端

class reportAPI(source):

    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('tested', type=inputs.boolean, default=True, required=False)
        # parser.add_argument('key',     type=str, default=None, required=False)
        
        report = ReportResult()
        report, info = report_.create(data, data['tested'])
        get_pdf = report.get_pdf()      
        filename = "output"
        response = make_response(get_pdf)
        return response
#=========================
api.add_resource(reportAPI, '/test')

我希望用户阅读带有创建的错误消息的 window 警报 在 test.vue 响应中

this.$axios.post(this.$backendUrl + '/test', jsonData)
          .then(response => {
            console.log(response)
            this.fileData = { data: response.data }
            this.$emit('fileGenerated', this.fileData)

当前文件: {"1": "a/b", "2": "b/c", "3": "c/d", "4":"d*f"}

错误 pandas.core.computation.ops.UndefinedVariableError: 名称 'd*f' 未定义

来自 oracle 的数据框

a b c d
1 1 20 1
10 5 18 2
15 3 16 4
20 2 14 6
25 6 3 8

正如其他人所说,您可以使用 try/except 来捕获错误。然后,如果错误被捕获,在这种情况下,您可以 return 一个包含错误的对象而不是数据。

通常最佳做法是 API 调用 return 一个 success/fail 布尔值和数据本身。因此,在此示例中,您可以 return 以下内容(表示为 JSON)...

成功时:

{
   success: true,
   data: ...
}

捕获到错误时:

{
   success: false,
   data: "The error message"
}

您可以使用 JavaScript 的内置 alert() 功能来显示警报,或者您可以使用类似 vue-simple-alert.

的功能