Flask Programming

Hands On No. 5 : Working With Sessions

Resources

Source Code of hello.py
from flask import Flask
from flask import render_template
from flask import request
from flask import session

app = Flask(__name__, template_folder='templates')
app.secret_key = b'_5#yswq2L"F4Q8z\n\xec]/'

@app.route("/")
def datainput():
    if 'username' in session:
        username1 = session["username"]
        return render_template('Display-Data.html', username= username1)
    else:
        return render_template('Data-Input.html')

@app.route('/viewdata', methods=['GET', 'POST'])
def viewdata():
    if request.method == 'POST':
        username = request.form.get('uname')
        password = request.form.get('password')
        if ((username == 'dhaval') and (password == 'mehta')):
            username1 = username.upper()
            session['username'] = username = request.form.get('uname')
            return render_template('Display-Data.html', username= username1)
        else:
             return f'Wrong Username and Password'
    if request.method == 'GET':
        return render_template('get-is-not-supported.html')
    
@app.route('/logout')
def logout():
    session.pop('username', None)
    return render_template('Data-Input.html')

Source Code of Data-Input.html

<!DOCTYPE html>
<html>
<head>
<title>Personal Details</title>
<script>

function dataCheck()
{
var a = document.getElementById("uname").value.length;
if(a==0)
{
alert("Enter Username ");
return false;
}
var b = document.getElementById("password").value.length;
if(b==0)
{
alert("Enter Password ");
return false;
}
}
</script>
</head>
<body>

<form name="frmmain" action="viewdata" method="POST">
<label for="fname">Enter Username :</label><br>
<input type="text" id="uname" name="uname" value=""><br>
<label for="lname">Enter Password :</label><br>
<input type="password" id="password" name="password" value=""><br><br>
<input type="submit" value="Submit" onclick="return dataCheck()" onsubmit="return dataCheck()">
</form>

</body>
</html>

Source Code of Display-Data.html

<!DOCTYPE html>
<html>
<head>
<title>Personal Details</title>
</head>
<body>
<h1>Welcome {{ username }}</h1>
</body>
</html>

Source Code of get-is-not-supported.html
Get method support is not available