forked from realpython/discover-flask
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
77 lines (59 loc) · 1.89 KB
/
app.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
66
67
68
69
70
71
72
73
74
75
76
77
# import the Flask class from the flask module
from flask import Flask, render_template, redirect, \
url_for, request, session, flash
from functools import wraps
from flask.ext.sqlalchemy import SQLAlchemy
# create the application object
app = Flask(__name__)
# config
import os
app.config.from_object(os.environ['APP_SETTINGS'])
# create the sqlalchemy object
db = SQLAlchemy(app)
# import db schema
from models import *
# 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 "Hello, World!" # return a string
posts = db.session.query(BlogPost).all()
return render_template('index.html', posts=posts) # render a template
@app.route('/welcome')
def welcome():
return render_template('welcome.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('login.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'))
# connect to database
def connect_db():
return sqlite3.connect('posts.db')
# start the server with the 'run()' method
if __name__ == '__main__':
app.run()