-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblog.py
83 lines (68 loc) · 2.08 KB
/
blog.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
78
79
80
81
82
83
# blog.py controller
#imports
from flask import Flask, render_template, request, session, flash, redirect, url_for, g
from functools import wraps
import sqlite3
# configuration
DATABASE = 'blog.db'
USERNAME = 'admin'
PASSWORD = 'admin'
SECRET_KEY = 'hard_to_guess'
app = Flask(__name__)
# pulls an app configuration by looking for UPPERCASE variables
app.config.from_object(__name__)
# function used for connecting the database
def connect_db():
return sqlite3.connect(app.config['DATABASE'])
def login_required(test):
@wraps(test)
def wrap(*args, **kwargs):
if 'logged_in' in session:
return test(*args, **kwargs)
else:
flash('You need to login first.')
return redirect(url_for('login'))
return wrap
@app.route('/', methods=['GET', 'POST'])
def login():
error = None
if request.method == "POST":
if request.form['username'] != app.config['USERNAME'] or request.form['password'] != app.config['PASSWORD']:
error = 'Invalid Credentials. Please try again.'
else:
session['logged_in'] = True
return redirect(url_for('main'))
return render_template('login.html', error = error)
@app.route('/main')
@login_required
def main():
g.db = connect_db()
cur = g.db.execute('select * from posts')
posts = [dict(title=row[0], post=row[1]) for row in cur.fetchall()]
g.db.close()
return render_template('main.html', posts=posts)
@app.route('/add', methods=['POST'])
@login_required
def add():
title = request.form['title']
post = request.form['post']
if not title or not post:
flash("All fields are required. Please try again.")
return redirect(url_for('main'))
else:
g.db = connect_db()
g.db.execute(
'insert into posts (title, post) values (?, ?)',
[request.form['title'], request.form['post']]
)
g.db.commit()
g.db.close()
flash('New entry was successfully posted!')
return redirect(url_for('main'))
@app.route('/logout')
def logout():
session.pop('logged_in', None)
flash('You were logged out')
return redirect(url_for('login'))
if __name__ == '__main__':
app.run(debug=True)