def books_list(): form = BookForm() error = "" if request.method == "POST": if form.validate_on_submit(): books.create(form.data) books.save_all() if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] if file.filename == '': flash('No selected file') return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) flash("File is uploaded") return redirect(url_for('uploaded_file', filename=filename)) if form.validate_on_submit(): books.create(form.data) books.save_all() return redirect(url_for("books_list")) return render_template("books.html", form=form, books=books.all(), error=error)
def bookin(): """ 书籍录入 输入书籍的名字,将书籍的 书名, 封面, 简介 录入数据库 """ if current_user.username == 'neo1218': form = BookForm() if form.validate_on_submit(): bookname = form.bookname.data get_url = "https://api.douban.com/v2/book/search?q=%s" % bookname resp_1 = json.loads(urlopen(get_url).read().decode('utf-8')) book_id = resp_1['books'][0]['id'] url = "https://api.douban.com/v2/book/%s" % book_id resp_2 = json.loads(urlopen(url).read().decode('utf-8')) book = Book(url=url, name=resp_2['title'], author=resp_2['author'][0], \ tag=form.tag.data, summary=resp_2['summary'], \ image=resp_2['images'].get('large'), user_id=None, end=None, \ status=False) db.session.add(book) db.session.commit() flash('书籍已录入!') return redirect(url_for('bookin')) return render_template('bookin.html', form=form) else: return redirect(url_for('home'))
def add(): form = BookForm() print form.name.data if form.validate_on_submit(): if b_img: b_img = form.imgname.data else: b_img = 'default.jpg' b_name = form.name.data b_category = form.category.data b_press = form.press.data b_author = form.author.data b_note = form.note.data b = Book(name=b_name, img=b_img, category=b_category, press=b_press, author=b_author, note=b_note, status=False, num=0) db.session.add(b) db.session.commit() if is_not_admin(): time = datetime.now() give = Give(author=g.user.id, book_id=b.id, time=time, status=0) db.session.add(give) db.session.commit() flash("添加成功,等待管理员审核") return redirect(url_for('info', b_id=b.id)) return render_template('book_add.html', g=g, form=form)
def create_listing(): form = BookForm() if form.validate_on_submit(): new_book = Book(isbn=int(form.isbn.data), owner=current_user.user_id) session = Session() session.add(new_book) session.commit() new_transaction = Transaction( seller=current_user.user_id, book=new_book.book_id, address_from=form.streetNameNum.data + " " + form.city.data + ", " + form.state.data + " " + form.zipcode.data) session.add(new_transaction) user = session.query(User).filter( User.user_id == current_user.user_id).first() user.credits += 1 user.totalcredit += 1 session.commit() return redirect( url_for( "index", msg= "The Magic Bookshelf📚 applauds your generosity! You have earned [✨Arcane Dust x1]" )) # Very important, make sure to initialize the field of the OWNER's # associated user's ID after the post request. To be handled later return render_template('create_listing.html', form=form)
def index(): form = BookForm() if form.validate_on_submit(): results = models.Book.select().where( models.Book.ISBN_13 == form.ISBN_13.data.strip() or models.Book.ISBN_10 == form.ISBN_10.data.strip()).limit(1) if len(results) > 0: book = results[0] else: book = None if book == None: models.Book.create(image=form.image.data.strip(), title=form.title.data.strip(), author=form.author.data.strip(), ISBN_13=form.ISBN_13.data.strip(), ISBN_10=form.ISBN_10.data.strip(), date_published=form.date_published.data.strip(), description=form.description.data.strip(), total_pages=form.total_pages.data) flash("Added new book, titled: {}".format(form.title.data), "alert alert-success") book = models.Book.get( models.Book.ISBN_13 == form.ISBN_13.data.strip() or models.Book.ISBN_10 == form.ISBN_10.data.strip()) return redirect("/setgoal/{}".format(book.id)) return render_template("add_book.html", title="Add Form", form=form)
def bookform(): form = BookForm() if form.validate_on_submit(): conn = sqlite3.connect('bookdata') cur = conn.cursor() all_books = cur.execute('SELECT * FROM BooksTable;').fetchall() id = str(uuid.uuid4()) fileName = 'bookPhoto_' + str(id) book_dict = { 'Author': form.author.data, 'Title': form.title.data, 'Rating': int(form.rating.data), 'Description': form.description.data, 'FileName': fileName, 'ID': id } form.photo.data.save("static/userImages/" + fileName + ".png") cur.execute("INSERT INTO BooksTable VALUES (?,?,?,?,?,?)", [ book_dict["ID"], book_dict["Title"], book_dict["Author"], book_dict["Rating"], book_dict["FileName"], book_dict["Description"] ]) conn.commit() conn.close() return redirect('/index') return render_template('bookform.html', form=form)
def addbook(): if current_user.status == 1: bookform = BookForm() if request.method == "POST": isbn = request.form.get('isbn') name = request.form.get('name') price = request.form.get('price') author = request.form.get('author') book = Book(isbn=isbn, price=price, name=name, author=author, num=1) if bookform.validate_on_submit(): try: db.session.add(book) db.session.commit() flash('添加图书成功') except Exception as e: flash('添加书籍失败') return redirect(url_for('showallbooks')) return render_template('addbook.html', bookform=bookform) else: return ' permission denied'
def book(): form = BookForm() if form.validate_on_submit(): if session.get('is_admin'): if form.g_id.data is None: flash('Input guest id') return render_template('book.html', form=form) else: session['g_id'] = form.g_id.data else: session['g_id'] = session.get('user_id') today = datetime.date.today() check_in = form.check_in.data check_out = form.check_out.data if check_out <= check_in or check_in < today: flash('Illegal date input') return render_template('book.html', form=form) cur = mysql.connection.cursor() # 从所有房间中找出还没被预定的房间 check_in = check_in.strftime('%Y-%m-%d') check_out = check_out.strftime('%Y-%m-%d') cur.execute( 'select * from room where r_id not in (select r_id from booking where `from`<%s and `to`>%s)', [check_out, check_in]) rooms = cur.fetchall() session['check_in'] = check_in session['check_out'] = check_out session['meal'] = form.meal.data session['num_adult'] = form.num_adult.data session['num_child'] = form.num_child.data return render_template('select_rooms.html', rooms=rooms) return render_template('book.html', form=form)
def bookin(): """ 书籍录入 输入书籍的名字,将书籍的 书名, 封面, 简介 录入数据库 """ if current_user.role_id == 2: form = BookForm() if form.validate_on_submit(): bookname = form.bookname.data get_url = "https://api.douban.com/v2/book/search?q=%s" % bookname resp_1 = json.loads(urlopen(get_url).read().decode('utf-8')) book_id = resp_1['books'][0]['id'] url = "https://api.douban.com/v2/book/%s" % book_id resp_2 = json.loads(urlopen(url).read().decode('utf-8')) book = Book(url=url, name=resp_2['title'], author=resp_2['author'][0], \ tag=form.tag.data, summary=resp_2['summary'], \ image=resp_2['images'].get('large'), user_id=None, end=None, \ status=False) db.session.add(book) db.session.commit() flash('书籍已录入!') return redirect(url_for('books.bookin')) return render_template('bookin.html', form=form) else: return redirect(url_for('books.home'))
def add_book(): """ Function to load WTForm for adding book and render to html and add to database. Checks first whether a user is logged in, before performing function. WTForms code adapted from Corey Shafer's tutorial found at https://www.youtube.com/watch?v=UIJKdCIEXUQ&list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH&index=3 """ # Check to see if user logged in and render html if g.user: form = BookForm() # Validation of form and insert in collection if form.validate_on_submit(): flash(f"New book added: {form.title.data.title()}!", "success") book = { "title": form.title.data.lower(), "author_fname": form.author_fname.data.lower(), "author_lname": form.author_lname.data.lower(), "category_id": form.category_id.data, "user_id": g.user, "up_votes": 0, "down_votes": 0, "date_added": date.today().strftime("%Y/%m/%d"), "cover_url": form.cover_url.data, "csrf_token": form.csrf_token.data } books = mongo.db.books books.insert_one(book) return redirect( url_for( "get_books", _scheme="https", _external=True)) # Check to see type of user and return of form for correction else: super_user = mongo.db.users.find_one({"username": "******"}) if g.user == str(super_user["_id"]): return render_template( "addbook.html", form=form, categories=mongo.db.categories.find().sort("category_name"), super_user=g.user) else: return render_template( "addbook.html", form=form, categories=mongo.db.categories.find().sort("category_name"), regular_user=g.user) else: flash(f"You need to log in first...", "warning") return redirect( url_for( "log_user_in", _scheme="https", _external=True))
def book_details(book_id): book = books.get(book_id - 1) form = BookForm(data=book) if request.method == "POST": if form.validate_on_submit(): books.update(book_id - 1, form.data) return redirect(url_for("books_list")) return render_template("book.html", form=form, book_id=book_id)
def index(): form = BookForm(csrf_enabled=False) if form.validate_on_submit(): # Check the password and log the user in # [...] artist=Main.main(form.book.data) return redirect(url_for('index')) return redirect(url_for('qwerty')) return render_template('index.html', form=form)
def dispatch_request(self, obj_id): obj = Book.query.get_or_404(obj_id) form = BookForm(obj=obj) form.authors.query = Author.query.join(Book.authors).union(Author.query) if request.method == "POST": if form.validate_on_submit(): form.populate_obj(obj) obj.save() return redirect("/books/") return render_template("book_edit.html", form=form, obj=obj)
def home(): phrase = None sentence = None form = BookForm() if form.validate_on_submit(): phrase = form.book.data MarkovChain = TextCreator(form.book.data) sentence = MarkovChain.generate_text(output_length=20) form.book.data = '' return render_template('home.html', form=form, phrase=phrase, sentence=sentence)
def cadastro(): form = BookForm() if form.validate_on_submit(): book = Book(titulo=request.form['titulo'], autor=request.form['autor'], editora=request.form['editora'], categoria=request.form['categoria'], tipo=request.form['tipo'], status=request.form['status'], quantidade=request.form['quantidade'], descricao=request.form['descricao']) db.session.add(book) flash('Livro inserido com sucesso!!') db.session.commit() return redirect(url_for('cadastro')) return render_template('cadastro.html', form=form)
def create_book(): form = BookForm() if form.validate_on_submit(): book = Book(title = form.title.data, timestamp = datetime.utcnow(), author = g.user) db.session.add(book) db.session.commit() return redirect(url_for('search')) else: return render_template('create_book.html', form = form)
def dispatch_request(self): form = BookForm() form.authors.query = Author.query.all() if request.method == "POST": if form.validate_on_submit(): obj = Book() form.populate_obj(obj) obj.save() return redirect("/books/") return render_template("book_add.html", form=form)
def books_list_api_v1(): form = BookForm() error = "" if request.method == "POST": if form.validate_on_submit(): books.create(form.data) return redirect(url_for("books_list_api_v1")) return render_template("books.html", form=form, books=books.all(), error=error)
def show_library(): error="" book_form = BookForm() if request.method == "POST": if book_form.validate_on_submit(): services.add_book(book_form) return redirect(url_for('show_library')) books_list = services.load() return render_template("homepage.html", form = book_form, books = books_list, error=error)
def create_book(): form = BookForm() if request.method == 'POST' and form.validate_on_submit(): db.execute( "INSERT INTO books (title, author) VALUES (:title, :author);", { "title": form.title.data, 'author': form.author.data }) db.commit() # data = Book(form.title.data, form.author.data, form.isbn.data, form.year.data, ) return render_template('book.html', form=form)
def book_update(id): """ update books """ book = Book.query.get(id) book_form = BookForm(obj=book) if request.method == 'POST': if book_form.validate_on_submit(): book_form.populate_obj(book) db.session.add(book) db.session.commit() return redirect('/') return render_template('book_edit.html', book_form=book_form)
def library_list(): form = BookForm() error = "" if request.method == "POST": if form.validate_on_submit(): library.create(form.data) library.save_all() return redirect(url_for("library_list")) return render_template("library.html", form=form, library=library.all(), error=error)
def book_add(): """ returns book add function """ book = Book() book_form = BookForm(obj=book) if request.method == 'POST': if book_form.validate_on_submit(): book_form.populate_obj(book) db.session.add(book) db.session.commit() return redirect('/') return render_template('book_edit.html', book_form=book_form)
def edit_book(id): form = BookForm() book = data_services.get_book_by_id(id) if request.method == 'GET': authors = "" for author in book.author: authors = author + ", " form = BookForm(obj=book) form.author.data = authors subscribers = data_services.get_all_subscriber() form.subscriber.choices = [(subscriber.id, subscriber.email) for subscriber in subscribers] form.subscriber.process_data(subscribers[0].id) publishers = data_services.get_all_publishers() form.publisher.choices = [(publisher.id, publisher.name) for publisher in publishers] form.publisher.process_data(book.publisher.id) return render_template('edit_book.html', form=form, status='edit') elif request.method == 'POST': if form.update.data: if form.validate_on_submit(): authors = [] for a in form.author.data.split(","): if a != "" and a != " ": authors.append(a) publisher = data_services.get_publisher(form.publisher.data) data_services.update_book(bk=book, title=form.title.data, author=form.author.data, pages=form.pages.data, publish_date=form.publish_date.data, publisher=publisher) flash('Book created successfully', 'success') else: for k, v in form.errors.items(): flash(v[0], 'danger') return render_template('edit_book.html', form=form, status='edit') elif form.delete.data: data_services.delete_book(book) flash('Book deleted successfully', 'success') elif form.borrow.data: subscriber = data_services.get_subscriber_by_id( form.subscriber.data) data_services.book_add_subscriber(bk=book, subscriber=subscriber, start=form.start.data, end=form.end.data) flash('Book borrow created successfully', 'success') return redirect('/book/list')
def book_add(): form = LoginForm() book_form = BookForm(request.form) book_form.authors.choices = [(p.id, p.name) for p in db_session.query(Author).order_by('id')] if book_form.validate_on_submit(): book = Book() book.title = book_form.title.data book.authors = [db_session.query(Author).get(o) for o in book_form.authors.data] db_session.add(book) db_session.commit() flash('Successfully added.', 'success') return redirect(url_for('index')) return render_template("add_book.html", bform=book_form, form=form, user=current_user, is_authenticated=True)
def book_edit(id): form = LoginForm() book = db_session.query(Book).get(id) book_form = BookForm(request.form, obj=book) book_form.authors.choices = [(p.id, p.name) for p in db_session.query(Author).order_by('id')] if book_form.validate_on_submit(): book = db_session.query(Book).get(id) book.title = book_form.title.data book.authors = [db_session.query(Author).get(o) for o in book_form.authors.data] db_session.commit() flash('Saved.', 'info') return redirect(url_for('index')) book_form.authors.data = [p.id for p in book.authors] return render_template("book.html", bform=book_form, form=form, book=book, user=current_user, is_authenticated=True)
def edita(id): book_list = Book.query.filter_by(id=id).first() form = BookForm() form.titulo.data = book_list.titulo form.autor.data = book_list.autor form.editora.data = book_list.editora form.categoria.data = book_list.categoria form.tipo.data = book_list.tipo form.status.data = book_list.status form.quantidade.data = book_list.quantidade form.descricao.data = book_list.descricao if form.validate_on_submit(): #book = Book(titulo=request.form['titulo'], autor=request.form['autor'], editora=request.form['editora'], categoria=request.form['categoria'], tipo=request.form['tipo'], status=request.form['status'], quantidade=request.form['quantidade'], descricao=request.form['descricao'], id=id) db.session.execute("UPDATE Book SET titulo = '"+request.form['titulo']+"', autor = '"+request.form['autor']+"', editora = '"+request.form['editora']+"', categoria = '"+request.form['categoria']+"', tipo = '"+request.form['tipo']+"', status = '"+request.form['status']+"', quantidade = '"+request.form['quantidade']+"', descricao = '"+request.form['descricao']+"' where id = '"+id+"'") flash('Livro editado com sucesso!!') db.session.commit() return redirect(url_for('lista')) return render_template('cadastro.html', form=form, book_list=book_list)
def add_item(): form = BookForm() if form.validate_on_submit(): file = form.image.data if file and correct_file_type(file.filename): filename = secure_filename(file.filename) path = os.path.join('app/static/images', filename) file.save(path) product = Product(title=form.title.data, description=form.description.data, price=form.price.data, code=form.module_code.data, category=form.category.data, status='available', image_link=path, user_id=current_user.id, ad_fee_paid='No', location=form.location.data) db.session.add(product) db.session.commit() flash('Item Successfully Added!') return redirect(url_for('index')) else: flash('Incorrect File Type. Only .png, .jpg and .jpeg allowed.') return render_template('profile.html', title='Profile', form=form, page='add_item') return render_template('profile.html', title='Profile', form=form, page='add_item', items_in_cart=get_num_items())
def edit_book(isbn): ''' Edit book :param isbn: ISBN ''' my_book = Book.query.filter_by(isbn=isbn).first() form = BookForm(obj=my_book) if form.validate_on_submit(): try: form.populate_obj(my_book) db.session.add(my_book) db.session.commit() flash('Saved successfully', 'success') except: db.session.rollback() flash('Error update book.', 'danger') return render_template( 'web/edit_book.html', form=form)
def new_book(): ''' Create new book ''' form = BookForm() if form.validate_on_submit(): # TODO isbn = request.form['isbn'] name = request.form['name'] book_db = db.session.query(Book).filter_by(isbn=isbn) user_db = db.session.query(User).filter_by( name=name).first() if book_db is None: if user_db is not None: pw_db = user_db.password pw_in = request.form['password'] print(name) print(pw_db) print(pw_in) if pw_db == pw_db: # db.session.add(user) user = User.query.filter_by(name=name).first() print(user.name) # my_book = Book() form.populate_obj(my_book) try: db.session.add(my_book) user.books.append(my_book) db.session.commit() # User info flash('Book created correctly', 'success') # return redirect(url_for('books')) return redirect(url_for('new_book')) except: db.session.rollback() flash('Error generating book.', 'danger') # flash(traceback.format_exc(), 'danger') return render_template('web/new_book.html', form=form)
def new_book(): form = BookForm() if request.method == 'GET': publishers = data_services.get_all_publishers() form.publisher.choices = [(publisher.id, publisher.name) for publisher in publishers] return render_template('edit_book.html', form=form, status='new') elif request.method == 'POST': if form.validate_on_submit(): publisher = data_services.get_publisher(form.publisher.data) data_services.create_book(title=form.title.data, author=form.author.data, pages=form.pages.data, publish_date=form.publish_date.data, publisher=publisher) flash('Book created successfully', 'success') else: for k, v in form.errors.items(): flash(v[0], 'danger') return render_template('edit_book.html', form=form, status='new') return redirect('/book/list')
def modify(b_id): # if is_not_admin(): # return redirect(url_for('info',b_id=b_id)) b = Book.query.get(b_id) if not b: return "ERROR!" if not b.img: b.img = 'default.jpg' form = BookForm() if form.validate_on_submit(): b.img = form.imgname.data b.name = form.name.data b.category = form.category.data b.press = form.press.data b.author = form.author.data b.note = form.note.data db.session.add(b) db.session.commit() flash("修改成功") return redirect(url_for('info', b_id=b.id)) return render_template('book_modify.html', g=g, book=b, form=form)
def book_add(): # form = LoginForm() book_form = BookForm(request.form) book_form.authors.choices = [ (p.id, p.name) for p in db_session.query(Author).order_by('id') ] if book_form.validate_on_submit(): book = Book() book.title = book_form.title.data book.authors = [ db_session.query(Author).get(o) for o in book_form.authors.data ] db_session.add(book) db_session.commit() flash('Successfully added.', 'success') return redirect(url_for('index')) return render_template("new_book.html", bform=book_form, user=current_user, is_authenticated=True)
def bookform(): form = BookForm() if form.validate_on_submit(): # flash('Book Saved (author - {}, title{}'.format( # form.author.data, form.title.data)) conn = sqlite3.connect('bookdata') cur = conn.cursor() all_books = cur.execute('SELECT * FROM BooksTable;').fetchall() book_dict = { 'Author': form.author.data, 'Title': form.title.data, 'Rating': int(form.rating.data), 'ID': len(all_books) } #result = jsonify(book_dict) cur.execute("INSERT INTO BooksTable VALUES (?,?,?,?)", [ book_dict["ID"], book_dict["Title"], book_dict["Author"], book_dict["Rating"] ]) conn.commit() conn.close() return redirect('/index') return render_template('bookform.html', form=form)
def book_info(id): form = BookForm() book_can = BookCan.query.get(id) if request.method == 'GET': return render_template('add_book.html', form=form, id=id) if request.method == 'POST': if form.validate_on_submit(): book = Book(name=form.name.data, link=form.link.data, intro=form.intro.data) book_can.book.append(book) db.session.add(book) db.session.commit() btn = request.form.get('btn') if btn == u'继续添加': form.name.data = None form.link.data = None form.intro.data = None return render_template('add_book.html', form=form, id=id) else: return redirect(url_for('can_info', id=id, page=1)) else: flash('提交失败,请重新填写') return render_template('add_book.html', form=form)
def book_edit(id): # form = LoginForm() book = db_session.query(Book).get(id) book_form = BookForm(request.form, obj=book) book_form.authors.choices = [ (p.id, p.name) for p in db_session.query(Author).order_by('id') ] if book_form.validate_on_submit(): book = db_session.query(Book).get(id) book.title = book_form.title.data book.authors = [ db_session.query(Author).get(o) for o in book_form.authors.data ] db_session.commit() flash('Saved.', 'info') return redirect(url_for('index')) book_form.authors.data = [p.id for p in book.authors] return render_template("book.html", bform=book_form, book=book, user=current_user, is_authenticated=True)
def edit_book(book_id): """ Function to load form for a book review and render to html. Checks first whether a user is logged in, before performing function. """ # Check to see if user logged in and render html if g.user: the_book = mongo.db.books.find_one({"_id": ObjectId(book_id)}) super_user = mongo.db.users.find_one({"username": "******"}) # Check if user same as contributor or super user if g.user == the_book["user_id"] or g.user == str(super_user["_id"]): form = BookForm() all_categories = mongo.db.categories.find() # Validation of form and insert in collection if form.validate_on_submit(): flash( f"Book details successfully updated: {form.title.data.title()}!", "success") books = mongo.db.books books.update({"_id": ObjectId(book_id)}, { "title": form.title.data.lower(), "author_fname": form.author_fname.data.lower(), "author_lname": form.author_lname.data.lower(), "category_id": form.category_id.data, "user_id": g.user, "up_votes": the_book["up_votes"], "down_votes": the_book["down_votes"], "date_added": date.today().strftime("%Y/%m/%d"), "cover_url": form.cover_url.data, "csrf_token": form.csrf_token.data }) return redirect( url_for( "get_book", book_id=book_id, _scheme="https", _external=True)) # Check to see type of user and return of form for correction else: if g.user == str(super_user["_id"]): return render_template( "editbook.html", book=the_book, categories=all_categories, form=form, super_user=g.user) else: return render_template( "editbook.html", book=the_book, categories=all_categories, form=form, regular_user=g.user) else: flash( f"You cannot edit this book's details, as it was uploaded by someone else...", "danger") return redirect( url_for( "get_book", book_id=book_id, _scheme="https", _external=True)) else: flash(f"You need to log in first...", "warning") return redirect( url_for( "log_user_in", _scheme="https", _external=True))
def submit_book_form(): if g.user: form = BookForm() planets = [(p.name, p.name) for p in Planet.query.all()] form.planet.choices = planets # We have to add all the possible choices for depart_flight, return_flight, and tour here, otherwise WTForms won't # recognize the choices that we've populated those fields with on the frontend with JS and will give us errors flights = [(f.flight_num, f"Flight: {f.flight_num}") for f in Flight.query.all()] form.depart_flight.choices = flights form.depart_flight.choices.append((0, "None")) form.return_flight.choices = flights form.return_flight.choices.append((0, "None")) form.tour.choices = [(t.id, t.name) for t in Tour.query.all()] form.tour.choices.append((0, "None")) if form.validate_on_submit(): tour_id = form.tour.data tour_date = form.tour_date.data no_tour = form.no_tour.data depart_date = form.depart_date.data depart_id = form.depart_flight.data no_depart = form.no_depart.data return_date = form.return_date.data return_id = form.return_flight.data no_return = form.no_return.data planet_name = form.planet.data if g.itin and session[ 'itin'] and g.user.id == g.itin.user_id and g.itin.id == session[ 'itin']: itin = Itinerary.query.get(g.itin.id) planet = Planet.query.get(planet_name) itin.planets.append(planet) db.session.commit() if no_tour and no_depart and no_return and len( itin.tours) == 0: flash( "You have to select either a flight and flight date or a tour and tour date to submit this form.", "danger") return redirect('/book') if no_tour and no_depart and no_return and len(itin.tours) > 0: # There could be a situation where a user adds only tours and no flights, but on the last tour, they choose # to select 'no tour', because they made a mistake. To account for that, we calculate which previously added # tour had the earliest start datetime, which one had the latest end datetime, set the itinerary start/end # date/times to those dates and times, check to see if the itinerary conflicts with any others, and redirect # them to the book success page. tour_start_datetimes = [ get_datetime(tour_date.start_date, tour_date.tour.start_time) for tour_date in itin.tour_dates ] tour_end_datetimes = [ get_datetime(tour_date.end_date, tour_date.tour.end_time) for tour_date in itin.tour_dates ] earliest_datetime = min(tour_start_datetimes) latest_datetime = max(tour_end_datetimes) earliest_datetime_arr = datetime_to_strings( earliest_datetime) latest_datetime_arr = datetime_to_strings(latest_datetime) itin.start_time = earliest_datetime_arr[0] itin.start_date = earliest_datetime_arr[1] itin.end_time = latest_datetime_arr[0] itin.end_date = latest_datetime_arr[1] db.session.commit() # Compare user's past itineraries to this current one. If any dates conflict with each other, we flash an # error resp = compare_curr_itin_to_itins( User.query.get(g.user.id), itin) if resp != "You're all good!": flash(resp, 'danger') return redirect('/book') else: remove_itin() flash( "Successfully booked your trip! Thank you for choosing Star Tours! Enjoy your trip!", 'success') return render_template('book_success.html', itin=itin) if not no_tour: # If tour_id isn't 0 and tour_date isn't blank, then we get the tour, add the dates to it and commit tour = Tour.query.get(tour_id) tour_dates = TourDate(start_date=tour_date, end_date=set_arrive_end_date( tour_date, tour.start_time, tour.duration), tour_id=tour.id, itinerary_id=itin.id) db.session.add(tour_dates) db.session.commit() if planet_name != tour.planet_name: flash( "Your selected planet doesn't match the tour's planet. Please select the correct planet for the tour.", "danger") return redirect('/book') # If there are already flight dates added to the itinerary and database from the adding tours route, plug # those into the function below, if not, don't include them and let the default arguments do their thing # Make sure to sort the flight dates first, so we know for sure which one's the depart date (the closest date to # today) and which one's the return date (the furthest date from today) if len(itin.flight_dates) > 1: itin.flight_dates.sort(key=get_flight_depart_datetime) if len(itin.flight_dates) == 1 and itin.flight_dates[ 0].flight.depart_or_return == "depart": # Checks to see if selected flights' dates and times conflict with one another or with the tour's date and time result = compare_curr_flights_to_curr_tour( no_depart, no_return, depart_id, return_id, depart_date, return_date, tour, tour_dates, itin, d_flight_dates=itin.flight_dates[0]) elif len(itin.flight_dates) == 1 and itin.flight_dates[ 0].flight.depart_or_return == "return": result = compare_curr_flights_to_curr_tour( no_depart, no_return, depart_id, return_id, depart_date, return_date, tour, tour_dates, itin, r_flight_dates=itin.flight_dates[0]) elif len(itin.flight_dates) == 2: result = compare_curr_flights_to_curr_tour( no_depart, no_return, depart_id, return_id, depart_date, return_date, tour, tour_dates, itin, itin.flight_dates[0], itin.flight_dates[1]) else: result = compare_curr_flights_to_curr_tour( no_depart, no_return, depart_id, return_id, depart_date, return_date, tour, tour_dates, itin) # Checks to see if the current tour's start and end datetime conflict with any other tours' start and end datetimes result2 = compare_curr_tour_to_itin_tours( itin, tour, tour_dates) if type(result) == str: flash(result, "danger") return redirect('/book') if result2 != "You're all good!": flash(result2, "danger") return redirect('/book') itin.tours.append(tour) itin.total += tour.price # Order the tour dates from closest to today to furthest from today, so we can order them in our Trips section # in the user's account page. This will help us order them from earliest to latest in the trip. itin.tour_dates.sort(key=get_tour_start_datetime) db.session.commit() # In cases where we have no flights and only tours or one flight and tours, we need to determine which tour # has the earliest start_date, so it can be the itinerary's start_date, and which tour has the latest # end_date, so it can be the itinerary's end_date tour_start_datetimes = [ get_datetime(tour_date.start_date, tour_date.tour.start_time) for tour_date in itin.tour_dates ] tour_end_datetimes = [ get_datetime(tour_date.end_date, tour_date.tour.end_time) for tour_date in itin.tour_dates ] earliest_datetime = min(tour_start_datetimes) latest_datetime = max(tour_end_datetimes) earliest_datetime_arr = datetime_to_strings( earliest_datetime) latest_datetime_arr = datetime_to_strings(latest_datetime) if len(result) == 0: itin.start_time = earliest_datetime_arr[0] itin.start_date = earliest_datetime_arr[1] itin.end_time = latest_datetime_arr[0] itin.end_date = latest_datetime_arr[1] db.session.commit() if len(result) == 2: itin.flights.append(result[0]) db.session.commit() flight_dates = result[1] # If there's only 1 flight, it matters if it's the depart or the return flight. If it's the depart flight, # then the start time and date for the itinerary will be that flight's start time and date. If it's the # return flight, then the itinerary's end time and date will be that flight's end time and date. if result[0].depart_or_return == "depart": itin.start_time = result[0].depart_time itin.start_date = flight_dates.depart_date itin.end_time = latest_datetime_arr[0] itin.end_date = latest_datetime_arr[1] itin.total += result[0].price db.session.commit() if result[0].depart_or_return == "return": itin.start_time = earliest_datetime_arr[0] itin.start_date = earliest_datetime_arr[1] itin.end_time = result[0].arrive_time itin.end_date = flight_dates.arrive_date itin.total += result[0].price db.session.commit() if len(result) == 4: itin.flights.append(result[0]) d_flight_dates = result[1] itin.flights.append(result[2]) r_flight_dates = result[3] itin.start_time = result[0].depart_time itin.start_date = d_flight_dates.depart_date itin.end_time = result[2].arrive_time itin.end_date = r_flight_dates.arrive_date itin.total += result[0].price + result[2].price # Order the flight dates by closest to today to furthest away from today, so we will always know which # one's the depart flight (the closest) and which one is the return flight (the furthest) itin.flight_dates.sort(key=get_flight_depart_datetime) db.session.commit() # Compare user's past itineraries to this current one. If any dates conflict with each other, we flash an # error resp = compare_curr_itin_to_itins( User.query.get(g.user.id), itin) if resp != "You're all good!": flash(resp, 'danger') return redirect('/book') else: remove_itin() flash( "Successfully booked your trip! Thank you for choosing Star Tours! Enjoy your trip!", 'success') return render_template('book_success.html', itin=itin) else: # If there are no tours # If there are already flight dates added to the itinerary and database from the adding tours route, plug # those into the function below, if not, don't include them and let the default arguments do their thing # Make sure to sort the flight dates first, so we know for sure which one's the depart date (the closest date to # today) and which one's the return date (the furthest date from today) if len(itin.flight_dates) > 1: itin.flight_dates.sort(key=get_flight_depart_datetime) if len(itin.flight_dates) == 1 and itin.flight_dates[ 0].flight.depart_or_return == "depart": # Checks to see if selected flights' dates and times conflict with one another result = compare_curr_flights( no_depart, no_return, depart_id, depart_date, return_id, return_date, itin, d_flight_dates=itin.flight_dates[0]) elif len(itin.flight_dates) == 1 and itin.flight_dates[ 0].flight.depart_or_return == "return": result = compare_curr_flights( no_depart, no_return, depart_id, depart_date, return_id, return_date, itin, r_flight_dates=itin.flight_dates[0]) elif len(itin.flight_dates) == 2: result = compare_curr_flights(no_depart, no_return, depart_id, depart_date, return_id, return_date, itin, itin.flight_dates[0], itin.flight_dates[1]) else: result = compare_curr_flights(no_depart, no_return, depart_id, depart_date, return_id, return_date, itin) if type(result) == str: flash(result, 'danger') return redirect('/book') if len(result) == 2: if planet_name != result[ 0].depart_planet and planet_name != result[ 0].arrive_planet: flash( "Your selected planet doesn't match your flight's planet. Please select the correct planet for flight.", "danger") return redirect('/book') itin.flights.append(result[0]) flight_dates = result[1] itin.start_time = result[0].depart_time itin.start_date = flight_dates.depart_date itin.end_time = result[0].arrive_time itin.end_date = flight_dates.arrive_date itin.total += result[0].price db.session.commit() if len(result) == 4: if planet_name != result[ 0].depart_planet and planet_name != result[ 0].arrive_planet and planet_name != result[ 2].depart_planet and planet_name != result[ 2].arrive_planet: flash( "Your selected planet doesn't match your depart flight's or arrive flight's planets. Please select the correct planet for the flights.", "danger") return redirect('/book') itin.flights.append(result[0]) d_flight_dates = result[1] itin.flights.append(result[2]) r_flight_dates = result[3] itin.start_time = result[0].depart_time itin.start_date = d_flight_dates.depart_date itin.end_time = result[2].arrive_time itin.end_date = r_flight_dates.arrive_date itin.total += result[0].price + result[2].price # Order the flight dates by closest to today to furthest away from today, so we will always know which # one's the depart flight (the closest) and which one is the return flight (the furthest) itin.flight_dates.sort(key=get_flight_depart_datetime) db.session.commit() resp = compare_curr_itin_to_itins( User.query.get(g.user.id), itin) if resp != "You're all good!": flash(resp, 'danger') return redirect('/book') else: remove_itin() flash( "Successfully booked your trip! Thank you for choosing Star Tours! Enjoy your trip!", 'success') return render_template('book_success.html', itin=itin) else: flash( "You have to log in first, then go to the 'Book A Trip' page and click on 'Submit' to access this route.", "danger") return redirect('/book') else: flash( "Something went wrong when submitting the form. Please try again.", "danger") return redirect('/book') else: flash("You have to log in first to access this route.", "danger") return redirect('/')