Exemplo n.º 1
0
def newBook():
	form = BookForm(formdata=request.form or None)
	print form.category.data, form.publisher.data, form.author.data
	if request.method == 'POST':
		if request.form and form.validate():
			category = Category.query.get(form.category.data)
			publisher = Publisher.query.get(form.publisher.data)
			author = Author.query.get(form.author.data)
			number = len(category.books.all()) + 1
			categoryShortName = category.shortName
			b = Book(number=number,
					title=form.title.data,
					author=[author],
					category=[category],
					publisher=[publisher],
					edition=form.edition.data,
					price=form.price.data,
					)
			#db.session.add(b)
			db.session.commit()
			return redirect(url_for('books', page=1))
		else:
		    flash('There was an error with your input: %s' % form.errors)
		    return redirect(url_for('newBook'))
		return redirect(redirectUrl)
	else:
		return render_template('newBook.html', form=form)
Exemplo n.º 2
0
def book():
	form = BookForm(request.form)
	if request.method == 'POST' and form.validate():
		building = form.building.data
		roomNum = form.room.data
		client = form.renter.data
		startDate = form.startDate.data
		endDate = form.endDate.data

		#write to database
		aRoom = db.session.query(Room).filter_by(building_id = building, number = roomNum).first()
		if not aRoom:
			err = "Room number " + str(roomNum) + " is not valid for the building " + str(building)
			return render_template('error.html', msg=err)
		aClient = db.session.query(Client).filter_by(name = client).first()
		if not aClient:
			session['bookInfo'] = json.dumps({'room' : roomNum, 'newRenterName':client, 'bookRoomId':xstr(aRoom.roomId), 'stDate':xstr(startDate), 'endDate':xstr(endDate)})
			return redirect(url_for('newRenter'))
		res = Reservation(arrive = startDate, depart = endDate, roomId = aRoom.roomId, clientId = aClient.clientId)

		termsDict = {'building': xstr(building), 'room':roomNum, 'client': '', 'stDate':xstr(startDate), 'endDate':xstr(endDate)}
		preRes = doSearch(termsDict)
		if bookDateCompare(preRes, termsDict):
			return render_template('error.html', msg="There is an issue with that room and date combination")
		try:
			db.session.add(res)
			db.session.commit()
		except (exc.InvalidRequestError, exc.ProgrammingError):
			db.session.rollback()
			err = "There is an issue booking that room for that set of dates, please try again. It is most likely there is a record for this user on those dates already."
			return render_template('error.html', msg=err)
		
	return render_template('book.html', form=form)
Exemplo n.º 3
0
def edit_book(request):
    form = BookForm(request.POST)
    if request.method == 'POST' and form.validate():
        form.populate_obj(user)
        user.save()
        redirect('edit_profile')
    return render_response('edit_profile.html', form=form)
Exemplo n.º 4
0
def add_book():
    form = BookForm(request.form)
    if request.method == 'POST' and form.validate():
        book = Book(form.title.data, form.authors.data)
        session.add(book)
        session.commit()
        return redirect(url_for('index'))
    return render_template('book_form.html', form=form, action="/book/add")
Exemplo n.º 5
0
def default():
    form = BookForm(request.form)
    if (request.method == 'POST' and form.validate()):
        print(form.data)
        add_book(form.data)
        book_list = get_books()
        return render_template('/home.html', bks=book_list)
    return render_template('create.html', form=form)
Exemplo n.º 6
0
def addbook():
    form = BookForm(request.form)
    if form.validate():
        b = Book(form.title.data)
        db_session.add(b)
        db_session.commit()
        return redirect(url_for("singlebook", b_id=b.id))
    else:
        return redirect(url_for("index"))
Exemplo n.º 7
0
def books_edit(book_id):
    book = Book.query.get_or_404(book_id)
    form = BookForm(request.form, obj=book)

    if request.method == "POST" and form.validate():
        book.title = form.data.get('title')
        db.session.commit()
        flash("Book changed")
        return redirect(url_for('books_view_all'))

    return render_template('books/edit.html', **locals())
