Adding views and schema.

This commit is contained in:
John Washam
2016-06-30 19:03:09 -07:00
parent 255001f40d
commit 4b1cf0afdb
8 changed files with 240 additions and 2 deletions

View File

@@ -1,11 +1,111 @@
from flask import Flask
import os
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash
app = Flask(__name__)
app.config.from_object(__name__)
# Load default config and override config from an environment variable
app.config.update(dict(
DATABASE=os.path.join(app.root_path, 'cards.db'),
SECRET_KEY='development key',
USERNAME='admin',
PASSWORD='default'
))
app.config.from_envvar('CARDS_SETTINGS', silent=True)
def connect_db():
rv = sqlite3.connect(app.config['DATABASE'])
rv.row_factory = sqlite3.Row
return rv
def init_db():
db = get_db()
with app.open_resource('data/schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
def get_db():
"""Opens a new database connection if there is none yet for the
current application context.
"""
if not hasattr(g, 'sqlite_db'):
g.sqlite_db = connect_db()
return g.sqlite_db
@app.teardown_appcontext
def close_db(error):
"""Closes the database again at the end of the request."""
if hasattr(g, 'sqlite_db'):
g.sqlite_db.close()
# -----------------------------------------------------------
# Uncomment and use this to initialize database, then comment it
# You can rerun it to pave the database and start over
# @app.route('/initdb')
# def initdb():
# init_db()
# return 'Initialized the database.'
@app.route('/')
def index():
return 'Hello World, you ready to learn?'
return render_template('index.html')
@app.route('/cards')
def cards():
db = get_db()
cur = db.execute('SELECT type, front, back, known FROM cards ORDER BY id DESC')
cards = cur.fetchall()
return render_template('cards.html', cards=cards)
@app.route('/add', methods=['POST'])
def add_card():
if not session.get('logged_in'):
abort(401)
db = get_db()
db.execute('INSERT INTO cards (type, front, back) VALUES (?, ?, ?)',
[request.form['type'],
request.form['front'],
request.form['back']
])
db.commit()
flash('New card was successfully added.')
return redirect(url_for('cards'))
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
# return request.form['username'] + " / " + app.config['USERNAME'] + " / " \
# + request.form['password'] + " / " + app.config['PASSWORD']
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('cards'))
return render_template('login.html', error=error)
@app.route('/logout')
def logout():
session.pop('logged_in', None)
flash("You've logged out")
return redirect(url_for('index'))
if __name__ == '__main__':