-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart3_template_inheritance_auth.py
65 lines (49 loc) · 1.6 KB
/
part3_template_inheritance_auth.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# import the Flask class from the flask module
from functools import wraps
from flask import Flask, render_template, redirect, \
url_for, request, session, flash
# create the application object
app = Flask(__name__)
# config
app.secret_key = 'my precious'
# login required decorator
def login_required(f):
@wraps(f)
def wrap(*args, **kwargs):
if 'logged_in' in session:
return f(*args, **kwargs)
else:
flash('You need to login first.')
return redirect(url_for('login'))
return wrap
# use decorators to link the function to a url
@app.route('/')
@login_required
def home():
return render_template('index2.html') # render a template
# return "Hello, World!" # return a string
@app.route('/welcome')
def welcome():
return render_template('welcome2.html') # render a template
# route for handling the login page logic
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if (request.form['username'] != 'admin') \
or request.form['password'] != 'admin':
error = 'Invalid Credentials. Please try again.'
else:
session['logged_in'] = True
flash('You were logged in.')
return redirect(url_for('home'))
return render_template('login2.html', error=error)
@app.route('/logout')
@login_required
def logout():
session.pop('logged_in', None)
flash('You were logged out.')
return redirect(url_for('welcome'))
# start the server with the 'run()' method
if __name__ == '__main__':
app.run(debug=True)