Exemplo n.º 8
0
def books_add():
    form = BookForm(request.form)

    if request.method == "POST" and form.validate():
        new_book = Book(title=form.data.get('title'))
        new_book.authors = form.data.get('authors')
        db.session.add(new_book)
        db.session.commit()
        flash("Book added")
        return redirect(url_for('books_view_all'))

    return render_template('books/add.html', **locals())
Exemplo n.º 9
0
def create_book():
    if request.method == 'GET':
        form = BookForm()
    else:  # POST
        form = BookForm(request.form)
        if form.validate():
            book = Book('')
            form.populate_obj(book)
            db.session.add(book)
            db.session.commit()
            return redirect(url_for('edit_books'))
    return render_template('books_edit_page.html', form=form)
Exemplo n.º 10
0
def create_book():
    if request.method == 'GET':
        form = BookForm()
    else:   # POST
        form = BookForm(request.form)
        if form.validate():
            book = Book('')
            form.populate_obj(book)
            db.session.add(book)
            db.session.commit()
            return redirect(url_for('edit_books'))
    return render_template('books_edit_page.html', form=form)
Exemplo n.º 11
0
def edit_book(book_id):
    form = BookForm(request.form)
    if request.method == 'GET':
        form = BookForm(request.form, session.query(Book).get(book_id))
    if request.method == 'POST' and form.validate():
        book_edited = Book(form.title.data, form.authors.data)
        book_db = session.query(Book).get(book_id)
        book_db.title = book_edited.title
        book_db.authors = book_edited.authors
        session.commit()
        return redirect(url_for('index'))
    return render_template('book_form.html', form=form, action="/book/%s/edit" % book_id, submit_text="Save")
Exemplo n.º 12
0
def book():
    form = BookForm(request.form)
    if request.method == 'POST' and form.validate():
        building = form.building.data
        roomNum = form.room.data
        client = form.renter.data
        startDate = form.startDate.data
        endDate = form.endDate.data

        #write to database
        aRoom = db.session.query(Room).filter_by(building_id=building,
                                                 number=roomNum).first()
        if not aRoom:
            err = "Room number " + str(
                roomNum) + " is not valid for the building " + str(building)
            return render_template('error.html', msg=err)
        aClient = db.session.query(Client).filter_by(name=client).first()
        if not aClient:
            session['bookInfo'] = json.dumps({
                'room': roomNum,
                'newRenterName': client,
                'bookRoomId': xstr(aRoom.roomId),
                'stDate': xstr(startDate),
                'endDate': xstr(endDate)
            })
            return redirect(url_for('newRenter'))
        res = Reservation(arrive=startDate,
                          depart=endDate,
                          roomId=aRoom.roomId,
                          clientId=aClient.clientId)

        termsDict = {
            'building': xstr(building),
            'room': roomNum,
            'client': '',
            'stDate': xstr(startDate),
            'endDate': xstr(endDate)
        }
        preRes = doSearch(termsDict)
        if bookDateCompare(preRes, termsDict):
            return render_template(
                'error.html',
                msg="There is an issue with that room and date combination")
        try:
            db.session.add(res)
            db.session.commit()
        except (exc.InvalidRequestError, exc.ProgrammingError):
            db.session.rollback()
            err = "There is an issue booking that room for that set of dates, please try again. It is most likely there is a record for this user on those dates already."
            return render_template('error.html', msg=err)

    return render_template('book.html', form=form)
Exemplo n.º 13
0
def add_book():
    form = BookForm(request.form)
    if request.method == 'POST' and form.validate():
        book = Book(form.title.data, form.author.data)
        session.add(book)
        session.commit()
        return redirect(url_for('index'))
    return render_template('book_form.html',
                           form=form,
                           action="/book/add",
                           user_name=current_user.name,
                           user_picture=current_user.picture,
                           if_administrator=verify_administrator())
Exemplo n.º 14
0
def edit(id):
    qry = db.session.query(Book).filter(Book.id == id)
    book = qry.first()

    if book:
        form = BookForm(formdata=request.form, obj=book)
        if request.method == 'POST' and form.validate():
            # save edits
            save_changes(book, form, current_user)

            flash('Book updated successfully!')
            return redirect('/mybooks')
        return render_template('edit_book.html', form=form)
    else:
        return 'Error loading #{id}'.format(id=id)
