Understanding "GET" with Flask and Python

Question:

I am trying to understand how GET works along with Flask and Python.

The following is my app.py source code:

from flask import *

app = Flask(__name__)  

@app.route('/', methods=['GET'])
def login():
    uname = request.args.get('uname')
    passwrd = request.args.get('pass')
    if uname == "ayush" and passwrd == "google":
        return "Welcome %s" % uname
    else:
        return "Username and password not found!"

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

The following is my index.html source code:

<html>
   <body>
      <form action = "http://127.0.0.1:5000/" method = "get">
         <table>
        <tr><td>Name</td>
        <td><input type ="text" name ="uname"></td></tr>
        <tr><td>Password</td>
        <td><input type ="password" name ="pass"></td></tr>
        <tr><td><input type = "submit"></td></tr>
    </table>
      </form>
   </body>
</html>

I am not being able to see the login page.

What am I doing wrong, and how can I fix that?

Asked By: user366312

||

Answers:

You are only returning when username and password matches, you need to return something if your if condition is not true

and you should use request.form.get if you are passing form data:

app.py

from flask import *

app = Flask(__name__)

@app.route('/', methods=['GET'])
def login():
    error = None
    uname = request.form.get('uname')
    passwrd = request.form.get('pass')
    if uname is None or passwrd is None:
        error = "Please enter your credentials"
    elif uname == "ayush" and passwrd == "google":
        return "Welcome %s" % uname
    else:
        error = "Invalid creds"

    #Render index.html and pass errors
    return render_template('index.html', error=error)


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

index.html

<html>
<body>
<form action="/" method="get">
    <table>
        <tr>
            <td>Name</td>
            <td><input type="text" name="uname"></td>
        </tr>
        <tr>
            <td>Password</td>
            <td><input type="password" name="pass"></td>
        </tr>
        {% if error %}
            <p class="error"><strong>Error:</strong> {{ error }}
        {% endif %}
        <tr>
            <td><input type="submit"></td>
        </tr>
    </table>
</form>
</body>
</html>
Answered By: Sourabh Burse
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.