forked from mjhea0/flaskr-tdd
-
Notifications
You must be signed in to change notification settings - Fork 140
/
Copy pathapp.py
102 lines (80 loc) · 2.78 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# imports
import os
from flask import Flask, request, session, g, redirect, url_for, \
abort, render_template, flash, jsonify
from flask_sqlalchemy import SQLAlchemy
# get the folder where this file runs
basedir = os.path.abspath(os.path.dirname(__file__))
# configuration
DATABASE = 'flaskr.db'
DEBUG = True
SECRET_KEY = 'my_precious'
USERNAME = 'admin'
PASSWORD = 'admin'
# define the full path for the database
DATABASE_PATH = os.path.join(basedir, DATABASE)
# database config
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + DATABASE_PATH
SQLALCHEMY_TRACK_MODIFICATIONS = False
# create app
app = Flask(__name__)
app.config.from_object(__name__)
db = SQLAlchemy(app)
import models
@app.route('/')
def index():
"""Searches the database for entries, then displays them."""
entries = db.session.query(models.Flaskr)
return render_template('index.html', entries=entries)
@app.route('/add', methods=['POST'])
def add_entry():
"""Adds new post to the database."""
if not session.get('logged_in'):
abort(401)
new_entry = models.Flaskr(request.form['title'], request.form['text'])
db.session.add(new_entry)
db.session.commit()
flash('New entry was successfully posted')
return redirect(url_for('index'))
@app.route('/login', methods=['GET', 'POST'])
def login():
"""User login/authentication/session management."""
error = None
if request.method == 'POST':
if request.form['username'] != app.config['USERNAME']:
error = 'Invalid username'
elif request.form['password'] != app.config['PASSWORD']:
error = 'Invalid password'
else:
session['logged_in'] = True
flash('You were logged in')
return redirect(url_for('index'))
return render_template('login.html', error=error)
@app.route('/logout')
def logout():
"""User logout/authentication/session management."""
session.pop('logged_in', None)
flash('You were logged out')
return redirect(url_for('index'))
@app.route('/delete/<int:post_id>', methods=['GET'])
def delete_entry(post_id):
"""Deletes post from database."""
result = {'status': 0, 'message': 'Error'}
try:
new_id = post_id
db.session.query(models.Flaskr).filter_by(post_id=new_id).delete()
db.session.commit()
result = {'status': 1, 'message': "Post Deleted"}
flash('The entry was deleted.')
except Exception as e:
result = {'status': 0, 'message': repr(e)}
return jsonify(result)
@app.route('/search/', methods=['GET'])
def search():
query = request.args.get("query")
entries = db.session.query(models.Flaskr)
if query:
return render_template('search.html', entries=entries, query=query)
return render_template('search.html')
if __name__ == '__main__':
app.run()