create account

Web development with python #5 : Session in flask and Login and Logout system by duski.harahap

View this thread on: hive.blogpeakd.comecency.com
· @duski.harahap · (edited)
$16.36
Web development with python #5 : Session in flask and Login and Logout system
#### 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
- Python - https://www.python.org/
- Flask - http://flask.pocoo.org/
- Jinja2 -http://jinja.pocoo.org/docs/2.10/

#### 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](https://steemit.com/utopian-io/@duski.harahap/web-development-with-python-5-store-cookie-and-get-cookie-in-template-1543593496200). 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 the``` app```.
<br>
- **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.
<br>

- **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](https://steemit.com/utopian-io/@duski.harahap/web-developement-with-python-3-get-method-query-parameter-and-navigate-routing-1543411189705).After all steps have been completed, We can see the results as shown below:

![ezgif.com-video-to-gif.gif](https://ipfs.busy.org/ipfs/QmeuDAu942Ta2BRbLRYTyRzej6ThErJD8YFB5kWCmciqQt)

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  ```milleaduski@gmail.com```.

![Screenshot_1.png](https://ipfs.busy.org/ipfs/QmXbXpQg9w3yDojUV7ScfMAmdS4KWMhdWJ1ZjDqBCkmKZu)
<br>
- **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](https://ipfs.busy.org/ipfs/QmY83n3sysWEYBofUddtWxv4EB8392VdqZiD5Gf6ZLXQ7K)


### 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()```.
<br>

- **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](https://ipfs.busy.org/ipfs/QmXqxwbvzYeEhgM5n2hTogKLmF5Q8B7x3aSikdCrKYXFTw)


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](https://steemit.com/utopian-io/@duski.harahap/web-developement-with-python-1-flask-initialization-and-routing-system-1542726589553)

[Web development with python #2 : Templating jinja2 and Method POST on routing system](https://steemit.com/utopian-io/@duski.harahap/web-developement-with-python-2-templating-jinja2-and-method-post-on-routing-system-1542987551736)

[Web development with python #3 : Get method, Query parameter and Navigate Routing](https://steemit.com/utopian-io/@duski.harahap/web-developement-with-python-3-get-method-query-parameter-and-navigate-routing-1543411189705)

[Web development with python #4: Store cookie and Get cookie in template](https://steemit.com/utopian-io/@duski.harahap/web-development-with-python-5-store-cookie-and-get-cookie-in-template-1543593496200)


#### Proof of work done

https://github.com/milleaduski/python-web-app
πŸ‘  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 8 others
properties (23)
authorduski.harahap
permlinkweb-development-with-python-5-session-in-flask-and-login-and-logout-system-1544025770372
categoryutopian-io
json_metadata{"app":"steemit/0.1","format":"markdown","image":["https://ipfs.busy.org/ipfs/QmeuDAu942Ta2BRbLRYTyRzej6ThErJD8YFB5kWCmciqQt","https://ipfs.busy.org/ipfs/QmXbXpQg9w3yDojUV7ScfMAmdS4KWMhdWJ1ZjDqBCkmKZu","https://ipfs.busy.org/ipfs/QmY83n3sysWEYBofUddtWxv4EB8392VdqZiD5Gf6ZLXQ7K","https://ipfs.busy.org/ipfs/QmXqxwbvzYeEhgM5n2hTogKLmF5Q8B7x3aSikdCrKYXFTw"],"tags":["utopian-io","tutorials","python","flask","web"],"links":["https://github.com/python","https://www.python.org/","http://flask.pocoo.org/","http://jinja.pocoo.org/docs/2.10/","https://steemit.com/utopian-io/@duski.harahap/web-development-with-python-5-store-cookie-and-get-cookie-in-template-1543593496200","https://steemit.com/utopian-io/@duski.harahap/web-developement-with-python-3-get-method-query-parameter-and-navigate-routing-1543411189705","https://steemit.com/utopian-io/@duski.harahap/web-developement-with-python-1-flask-initialization-and-routing-system-1542726589553","https://steemit.com/utopian-io/@duski.harahap/web-developement-with-python-2-templating-jinja2-and-method-post-on-routing-system-1542987551736","https://github.com/milleaduski/python-web-app"]}
created2018-12-05 16:02:54
last_update2018-12-06 02:47:09
depth0
children3
last_payout2018-12-12 16:02:54
cashout_time1969-12-31 23:59:59
total_payout_value12.368 HBD
curator_payout_value3.993 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length8,624
author_reputation60,094,717,098,672
root_title"Web development with python #5 : Session in flask and Login and Logout system"
beneficiaries
0.
accountutopian.pay
weight500
max_accepted_payout100,000.000 HBD
percent_hbd10,000
post_id76,405,015
net_rshares28,168,964,645,437
author_curate_reward""
vote details (72)
@utopian-io ·
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](https://chrome.google.com/webstore/detail/steemplus/mjbkjgcplmaneajhcbegoffkedeankaj?hl=en) or [Steeditor](https://steeditor.app)).

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

<a href='https://steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1'>Vote for Utopian Witness!</a>
properties (22)
authorutopian-io
permlinkre-web-development-with-python-5-session-in-flask-and-login-and-logout-system-1544025770372-20181208t020452z
categoryutopian-io
json_metadata"{"app": "beem/0.20.9"}"
created2018-12-08 02:04:54
last_update2018-12-08 02:04:54
depth1
children0
last_payout2018-12-15 02:04:54
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length595
author_reputation152,955,367,999,756
root_title"Web development with python #5 : Session in flask and Login and Logout system"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id76,524,270
net_rshares0
@yokunjon ·
$7.71
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](https://join.utopian.io/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](https://review.utopian.io/result/8/2-1-2-1-1-4-3-4-).

---- 
Need help? Write a ticket on https://support.utopian.io/. 
Chat with us on [Discord](https://discord.gg/uTyJkNm). 
[[utopian-moderator]](https://join.utopian.io/)
πŸ‘  , , , , , , , , , , , ,
properties (23)
authoryokunjon
permlinkre-duskiharahap-web-development-with-python-5-session-in-flask-and-login-and-logout-system-1544025770372-20181207t072450177z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"links":["https://join.utopian.io/guidelines","https://review.utopian.io/result/8/2-1-2-1-1-4-3-4-","https://support.utopian.io/","https://discord.gg/uTyJkNm","https://join.utopian.io/"],"app":"steemit/0.1"}
created2018-12-07 07:24:51
last_update2018-12-07 07:24:51
depth1
children1
last_payout2018-12-14 07:24:51
cashout_time1969-12-31 23:59:59
total_payout_value5.840 HBD
curator_payout_value1.873 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,498
author_reputation19,266,807,595,513
root_title"Web development with python #5 : Session in flask and Login and Logout system"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id76,486,245
net_rshares12,684,897,933,891
author_curate_reward""
vote details (13)
@utopian-io ·
Thank you for your review, @yokunjon! Keep up the good work!
πŸ‘  
properties (23)
authorutopian-io
permlinkre-re-duskiharahap-web-development-with-python-5-session-in-flask-and-login-and-logout-system-1544025770372-20181207t072450177z-20181209t120243z
categoryutopian-io
json_metadata"{"app": "beem/0.20.9"}"
created2018-12-09 12:02:45
last_update2018-12-09 12:02:45
depth2
children0
last_payout2018-12-16 12:02:45
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length60
author_reputation152,955,367,999,756
root_title"Web development with python #5 : Session in flask and Login and Logout system"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id76,584,578
net_rshares14,145,948,720
author_curate_reward""
vote details (1)