13

Recently I was working on a web application, using Flask and sympy libraries. The user enters his equation in a textarea and Flask rechieve it as a string. I would like to have the possibility to calculate the result of this equation,by using sympy function solve(). But for this I must convert this string to an sympy expression. How could I do that?

from flask import Flask,request,render_template,flash
from sympy import *
from sympy.parsing.sympy_parser import *

x = symbols('x')
app = Flask(__name__)
app.secret_key = 'mysecretkey'


def calculate_():
    first_eq = request.form['first_eq']

    first_eq2= parse_expr(first_eq)
    result = solve(first_eq2)
    return result


@app.route("/",methods=['GET', 'POST'])
def myGet():

    return render_template("my-form.html")

@app.route("/myPost/",methods=['GET', 'POST'])
def myPost():
    answer = request.form['answer']
    result_of_answer=solve(Eq(answer),x)
    result = calculate_()
    try:
        if result == result_of_answer:
            flash("you got it!")
        else:
            flash("no, it's wrong")
            return render_template("my-form.html")
    except:
        flash("sorry, wrong type. Try again!")
        return render_template("my-form.html")
if __name__ == '__main__':
    app.run()
Dharman
  • 30,962
  • 25
  • 85
  • 135
Vasile
  • 801
  • 2
  • 13
  • 31
  • You can use `parse_expr` which converts the string `s` to a SymPy expression as follows: http://docs.sympy.org/dev/modules/parsing.html – Avión Nov 09 '15 at 10:13
  • I tryed to use this in my calculate_ func. It gives me a sympifyError: `def calculate_(): first_eq = request.form['first_eq'] first_eq2= parse_expr(first_eq) result = solve(first_eq2) return result` – Vasile Nov 09 '15 at 11:47
  • What's the content of `first_eq`? Please, edit your main post with your code. – Avión Nov 09 '15 at 12:06
  • I added my code. The content of the first_eq is an expression equaled to zero. – Vasile Nov 09 '15 at 13:14

2 Answers2

12

sympify() uses eval() which is dangerous. Use sympy.parsing.sympy_parser.parse_expr() instead.

Alec
  • 8,529
  • 8
  • 37
  • 63
10

The function you're looking for is sympify. http://docs.sympy.org/latest/modules/core.html#sympy.core.sympify.sympify

asmeurer
  • 86,894
  • 26
  • 169
  • 240
  • 6
    This answer uses `eval()` and is dangerous – Alec Apr 05 '20 at 06:14
  • 1
    See also: [How safe is simpify?](https://stackoverflow.com/questions/16718644/how-safe-is-sympys-sympifystring-evalf) (tl;dr: it's not) – Stef Sep 09 '22 at 08:38