0

I'm new to programing with flask, so I apologize if my question is naive, but I can't seem to figure out what I'm sure is a simple idea.

I'm trying to create an input where you can enter a string, and convert it into a function. So if someone enters 2*x + 5, i can create f(x) = 2*x +5

This is what I have so far:

@app.route('/test1')
def test2():
    return render_template("template_test.html")

@app.route('/test1', methods = ['POST'])
def test2_post():
    text = request.form['text']

    def f(x):
        return text

    return f(10)
  • 2
    This isn't really unique to Flask. Did you research creating functions from a string *just using Python* yet? Googling *python create function from string* should give you a starting point here. – Martijn Pieters Oct 24 '16 at 18:23

2 Answers2

1

Safer than using eval: you could use a library that will parse mathematical expression - added bonus, you can give a meaningful error message to the user who input it if their input isn't a valid mathematical expression. See Evaluating a mathematical expression in a string - specifically, this answer which gives a hand-rolled parser that can be used like so:

def test2_post():
    text = request.form['text']
    nsp = NumericStringParser()
    nsp.set_variable('x', 10) # you'll have to implement this method
    result = nsp.eval(text)
    return(result)

The one thing above and beyond the linked answer is providing a way to set a variable. You'd have to extend the code given in that answer - my suggestion would be to keep a dictionary of variables and values inside of the NumericStringParser object. The set_variable function sets the value in that dictionary, and you add an alpha-numeric token in the parser that gets converted to the corresponding value in the dictionary of variables and values.

If you haven't worked with writing a parser before, it's a bit out of scope in this question for me to give details - but I'd encourage you to take a few minutes to look into it, it's not as scary as it may seem.

Why bother: if this is for a web app that you're writing, there are very few situations where you could safely eval user input - it's almost definitely a bad idea. This is a way to execute arbitrary math expressions without the security risk of using eval.

Community
  • 1
  • 1
alexanderbird
  • 3,847
  • 1
  • 26
  • 35
0

While this is not flask-specific, in python, executing code in a string can be accomplished by using exec; however, it is generally considered bad practice to use this (especially in a web server context) as it is a very easily exploitable security risk.

Chris Kenyon
  • 208
  • 1
  • 8