So, I am learning Flask and trying to create an app that will display what I typed. Here's the python code:
from flask import Flask, render_template, request, redirect, url_for
app = Flask("hello")
app.secret_key = "hello"
@app.route('/')
def home():
return "This is a simple page. <p>Please navigate by yourself"
@app.route('/hi', methods = ['POST', 'GET'])
def inp():
if request.method =='POST' :
val = request.form["inpValue"]
return render_template(url_for('rslt', res = val))
else:
return redirect(url_for("hello", url = "failed"))
@app.route('/<res>')
def rslt(res):
return f"<p> Resut = {res}</p> "
app.run(debug=True)
Here is the index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{name}}</title>
</head>
<body>
<main>
<nav id="top">
<input type="text" name="name">
<p>{{name}}</p>
</nav>
<div id="middle">
{% block content%}
<form action="/hi" method="post">
<input type="text" name="inpValue" />
<input type="submit" value="submit" />
</form>
{% endblock %}
<p>User Typed - {{inpResult}}</p>
</div>
</main>
<footer>
<div id="bottom"></div>
</footer>
</body>
</html>
and here is the result.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
</head>
<body>
<p> Resut = {{result}}</p>
</body>
</html>
At the end I am getting a bad request whenever I try to access the page '/hi'. Please help me rectifying my code.
The problem is that the
<url>
variable matches anything, including/hi
. So when you request the/hi
page, the/<url>
route is the first match.Move the
/<url>
route to be after the/hi
route, so it looks for/hi
first.