def create(): if request.method == 'POST': title = request.form['title'] author = request.form['author'] publish_year = request.form['publish_year'] error = None if not title: error = 'Title is required.' if not author: error = 'Author is required.' if not publish_year: error = 'Publish Year is required.' if error is not None: flash(error) else: db = get_db() db.execute( 'INSERT INTO books (title, author, publish_year)' ' VALUES (?, ?, ?)', (title, author, publish_year)) db.commit() return redirect(url_for('books.index')) return render_template('books/create.html')
def load_logged_in_user(): user_id = session.get('user_id') if user_id is None: g.user = None else: g.user = get_db().execute('SELECT * FROM user WHERE id = ?', (user_id, )).fetchone()
def index(): """Show all the posts, most recent first.""" db = get_db() books = db.execute( 'SELECT id, title, author, publisher, publish_year FROM books' ).fetchall() # books = [ # {'title': 'The Collapsing Empire', 'author': 'John Scalzi', 'published': '2017'}, # {'title': "Mote in God's Eye", 'author': 'Larry Niven', 'published': '1998'}, # {'title': 'Red Moon', 'author': 'Kim Stanley Robinson', 'published': '2018'}, # {'title': 'The Consuming Fire', 'author': 'John Scalzi', 'published': '2018'} # ] return render_template('books/index.html', books=books)
def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] db = get_db() error = None user = db.execute('SELECT * FROM user WHERE username = ?', (username, )).fetchone() if user is None: error = 'Incorrect username.' elif not check_password_hash(user['password'], password): error = 'Incorrect password.' if error is None: session.clear() session['user_id'] = user['id'] return redirect(url_for('index')) flash(error) return render_template('auth/login.html')
def register(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] db = get_db() error = None if not username: error = 'Username is required.' elif not password: error = 'Password is required.' elif db.execute('SELECT id FROM user WHERE username = ?', (username, )).fetchone() is not None: error = 'User {} is already registered.'.format(username) if error is None: db.execute('INSERT INTO user (username, password) VALUES (?, ?)', (username, generate_password_hash(password))) db.commit() return redirect(url_for('auth.login')) flash(error) return render_template('auth/register.html')