Exemplo n.º 15
0
def book():
    form = BookForm(request.form)
    print(form)
    catgories = db_session.query(Category).all()
    # create category list
    catgories_list = [(category.id, category.name) for category in catgories]
    form.category.choices = catgories_list
    if request.method == 'POST' and form.validate():
        # auto generate category id in bettwen 10 - 20000
        book = Book(randint(10, 20000), form.category.data, form.name.data,
                    form.author.data, form.price.data, form.description.data,
                    form.image.data)
        db_session.add(book)
        return redirect('/home')
    return render_template('book_create.html', form=form)
Exemplo n.º 16
0
def book_update(book_id):
    book = session.query(Book).filter(Book.id == book_id).one()
    form = BookForm(obj=book)
    success = False
    if request.method == 'POST':
        form = BookForm(request.form)
        if form.validate():
            form.populate_obj(book)
            session.add(book)
            session.commit()
            success = True
    return render_template(
        'book_update.html', **{
            'book_id': book,
            'form': form,
            'success': success
        })
Exemplo n.º 17
0
def new_book():
    form = BookForm(request.form)
    if request.method == 'POST' and form.validate():
        book = Book()
        book.room_id = form.room_id.data
        book.dates = [form.date_from.data, form.date_to.data]
        book.client_id = form.client_id.data
        payment = Payment()
        payment.type = form.ptype.data
        payment.done = form.pdone.data
        book.payment = payment
        try:
            add_book(book)
        except ValidationError as e:
            return render_template('bookform.html', form=form, ermes=e.message)
        return redirect(url_for('history'))
    return render_template('bookform.html', form=form)
Exemplo n.º 18
0
def edit_book(book_id):
    form = BookForm(request.form)
    if request.method == 'GET':
        form = BookForm(request.form, session.query(Book).get(book_id))
    if request.method == 'POST' and form.validate():
        book_edited = Book(form.title.data, form.author.data)
        book_db = session.query(Book).get(book_id)
        book_db.title = book_edited.title
        book_db.authors = book_edited.authors
        session.commit()
        return redirect(url_for('index'))
    return render_template('book_form.html',
                           form=form,
                           action="/book/%s/edit" % (book_id),
                           submit_text="Save",
                           user_name=current_user.name,
                           user_picture=current_user.picture,
                           if_administrator=verify_administrator())
Exemplo n.º 19
0
def new_book():
    """
    Add a new book
    """
    form = BookForm(request.form)
    if request.method == 'POST' and form.validate():
        # save the book
        book = Book(book_name=form.book_name.data,
                    author=form.author.data,
                    genre=form.genre.data,
                    summary=form.summary.data,
                    lendee=current_user)
        db.session.add(book)
        db.session.commit()
        add_book_history(book, current_user, 'Added')
        #save_changes(book, form, new=True)
        flash('Book added successfully!')
        return redirect('/mybooks')
    return render_template('new_book.html', form=form)
Exemplo n.º 20
0
def edit_books(id_=None):
    if id_ is None:
        books = Book.query.all()
        return render_template('books_list_page.html', books=books)
    else:
        book = Book.query.get_or_404(id_)
        if request.method == 'GET':
            form = BookForm(obj=book)
        elif request.method == 'POST':
            form = BookForm(request.form)
            if form.validate():
                form.populate_obj(book)
                db.session.add(book)
                db.session.commit()
                return redirect(url_for('edit_books'))
        else:  # request.method == 'DELETE'
            db.session.delete(book)
            db.session.commit()
            return '', 200
    return render_template('books_edit_page.html', form=form, obj_id=book.id)
Exemplo n.º 21
0
def singlebook(b_id):
    book = Book.query.filter(Book.id == b_id).one()
    if request.method == "GET":
        authors = book.authors
        page = {'title': book.title}
        forms = {
            'book': BookForm(),
            'search': SearchForm()
        }
        return render_template("book.html", **locals())
    elif request.method == "POST":
        form = BookForm(request.form)
        if form.validate():
            book.title = form.title.data
            db_session.commit()
        return redirect(url_for("singlebook", b_id=b_id))
    elif request.method == "DELETE":
        db_session.delete(book)
        db_session.commit()
        return url_for("index")
