Web development with python #5 : Session in flask and Login and Logout system

in #utopian-io5 years ago (edited)

Repository

https://github.com/python

What Will I Learn?

  • Session in flask
  • Login and Logout system

Requirements

  • Basic Python
  • Install Python 3
  • Install Flask

Resources

Difficulty

Basic

Tutorial Content

In this tutorial, we will continue the previous tutorial related to data storage on our web application. In the previous tutorial. We learned how to save data using cookie. The data that we store on cookies are only stored on our client's computer. so, of course, the data we store is not on the server side. Well, in this tutorial we will store data on the server side. we will implement it in the login system.

Session in Flask

to store data on the server side we will use the session. we use sessions to store sensitive data and those that require security, and we will also prevent data from being manipulated by the user. in this tutorial, we will implement the session on the login system.

  • Create a login system

We will start using sessions on our login system. so later we will save the session user who has successfully logged in. the session that we will use to detect whether the user has logged in or not. to use a session we need to import and we have to make a secret key like this:

secret_key:

app.secret_key = '34ujeifaj21mkll'

Secret key is random and determined by ourselves. so you can use a combination of numbers, letters, punctuation in string form. The secret key is used so that other people cannot manipulate our session, we can use the secret key in theapp.

  • Save session

We have made the secret key, then we will save the session we will use. before you use the session we must import it first. We can save the session like the following:

import session

from flask  session
@app.route('/login', methods=["GET", "POST"])
def login():
    if request.method == "POST":
        resp = make_response("Your email is "+ request.form['email'])
        resp.set_cookie('email_user', request.form['email'])
        session['email'] = request.form['email']
        return resp
    return render_template('login.html')

We can save a session with an array type like this session['email'], the 'email' is the key. request.form['email'] comes from the input post.

  • Redirect with session

We have learned how to save sessions, now we will learn how to use the session to be used as a login system. so later we will redirect when the user is not logged in. Before we use the redirect function we must import it first. for more details, we can see the code below:

import redirect

from flask  redirect

Route Login

@app.route('/login', methods=["GET", "POST"])
def login():
    if request.method == "POST":
        resp = make_response("Your email is "+ request.form['email'])
        resp.set_cookie('email_user', request.form['email'])
        session['email'] = request.form['email']
        return resp

    if 'email' in session:
        email = session['email']
        return redirect(url_for('profileFunc', email = email))
    return render_template('login.html')
  • Well we will use the session ['email'] to detect users who are logged in. We can check whether the email session is in session this way if 'email' in session.

  • If the email session exists, then we will redirect to /profile/<email>. We will redirect by passing the session value. to redirect we can use the redirect ().in the riderect () we can use the url_for function to direct the URL to the destination. We can redirect the URL by calling the function used in the URL. like the following example redirect(url_for('profileFunc', email = email)). The following is routing using the profileFunc():

Route profile

@app.route('/profile/<email>')
def profileFunc(email):
        return 'Welcome to my tutorial %s' %email

In this routing, we will receive the email parameter and we will use it to check whether the data we redirect has been successful. to see a discussion about URL parameters you can follow the following tutorial.After all steps have been completed, We can see the results as shown below:

ezgif.com-video-to-gif.gif

as we saw in the picture above, now we can detect whether the user is logged in or not. If the user is logged in, we will return the user to return 'Welcome to my tutorial %s' %email and the parameters that we have passed can we appear [email protected].

Screenshot_1.png

  • Redirect to another page

Now I will redirect users with different pages according to what we want, You can change its function like the following:

Route Profile

@app.route('/profile/<email>')
def profileFunc(email):
    return render_template('profile.html', email = email)

profile.html

<!DOCTYPE html>
<html>
<head>
    <title>Template Jinja2</title>
</head>

<body>
    <h1>This is the profile page</h1>
    <h2 style="color:blue;">Hai my name is {{email}}</h1>
    <a href="{{url_for('logout')}}">Logout</a>
</body>
</html>

Now we will be redirected to the profile page like the picture below:

ezgif.com-video-to-gif (1).gif

Logout and delete session

Now we need to create a system log out on the web application that we have learned. for that, we need to create a new routing task to log out the user who is logged in, so we can delete the session delete by accessing the route . for more details, we can look at the code below:

@app.route('/logout')
def logout():
    session.pop('email', None)
    return redirect(url_for("login"))
  • /logout is the routing used to log out and the function is logout

  • to delete the session we are using we can use the pop function from a session like this session.pop(). We can specify which session we will delete by passing it as the first parameter 'email' and the second parameter we value is none and then we can redirect with url_for().

  • Add logout button

In the frontend section, we need to add an interface so that the user can log out by clicking the button. Here is the frontend code:

profile.html

<!DOCTYPE html>
<html>
<head>
    <title>Template Jinja2</title>
</head>

<body>
    <h1>This is the profile page</h1>
    <h2 style="color:blue;">Hai my name is {{email}}</h1>
    <a href="{{url_for('logout')}}">Logout</a>
</body>
</html>

We can also use url_for() in the frontend section by access the logout function like this <a href="{{url_for('logout')}}">Logout</a>. After all stages are complete we can run our program and see the results as shown below:

ezgif.com-video-to-gif (2).gif

W can see in the picture above we have created a login system using the session contained on the server. so the session that we made only lasted about 2 hours. we have also learned how to redirect and check sessions to give access to routing that we will use. I hope you can develop this web application. That is all from me. thank you

Curriculum

Web development with python #1 : Flask initialization and Routing system

Web development with python #2 : Templating jinja2 and Method POST on routing system

Web development with python #3 : Get method, Query parameter and Navigate Routing

Web development with python #4: Store cookie and Get cookie in template

Proof of work done

https://github.com/milleaduski/python-web-app

Sort:  

I thank you for your contribution. Here are my thoughts. Note that, my thoughts are my personal ideas on your post and they are not directly related to the review and scoring unlike the answers I gave in the questionnaire;

  • Structure

    • I appreciate your improvement in the structure of the post. It looks better in my opinion. Thanks!
  • Language

    • I personally think the usage of the first person reduces the efficiency of the post. I advise you to consider using less first person. Still, this is a personal thought, don't get me wrong! :)

    • There are some sentences which are hard to understand because of the vocabulary and grammar. I advise you to proofread your posts before posting. It can increase the efficiency of your post.

  • Content

    • As I stated in my latest review, the content in your post is relatively simple. I personally appreciate tutorials which address complex matters more. Nonetheless, it is useful for beginners and I still appreciate it! :)

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Thank you for your review, @yokunjon! Keep up the good work!

Hey, @duski.harahap!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.26
TRX 0.11
JST 0.033
BTC 65012.58
ETH 3101.28
USDT 1.00
SBD 3.86