当前位置:   article > 正文

用python+vue实现一个计算页面_科学计算vue 转成python代码

科学计算vue 转成python代码

要实现一个计算器页面,我们需要分别创建前端和后端部分。前端使用 Vue.js 框架,后端使用 Python 的 Flask 框架。

安装依赖

pip install flask
npm install -g vue
npm install -g @vue/cli
vue create calculator-frontend
cd calculator-frontend
npm run serve
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

在 calculator-frontend 目录下创建一个名为 src 的文件夹,并在其中创建一个名为 Calculator.vue 的文件。将以下代码粘贴到该文件中:

<template>
  <div id="app">
    <h1>简易计算器</h1>
    <input type="text" v-model="expression" />
    <button @click="calculate">计算</button>
    <p>结果: {{ result }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      expression: "",
      result: "",
    };
  },
  methods: {
    calculate() {
      this.$axios.post("http://localhost:5000/calculate", {
        expression: this.expression,
      }).then((response) => {
        this.result = response.data.result;
      });
    },
  },
};
</script>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

在项目根目录下创建一个名为 backend.py 的文件,将以下代码粘贴到该文件中:

from flask import Flask, request, jsonify
import ast
import operator

app = Flask(__name__)

@app.route("/calculate", methods=["POST"])
def calculate():
    expression = request.json["expression"]
    try:
        result = eval_expr(expression)
        return jsonify({"result": result})
    except Exception as e:
        return jsonify({"error": str(e)})

def eval_expr(expr):
    ops = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv}
    node = ast.parse(expr, mode="eval")

    def _eval(node):
        if isinstance(node, ast.Expression):
            return _eval(node.body)
        elif isinstance(node, ast.Num):
            return node.n
        elif isinstance(node, ast.BinOp):
            left = _eval(node.left)
            right = _eval(node.right)
            return ops[type(node.op)](left, right)
        else:
            raise TypeError(node)

    return _eval(node.body)

if __name__ == "__main__":
    app.run(debug=True)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

运行后端服务器

python backend.py
  • 1

访问 http://localhost:8080,你将看到一个简单的计算器页面。在输入框中输入表达式,然后点击“计算”按钮,结果将显示在页面上。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/975457
推荐阅读
相关标签
  

闽ICP备14008679号