Home > Software design >  Understanding "GET" with Flask and Python
Understanding "GET" with Flask and Python

Time:12-07

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?

CodePudding user response:

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.args.get('uname')
    passwrd = request.args.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 ><strong>Error:</strong> {{ error }}
        {% endif %}
        <tr>
            <td><input type="submit"></td>
        </tr>
    </table>
</form>
</body>
</html>
  • Related