Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build a get-form post in flask

Ok so I am new to flask, and want to know what objects or tools I would use to do this. I want to create a form, where the user inputs some text, clicks a submit button, then the text that they submitted is bound as a python string, and has a function run on it, and that text is then posted back onto the web page they are viewing with the return value of that function it went through. Here is an example:

html form:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<form action = "/" method="get">
    <input type="text" name="mail" size="25">
    <input type="submit" value="Submit">
</form>

<textarea cols="50" rows="4" name="result"></textarea>

</body>
</html>

Then here is what I believe should be the url function should look like

@app.route('/', methods=['GET', 'POST'])
    def form():
         if request.method == 'GET':
             input_text = request.data #step to bind form text to python string
              new_text = textfunction(input_text) #running the function on the retrieved test.
              return (new_text) # no idea if this is write, but returns text after modification.

What would be the best way to set this up? Would it be correct to put a variable as the value for the input html? Need some help on this.

like image 601
Josh Weinstein Avatar asked Sep 19 '15 22:09

Josh Weinstein


1 Answers

Basically, what you want to do is have a block in your template that is only included if the variable has a value set. See the following example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<form action = "/" method="get">
    <input type="text" name="mail" size="25">
    <input type="submit" value="Submit">
</form>

{% if result %}
<textarea cols="50" rows="4" name="result">{{ result }}</textarea>
{% endif %}

</body>
</html>

and then in your python code

@app.route('/', methods=['GET', 'POST'])
def index(result=None):
    if request.args.get('mail', None):
        result = process_text(request.args['mail'])
    return render_template('index.html', result=result)


def process_text(text):
    return "FOO" + text
like image 158
m-murphy Avatar answered Oct 01 '22 13:10

m-murphy