Exemplo n.º 22
0
def delete(id):
    """
    Delete the item in the database that matches the specified
    id in the URL
    """
    qry = db.session.query(Book).filter(Book.id == id)
    book = qry.first()

    if book:
        form = BookForm(formdata=request.form, obj=book)
        if request.method == 'POST' and form.validate():
            # delete the item from the database
            db.session.delete(book)
            db.session.commit()

            flash('Book deleted successfully!')
            return redirect('/mybooks')
        return render_template('delete_book.html', form=form)
    else:
        return 'Error deleting #{id}'.format(id=id)
Exemplo n.º 23
0
def edit_books(id_=None):
    if id_ is None:
        books = Book.query.all()
        return render_template('books_list_page.html', books=books)
    else:
        book = Book.query.get_or_404(id_)
        if request.method == 'GET':
            form = BookForm(obj=book)
        elif request.method == 'POST':
            form = BookForm(request.form)
            if form.validate():
                form.populate_obj(book)
                db.session.add(book)
                db.session.commit()
                return redirect(url_for('edit_books'))
        else:    # request.method == 'DELETE'
            db.session.delete(book)
            db.session.commit()
            return '', 200
    return render_template('books_edit_page.html', form=form, obj_id=book.id)
Exemplo n.º 24
0
def add_book():
    form = BookForm()
    if request.method == 'POST' and form.validate():
        books = session.query(models.Books).all()
        # Creating a books object to add to the databse.
        book = Books(book_img=request.form['book_img'],
                     book_title=request.form['book_title'],
                     book_author=request.form['book_author'],
                     book_description=request.form['book_description'],
                     book_url=request.form['book_url'],
                     language_id=request.form['language_id'],
                     user_id=login_session['user_id'])
        session.add(book)
        session.commit()
        return redirect(url_for('books.index'))
    else:
        return render_template('add_book.jinja2',
                               languages=c.get_languages(),
                               form=form,
                               user=c.get_current_user())
Exemplo n.º 25
0
def edit_book(id):
    '''Editing or adding new book depends on given id.'''
    if id == 'new':
        book = Book()
    else:
        book = Book.query.filter_by(id=id).first_or_404()
    form = BookForm(request.form, obj=book)
    if request.method == 'GET':
        return render_template('edit_book.html', form=form)
    if request.method == 'POST' and form.validate():
        form.populate_obj(book)
        book.title = form.title.data
        book.authors = form.authors.data
        if id == 'new':
            db.session.add(book)
            flash('Book was successfully added')
        else:
            db.session.merge(book)
            flash('Book was successfully updated')
        db.session.commit()
        return redirect(url_for('book', id=book.id))
    else:
        return render_template('edit_book.html', form=form)
