Skip to content

Instantly share code, notes, and snippets.

@krpeacock
Created June 27, 2016 16:24
Show Gist options
  • Save krpeacock/06d745a37ca19f0723b77fd2ca176dee to your computer and use it in GitHub Desktop.
Save krpeacock/06d745a37ca19f0723b77fd2ca176dee to your computer and use it in GitHub Desktop.
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
# Flask - class used to initialize an app
# render_template - render a template
# request - getting form data via POST request
# redirect - respond with location header
# url_for - shorthand for using function name instead of name of route
from flask_modus import Modus
app = Flask(__name__)
modus = Modus(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://localhost/library_in_class'
db = SQLAlchemy(app)
# Modus - allows us to do method override via headers or query string
# with ?_method
# from models import Book
class Book(db.Model):
__tablename__ = 'books'
id = db.Column(db.Integer, primary_key = True)
title = db.Column(db.Text())
author = db.Column(db.Text())
# every book should have a title, author and id
def __init__(self,title,author):
self.title = title
self.author = author
def __repr__(self):
return 'title: {}, author: {}'.format(self.title, self.author)
db.create_all()
# from IPython import embed
# embed()
@app.route('/')
def root():
return redirect(url_for('index'))
# INDEX
@app.route('/books')
def index():
return render_template('index.html', books = Book.query.all())
# NEW
@app.route('/books/new')
def new():
return render_template('new.html')
# SHOW
@app.route('/books/<int:id>')
def show(id):
return render_template('show.html', book = Book.find(id))
# EDIT
@app.route('/books/<int:id>/edit')
def edit(id):
return render_template('edit.html', book = Book.find(id))
# CREATE
@app.route('/books', methods=["POST"])
def create():
Book(request.form['title'],request.form['author'])
return redirect(url_for('index'))
# UPDATE
@app.route('/books/<int:id>', methods=["PATCH"])
def update(id):
found_book = Book.find(id)
found_book.title = request.form['title']
found_book.author = request.form['author']
return redirect(url_for('index'))
# DELETE
@app.route('/books/<int:id>', methods=["DELETE"])
def destroy(id):
found_book = Book.find(id)
Book.book_list.remove(found_book)
return redirect(url_for('index'))
if __name__ == '__main__':
app.run(debug=True, port=3000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment