In: Computer Science
Write a Flask app in which a Python script prompts the user to enter a string and then that string, as entered, gets displayed on an otherwise blank HTML file, called output.html. Show the Python/Flask code and the html code of the output.html file, one below the other as part of your answer.
user_input.py
from flask import Flask, render_template,request
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def hello():
# this block executes after clicking on the submit button
if request.method == "POST":
# gets the string from the frontend to backend
inp=request.form["user_input"]
# redirect to output.html with the user entered string
return render_template("output.html",user_data=inp)
else:
# renders the form for user input
return render_template("home.html")
if __name__ == "__main__":
app.run(debug=True)
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home Page</title>
</head>
<body>
<form class="form"method="POST">
<label for="name">Write down your input string</label>
<!-- reads the string from the user -->
<input type="text" autofocus="autofocus" id="user_input" name="user_input">
<button type="submit">Submit</button>
<!-- on click on submit it sends user input to backend -->
</form>
</body>
</html>
Output.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Output Page</title>
</head>
<body>
<!-- display the string entered by the user -->
{{user_data}}
</body>
</html>