Open In App

Retrieve Text From Textarea in Flask

In this article, we will see how we can retrieve the elements inside the textarea tag using Python. Textarea is one of the popular tags we used in HTML. To retrieve text from a textarea in Flask, you can use the request.form.get() method. This method allows you to retrieve the value of a specific form field, such as a textarea, from the request data sent by the client. 

The request.form.get() method is a simple and effective way to retrieve text from a textarea in Flask. This method allows you to easily access the value of a specific form field from the request data, and it can be used to implement various types of forms and user input in your Flask applications. To get started, we need to install the Flask module using Python PIP



File Structure

Make sure that your HTML file is in the templates folder.



 

index.html

Now let’s make an HTML file (name: home.html) with <textarea>. This file will be present in a folder called templates. 




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form method="POST">
        <textarea name="textarea"></textarea>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

app.py

In this code, the request.form.get() method is used to retrieve the value of the textarea form field from the request data sent by the client. This value is stored in the text variable, and it can be used for further processing in your Flask application. Here is an example of how you can use the request.form.get() method to retrieve text from a textarea in Flask.




from flask import Flask, request, render_template
  
app = Flask(__name__)
  
  
@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        # Retrieve the text from the textarea
        text = request.form.get('textarea')
  
        # Print the text in terminal for verification
        print(text)
  
    return render_template('home.html')
  
  
if __name__ == '__main__':
    app.run()

Output:

Now on, type anything in the text area and press the submit button. This will show your text in the terminal

Enter your text and press Submit

See your entered text appearing on the screen


Article Tags :