Open In Colab

Update Flask App with more functions#

Let’s add two buttons: “Lowercase” and “Capital”. To add a “Capital” button that transforms the submitted text into uppercase and a “Lowercase” button that trasnforms the submitted text into lowercase, we need to modify both the form.html and app.py files. Here’s how:

  1. form.html:

<!DOCTYPE html>
<html>
    <head>
        <title>Submit Text</title>
        <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
    </head>
    <body>
        <form method="POST">
            <label for="text">Enter your text:</label><br>
            <input type="text" id="text" name="text"><br>
            <input type="submit" name="submit_button" value="Lowercase">
            <input type="submit" name="submit_button" value="Capital">
        </form>
        {% if message %}
        <div id="result">
            <h2>Submitted Text:</h2>
            <p>{{ message }}</p>
        </div>
        {% endif %}
    </body>
</html>

Here, we added another submit button with the value “Capital”.

  1. app.py:


from flask import Flask, render_template, request
app = Flask(__name__)

@app.route('/')
def hello_world():
    return render_template('index.html', message='Hello, World!')

@app.route('/form', methods=['GET', 'POST'])
def render_form():
    message = ''
    if request.method == 'POST':
        text = request.form.get('text')
        if request.form['submit_button'] == 'Lowercase':
            message = text.lower()
        elif request.form['submit_button'] == 'Capital':
            message = text.upper()
    return render_template('form.html', message=message)

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

In this updated app.py file, we added another condition to check which button was clicked. If the 'Lowercase' button was clicked, it converts the text to lowercase, and if the 'Capital' button was clicked, it converts the text to uppercase.

python_cources_for_beginners/
├── images/
│   ├── flask_page.png
└── Mini Project 2/
    ├── static/
    │   ├── images/
    │   │   ├── flask_page.png
    │   └── style.css
    ├── templates/
    │   ├── form.html
    │   └── index.html
    └── app.py