def addCategory(): # add a cateogry to the database if request.method == 'GET': # check is their is someone logged in if 'username' not in login_session: return redirect(url_for('showCatalog')) return render_template('addCategory.html') else: # attain cateogry name from html file and create row in database category = request.form['title'] # if category name is blank refresh page if category is None: return render_template('addCategory.html') else: new_category = Category(name=category) new_category.user_id = login_session['email'] session.add(new_category) session.commit() return redirect(url_for('showCatalog'))
def edit_item(category_name, item_name): """Edit an item from the database and return webpage of resulting item. Args: category_name: Name of the category of the item the user is editing item_name: Name of item the user is editing Returns: HTML template for the new item's webpage using Flask framework """ # Find categories categories = session.query(Category).all() # Get category id for edited item oldCategory = session.query(Category).filter_by(name=category_name).first() old_cat_id = oldCategory.id item = (session.query(Item) .filter_by(category_id=old_cat_id, name=item_name) .one()) # Edit data if request.method == 'POST': # Check if user selected "New Category" in dropdown if request.form['categoryName'] == 'newCategory': # Create new category in database from user input categoryName = request.form['newCat'] newCategory = Category(name=categoryName) session.add(newCategory) session.commit() else: categoryName = request.form['categoryName'] # Get category id for new item cat_id = (session.query(Category) .filter_by(name=categoryName).first().id) # Delete old category if this was the last item in the old category items_in_category = (session.query(Item) .filter_by(category_id=old_cat_id)) num_of_items = items_in_category.count() # Delete old category if new category is chosen and no items left if num_of_items == 1 and old_cat_id != cat_id: session.delete(oldCategory) # Save edits to item item.name = request.form['itemName'] item.description = request.form['itemDesc'] item.image = request.form['itemURL'] item.category_id = cat_id # Save edits officially to database session.add(item) session.commit() # Send a success message flash("Your item has been edited!") # Go back to main page return redirect(url_for('item', item_name=request.form['itemName'], category_name=categoryName)) else: return render_template('item-edit.html', categories=categories, item=item, category=category_name)
def createCategory(): """ All users can create a new category. """ if not userLoggedIn(): flash('Must be logged in to create new category') return redirect(url_for('showCatalog')) if request.method == 'POST': name = request.form['name'].lower() if session.query(Category).filter(Category.name == name).first(): flash('Category exist with that name') return redirect(url_for('createCategory')) category = Category(name=name) session.add(category) session.commit() flash(name.title() + ' successfully created') return redirect(url_for('showCatalog')) return render_template('updatecategory.html', newCategory=True)
def new_item(): """Create a new item in the database via a form and return a webpage.""" # Find categories categories = session.query(Category).all() # If user submits form to create new item if request.method == 'POST': # Check that user doesn't enter an empty string if request.form['newItemName'] == '': # Give an error message flash("The item wasn't added! You need to type a name!") # Return to new item page return render_template('item-new.html', categories=categories) # Check if user selected "New Category" in dropdown if request.form['categoryName'] == 'newCategory': # Create new category in database from user input categoryName = request.form['newCat'] newCategory = Category(name=categoryName) session.add(newCategory) session.commit() else: categoryName = request.form['categoryName'] # Get category id for new item cat_id = (session.query(Category) .filter_by(name=categoryName).first().id) newItem = Item(name=request.form['newItemName'], description=request.form['newItemDesc'], date_added=date.today(), image=request.form['newItemURL'], category_id=cat_id) session.add(newItem) session.commit() # Go back to main page return redirect(url_for('item', item_name=request.form['newItemName'], category_name=categoryName)) # Present new item form else: return render_template('item-new.html', categories=categories)
def newCategory(): if (not checkLoggedIn()): flash("Must login to access this functionality") return redirect(url_for('login')) if (not checkTokenValid()): flash("Login session expired") return redirect(url_for('logout')) if (request.method == 'GET'): return render_template('newcategory.html') if (request.method == 'POST'): newCatName = request.form['name'] category = session.query(Category).filter_by(name=newCatName).first() if ((newCatName is None) or (newCatName == '')): flash("New category must have a valid name") return redirect(url_for('newCategory')) elif (category is not None): flash("New category must have a unique name") return redirect(url_for('newCategory')) else: newCat = Category(name=newCatName, user_id=login_session['id']) session.add(newCat) session.commit() flash(newCatName + " category has been created") return redirect(url_for('getCatalog'))
# revert all of them back to the last commit by calling # session.rollback() session = DBSession() sports = { "soccer", "basketball", "tennis", "polo", "track", "swimming", "racing", "football", "baseball", "golf", "skydiving", "poker", "video games", "chess", "archery", "roulette", "water polo" } user = User(name="admin", email="*****@*****.**", admin=True) session.add(user) session.commit() for sport in sports: category = Category(name=sport) session.add(category) session.commit() for i in range(random.randint(1, 20)): name = sport + ' item ' + str(i + 1) price = random.randint(1, 100) item = Item( name=name, description= "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi cursus luctus dapibus. Aenean ut quam eu sapien malesuada porta ut non quam. Etiam cursus maximus eros eu pharetra. Fusce finibus turpis ipsum, quis vehicula libero molestie sed. Aenean cursus viverra nulla, vel venenatis dui vulputate in. Morbi et aliquet erat. Duis eget lacus quis lorem iaculis ornare ut quis dui. Vivamus euismod, sapien nec varius sodales, justo lacus mattis erat, non pellentesque arcu nulla ut neque. Aenean sagittis consectetur sem eu tristique. Donec consectetur turpis tincidunt risus euismod tincidunt. Sed lacus turpis, iaculis nec nulla eget, varius pretium magna. Aliquam vitae magna vitae elit eleifend suscipit eget eu arcu. Nunc dolor ex, bibendum id purus quis, tempus bibendum augue. Praesent consequat sapien risus, quis fermentum velit tincidunt imperdiet. Cras lacinia tempus libero, sed mollis ante tincidunt non.", price=price + .99, category=category, user=user) session.add(item) session.commit()
from sqlalchemy.orm import sessionmaker from catalog import Base, Category, Item from random import randint import datetime import random engine = create_engine('sqlite:///catalog.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() #Add Categories soccer = Category(name = "Soccer") session.add(soccer) snowboarding = Category(name = "Snowboarding") session.add(snowboarding) hockey = Category(name = "Hockey") session.add(hockey) baseball = Category(name = "Baseball") session.add(baseball) session.commit() #Add Items to catalog items = ['Shinguards','Jersey','Soccer Cleats','Goggles','Snowboard','Stick',\