Exemplo n.º 26
0
def edit_book(number):
	amazon_img = False
	if number == 'new':
		book = Book()
		book.mass = 0
		book.width = 0
		book.length = 0
		book.thickness = 0
		title = 'Ajouter un livre dans la bibliotheque'
	elif number[0:7] == 'amazon:':
		import urllib
		asin=unicode(number[7:])
		amazon = bottlenose.Amazon(AWS_KEY,AMAZON_SECRET_KEY,LANG)
		#
		# we fetch the primary informations from large group amazon search
		#
		fetch = amazon.ItemLookup(IdType='ASIN', ItemId= asin, ResponseGroup='Large')
		xml = objectify.fromstring(fetch)
		book = Book()
		try:
			book.title = unicode(xml.Items.Item.ItemAttributes.Title)
		except AttributeError:
			book.title = ''
		try:
			amazon_img = unicode(xml.Items.Item.LargeImage.URL)
		except AttributeError:
			amazon_img = ''
		try:
			book.isbn = unicode(xml.Items.Item.ItemAttributes.ISBN)
		except AttributeError:
			book.isbn = ''
		try:
			book.ean = unicode(xml.Items.Item.ItemAttributes.EAN)
		except AttributeError:
			book.ean = ''
		try:
			book.publisher = unicode(xml.Items.Item.ItemAttributes.Publisher)
		except AttributeError:
			book.publisher = ''
		
		#
		# amazon works in US units (hundreds-inches and pounds). I want them in kilos and cm, so I import the data in float and translate.
		#
		try:
			thickness = float(xml.Items.Item.ItemAttributes.PackageDimensions.Height)
			book.thickness = round(thickness * 2.54/100, 1)
		except AttributeError:
			book.thickness = ''
		try:
			length = float(xml.Items.Item.ItemAttributes.PackageDimensions.Length)
			book.length = round(length * 2.54/100, 1)
		except AttributeError:
			book.length = ''
		try:
			width = float(xml.Items.Item.ItemAttributes.PackageDimensions.Width)
			book.width = round(width * 2.54/100, 1)
		except AttributeError:
			book.width = ''
		try:
			mass = float(xml.Items.Item.ItemAttributes.PackageDimensions.Weight)
			book.mass = round(mass * 0.45/100,2)
		except AttributeError:
			book.mass = ''
		try:
			book.numberofpages = int(xml.Items.Item.ItemAttributes.NumberOfPages)
		except AttributeError:
			book.numberofpages = ''
		try:
			book.summary = unicode(xml.Items.Item.EditorialReviews.EditorialReview.Content)
		except AttributeError:
			book.summary = ''
		title = 'Ajouter un livre d\'Amazon dans la bibliotheque'

	else:
		book = Book.query.get(number)
		title = book.title
		if os.path.exists('app/static/covers/' + str(book.id)):
			book.img = True
	form = BookForm()
	form.authortoadd.choices = Author.query.filter(Author!=book.authors)
	update = False
	#if form.validate_on_submit():
	if request.form=='POST' and form.validate():
		#print form.errors
		book.title = unicode(form.title.data)
		# on ajoute les élements en dessous, mais s'ils ne sont pas là, c'est pas grave !
		if form.ean.data != book.ean:
			book.ean = unicode(form.ean.data)
			update = True
		if form.isbn.data != book.isbn:
			book.isbn = unicode(form.isbn.data)
			update = True
		if form.thickness.data != book.thickness:
			book.thickness = unicode(form.thickness.data)
			update = True
		if form.width.data != book.width:
			book.width = unicode(form.width.data)
			update = True
		if form.length.data != book.length:
			book.length = form.length.data
			update = True
		if form.summary.data != book.summary and form.summary.data != None:
			book.summary = unicode(form.summary.data)
			update = True
		if form.mass.data != book.mass:
			book.mass = form.mass.data
			update = True
		#if form.numberofpages.data != book.numberofpages:
		#	book.numberofpages = int(form.numberofpages.data)
		#	if type(book.numberofpages) == 'int'
		#		update = True
		if form.publisher.data != book.publisher and form.publisher.data != None:
			book.publisher = unicode(form.publisher.data)
			update = True
		#
		# gestion des auteurs
		if request.form.getlist('authortodelete'):
			for item in request.form.getlist('authortodelete'):
				a = Author.query.get(item)
				book.remove_author(a)
				update = True
		#
		if request.form.getlist('authortoadd'):
			for item in request.form.getlist('authortoadd'):
				# Same as authors, see upside.
				if item != '__None':
					a = Author.query.get(item)
					book.add_author(a)
					update = True
		# adding the book to the db
		if update:
			db.session.add(book)
			db.session.commit()
			db.session.refresh(book)
		
		image_finale = False
		
		if amazon_img:
			image_finale = urllib.urlopen(amazon_img)
			
		if request.method == 'POST' and request.files['cover']:
			image_finale = request.files['cover']
			
		if image_finale:
			fileurl = 'app/static/covers/' + str(book.id)
			image = FileStorage(image_finale).save(fileurl)
				
		return redirect('/admin')
	return render_template('edit_book.html', form = form, book = book, title = title, amazon_img = amazon_img)