def newItem(collection_id): #if 'username' not in login_session: # return redirect('/login') if request.method == 'POST': now = datetime.datetime.now() file = request.files['file'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) newPath = os.path.join(app.config['UPLOAD_FOLDER'], "%s.%s" % (file.filename.rsplit('.',1)[0]+now.strftime("%Y-%m-%d-%H-%M-%S-%f"), file.filename.rsplit('.', 1)[1])) file.save(newPath) file_create, orientation = getExif(newPath) item_url = newPath flash("File Uploaded!") create_datetime = request.form['create_date'] if create_datetime == '': if file_create: create_datetime = file_create else: create_datetime = now newItem = Items(title = request.form['name'], description = request.form['description'], type = request.form['type'], note = request.form['notes'], create_date = create_datetime, shelf_location = request.form['shelf'], date_added = datetime.datetime.now()) #user_id=login_session['id']) newItem.archive_url = item_url subject_ids = request.form.getlist('subject') for subj_id in subject_ids: subj = session.query(Subject).filter_by(id = subj_id).one() newItem.subject.append(subj) coll = session.query(Collections).filter_by(id = collection_id).one() newItem.collections.append(coll) session.add(newItem) #author_name = request.form['author'] #isAuthor = session.query(Authors).filter_by(name = author_name).one() #if !isAuthor: # addNewAuthor(author_name) #people_name = request.form['depicted_name'] session.commit() flash("New Item Created!") return redirect(url_for('showCollection', collection_id=collection_id)) else: collectionList = session.query(Collections).all() subjectList = session.query(Subject).all() authorList = session.query(Authors).all() return render_template('additem.html', collection_id=collection_id, collectionList=collectionList, authorList=authorList, subjectList=subjectList)
def post(self): # One can only delete themselves, if they are logged in and post with a # vaild state if not self.request.form.get("csrf") == session.get('state'): return self.flash_out( "The state does not match the session, please try again", 401, url_for("myaccount_view")) # Get the user id from session uid = session.get('uid') if not uid: self.auth.logout() return self.flash_out( "No valid login detected", 401, url_for("login_view")) # Revoke the access token for the provider provider = session.get('provider') if provider == "google": self.google.disconnect() elif provider == 'facebook': self.facebook.disconnect() # Delete all the items that belong to the user Items.delete_by_user(dbs, uid) # Delete the user's image Images.delete_by_id(dbs, self.user.picture) # Delete the user User.delete_user(dbs, uid) self.auth.logout() return self.flash_out("The account has been deleted", 200, "/")
def post(self): # check for csrf if not self.request.form.get("state") == session['state']: return self.flash_out( "The state did not match your session, please try again", 401, "/") # Define the available variables to populate the object my_vars = ['name', 'category', 'description', 'link'] # Define which ones should be Title case titles = ['name', 'category'] new_item = {} for mp in my_vars: if mp in titles: new_item[mp] = self.request.form.get(mp).title() else: new_item[mp] = self.request.form.get(mp) new_item['user_id'] = self.user_info['uid'] # this test excludes the optional image file test new_item_valid, new_item_test_error = utils.test_new_item(new_item) if not new_item_valid: # Here we should really re-populate the fields with the content submitted # for now one has to resubmit, there should also be a test on the # front end return self.flash_out( new_item_test_error, 401, url_for("additem_view")) # Check to see if this potential item is already in the db if Items.item_exists(dbs, new_item['name'], new_item['category']): return self.flash_out( "This Item already exists in this category", 401, url_for("additem_view")) # Check to see if there is a picture submission and upload it upload_file = self.request.files["picture"] if upload_file: image_name = utils.remove_special_characters( new_item["name"] + new_item["category"]) + "_img" img = self.upload_image_file(upload_file, image_name) # if the upload and storage succeeds add the img id to the item. if img: new_item['picture'] = img.id # add the new item to the database Items.addItem(dbs, new_item) return self.flash_out("New Item added", 200, "/")
def get(self, category, item_id): my_item = Items.get_by_id(dbs, item_id) if not my_item or my_item.user_id != self.user_info['uid']: return self.flash_out( "The item you are looking for does not exist or you are not allowed to delete it", 401, "/") return self.render_template( "item_delete.html", my_item=my_item, my_category=category)
def add_item(cat_name): """Render page for adding characters for GET request, or alter database for POST request""" select_tab = session.query(Category).filter_by(name = cat_name).one() # protect page in case somebody not logged in tries to access via the URL if 'username' not in login_session: return redirect('/') # if the user is logged in if request.method == 'POST': name = request.form['name'] category = request.form['category'] description = request.form['description'] image = request.form['image'] # check that all fields are filled if not name or not description or not image: flash('Please fill in all the fields!') return render_template('add_item.html', select_tab = select_tab.name, categories = categories) else: try: # add new character to the database newItem = Items(name = name, cat_name = category, description = description, image = image, user_id = login_session['user_id']) session.add(newItem) session.commit() return redirect('/') except exc.IntegrityError: session.rollback() flash("Invalid Entry") return render_template('add_item.html', select_tab = select_tab.name, categories = categories) else: return render_template('add_item.html', select_tab = select_tab.name, categories = categories)
def newItem(category_id, subcategory_id): if request.method == 'POST': filename = '' file = request.files['image'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) newItem = Items(title=request.form['title'], description=request.form['description'], category_id=request.form['category_id'], subcategory_id=request.form['subcategory_id'], image=filename) session.add(newItem) flash('New item %s Successfully Created' % newItem.title) session.commit() return redirect( url_for('getItemsBySub', category_id=newItem.category_id, subcategory_id=newItem.subcategory_id)) else: category = session.query(Categories).filter_by(id=category_id).one() subcategory = session.query(Subcategories).\ filter_by(id=subcategory_id).one() return render_template('new_item.html', access_token=login_session.get('access_token'), category=category, subcategory=subcategory)
def newItem(): # If the method is POST, try to add the new record if request.method == "POST": record = Items( name=request.form["name"], catagory_id=request.form["catagory_id"], description=request.form["description"], user_id=session['user_id']) # Try to add the new items try: database_session.add(record) database_session.commit() except SQLAlchemyError: flash("Cannot edit the item! Please contact developer!") return redirect("/") # Flash the system message flash("Item \"%s\" has already created!" % (record.name,)) return redirect("/") else: # Render the existing catagories for selection catagory = database_session.query(Catagory).all() item = None return render_template( "itemForm.html", catagory=catagory, item=item, editFlag=False)
def addItem(category_name, sub_category_name): if 'email' not in login_session: return redirect('/login') if request.method == 'POST': corner = session.query(Category).filter_by(name=category_name).one() sub_category = session.query(SubCategory).filter_by( category_id=corner.id, name=sub_category_name).one() additem = Items( name=request.form['item_name'], picture=request.form['image'], price=request.form['price'], seller_name=request.form['seller_name'], seller_phoneno=request.form['seller_phoneno'], description=request.form['description'], user_id=login_session['user_id'], category_id=corner.id, subCategory_id=sub_category.id) session.add(additem) flash("Item successfully added") session.commit() return redirect(url_for('showItems', category_name=category_name, sub_category_name=sub_category_name)) else: return render_template('addnewitem.html', corner=category_name, sub_category=sub_category_name, user=login_session['username'])
def add_item(): form = ItemForm(request.form) # DBSession() instance db_session = DBSession() # get categories for dropdown categories = db_session.query(Categories) #form = ItemForm(request.POST, obj=categories) form.category.choices = [(c.name, c.name) for c in categories] if request.method == 'POST' and form.validate(): # Get Form Values name = form.name.data detail = form.detail.data category = form.category.data db_session = DBSession() # Insert into DB newitem = Items(name=name, detail=detail, category=category) db_session.add(newitem) # Commit to DB db_session.commit() flash('Item created', 'success') return redirect(url_for('catalog')) return render_template('add_item.html', form=form, categories=categories)
def addCategoryItem(category_name): if 'username' not in login_session: return redirect('/login') category = session.query(Category).filter_by(name=category_name).one() categories = session.query(Category).all() user = getUserInfo(login_session['user_id']) if request.method == 'POST': newItem = Items( name=request.form['name'], description=request.form['description'], picture=request.form['picture'], category=session.query(Category).filter_by( name=request.form['category']).one(), # noqa date=datetime.datetime.now(), user_id=login_session['user_id']) session.add(newItem) session.commit() flash('Category Item Successfully Added!') return redirect( url_for('showCategoryItems', category_name=category.name)) # noqa else: return render_template('addquote.html', category=category, categories=categories, user=user)
def addItem(name, description, category_id, user_id): item = Items(name=name, description=description, category_id=category_id, user_id=user_id) session.add(item) session.commit()
def newProduct(shop_id): if 'username' not in login_session: return redirect('/login') shop = session.query(Shop).filter_by(id=shop_id).one() if login_session['user_id'] != shop.user_id: return """<script>function myFunction() {alert('You are not authorized to add a product to this list. Please create your own shop in order to add items.');}</script><body onload='myFunction()'>""" if request.method == 'POST': if 'itemPic' in request.files: file = request.files['itemPic'] filename = savingImgs(file) else: filename = "ImgPlaceHolder.png" newItem = Items(name=request.form['name'], description=request.form['description'], price=request.form['price'], itemImgName=filename, shop_id=shop_id) session.add(newItem) session.commit() flash("Product: %s Has been added!" % newItem.name) return redirect(url_for('showShop', shop_id=shop_id)) else: return render_template('newProduct.html', shop_id=shop_id)
def addItem(): if 'username' not in login_session: return redirect('/login') if request.method == 'POST': title = request.form['title'] category = request.form['category'] cat_id = session.query(Catalog.id).filter_by(category=category) newItem = Items(title=request.form['title'], description=request.form['description'], category_id=cat_id, user_id=login_session['user_id']) titleExists = session.query(exists().where(Items.title == title)).scalar() if not titleExists: session.add(newItem) session.commit() addMessage = 'New Item Added - {}'.format(newItem.title) flash(addMessage) return redirect(url_for('showCatalog')) else: flash('Item already exists. Request can not be completed') return redirect(url_for('showCatalog')) else: return render_template('addItem.html', session=login_session)
def newCategoryItem(category_id): CatOne = session.query(Categories).filter_by(id=category_id).one() # CHECK IF THE USER LOGGED IN if 'username' not in login_session: return redirect('/login') if request.method == 'POST': # CHECK FILEDS IF THEY ARE EMPTY if request.form['name'] and request.form['description'] and \ request.form['price'] and request.form['manufacture'] != '': newItem = Items(name=request.form['name'], description=request.form['description'], price=request.form['price'], manufacture=request.form['manufacture'], categories_id=category_id) session.add(newItem) session.commit() flash('New Menu %s Item Successfully created' % (newItem.name)) return redirect(url_for('categoryItems', category_id=CatOne.id)) else: flash("!!!!!! Fill please all new item fields !!!!!!") return redirect(url_for('categoryItems', category_id=CatOne.id)) else: return render_template('newItem.html', category_id=CatOne.id, categ=CatOne)
def newItem(catalog_name): if 'username' not in login_session: print(login_session) return "Please log in :)" else: results = db_session.query(Categories).all() get_category_id = db_session.query(Categories).filter_by( name=catalog_name).one() if request.method == 'POST': users = Users(name=login_session['username'], email=login_session['email']) find_category = db_session.query(Categories).filter_by( name=request.form.get('categories')).one() createItem = Items(user=users, title=request.form['title'], description=request.form['description'], category=find_category) db_session.add(createItem) db_session.commit() output = redirect(url_for('showAllCategories')) recent = Recent(item=createItem, created_date=datetime.now()) db_session.add(recent) db_session.commit() return output else: output = render_template('newitem.html', category=get_category_id, r=results) return output
def newItem(category_id): categories = session.query(Category).order_by(asc(Category.name)) category = session.query(Category).filter_by(id=category_id).one() if login_session['user_id'] != category.user_id: return "<script>function myFunction() {alert('You are not authorized" " to add items to this category. Please create your own category in" " order to add items.');}</script><body onload='myFunction()'>" if request.method == 'POST': newItem = Items(name=request.form['name'], date=datetime.datetime.now(), description=request.form['description'], color=request.form['color'], gender=request.form['gender'], age=request.form['age'], picture=request.form['picture'], category_id=category_id, user_id=category.user_id) session.add(newItem) session.commit() flash('New %s animal Successfully Created' % (newItem.name)) return redirect(url_for('showItems', category_id=category_id)) else: return render_template('newItem.html', category=category, categories=categories)
def createItem(name): """ Displays a form to create a new item Args: name: Name of the selected category """ if 'username' not in login_session: return redirect('/login') if request.method == 'POST': category = session.query(Categories).filter_by( id=request.form['category'] ).one() newItem = Items( name=request.form['title'], description=request.form['description'], categories_id=category.id, categories=category, user_id=login_session['user_id'] ) session.add(newItem) session.commit() return redirect(url_for('showAllCategories')) else: categories = session.query(Categories).all() return render_template( 'create_item.html', categories=categories, cat=name )
def addItem(): """ Add an item to a category """ if 'username' not in login_session: return redirect('/login') user_id = login_session['user_id'] if request.method == 'POST': catagory = session.query(Catagories).filter_by( name=request.form['catagory']).one() newItem = Items(title=request.form['title'], description=request.form['description'], catagory_id=catagory.id, user_id=user_id) session.add(newItem) session.commit() flash('%s Successfully created' % (newItem.title)) return redirect(url_for('showCatagories')) else: catagories = session.query(Catagories) return render_template("add_item.html", catagories=catagories, message="Add New Item")
def newItem(): if 'username' not in login_session: return redirect(url_for('categoryList')) else: if request.method == 'POST': categories = session.query(Category).all() recent_items = session.query(Items).order_by( Items.id.desc()).limit(7) cat = session.query(Category).filter_by( name=request.form.get('selected')).one() item_name = request.form['name'] item_description = request.form['description'] newItem = Items(name=item_name, description=item_description, category=cat, user_id=login_session['user_id']) session.add(newItem) session.commit() return render_template('loggedinmain.html', categoryList=categories, latest=recent_items, STATE=login_session['state']) else: categories = categories = session.query(Category).all() return render_template('newitem.html', categoryList=categories, STATE=login_session['state'])
def newItem(categories_name): if 'username' not in login_session: return redirect('/login') try: session = connect() categories = session.query(Categories).filter_by( name=categories_name).one() except: return 'category name does not exist!' if request.method == 'POST': try: findItme = session.query(Items).filter_by( category_name=categories_name, name=request.form['name']).one() return 'Name already exists!' except: if request.form['name'] == '': flash('Name can not be empty!') else: newItem = Items(name=request.form['name'], description=request.form['description'], categories_name=categories) session.add(newItem) session.commit() flash('New %s Item Successfully Created' % (newItem.name)) return redirect(url_for('showitems', categories_name=categories_name)) else: return render_template('newitem.html', categories_name=categories_name)
def add_item(cat_name): select_tab = session.query(Category).filter_by(name = cat_name).one() # protect this page in case somebody not logged in tries to access via the URL if 'username' not in login_session: return redirect('/') # if the user has logged in, we will tell the difference between a get and a post request categories = session.query(Category).order_by(Category.name) if request.method == 'POST': name = request.form['name'] category = request.form['category'] description = request.form['description'] image = request.form['image'] # check that all the fields have been filled in if not name or not description or not image: flash('Please fill in all the fields!') return render_template('add_item.html', select_tab = select_tab.name, categories = categories) else: try: # if they have filled everything in, we will add an entry to the database and redirect them newItem = Items(name = name, cat_name = category, description = description, image = image, user_id = login_session['user_id']) session.add(newItem) session.commit() return redirect('/') except exc.IntegrityError: session.rollback() flash("Invalid Entry") return render_template('add_item.html', select_tab = select_tab.name, categories= categories) else: return render_template('add_item.html', select_tab = select_tab.name, categories = categories)
def api_load(): url = 'https://www.udacity.com/public-api/v0/courses' response = urllib2.urlopen('https://www.udacity.com/public-api/v0/courses') json_response = json.loads(response.read()) categories = session.query(Category).all() for category in categories: try: category.items[:] = [] except: continue session.query(Items).delete() session.query(Category).delete() for track in json_response['tracks']: try: test = session.query(Category).filter_by(name=track['name']).one() except: category = Category(name=track['name']) session.add(category) for course in json_response['courses']: try: test = session.query(Items).filter_by(name=course['title']).one() except: item = Items(name=course['title'], description=course['summary']) session.add(item) for track in course['tracks']: category = session.query(Category).filter_by(name=track).one() if item not in category.items: category.items.append(item) session.commit() return 'Data Loaded'
def newItem(): if 'username' not in login_session: flash("You must be logged in to add an item!") return redirect(url_for('showLogin')) if request.method == 'POST': name = request.form['name'] category_id = request.form['category'] item = session.query(Items).filter_by(name=name, category_id=category_id).first() if item is None: newItem = Items(name=request.form['name'], description=request.form['description'], category_id=request.form['category'], user_name=login_session['username']) session.add(newItem) session.commit() flash("New item has been added") return redirect(url_for('home')) else: flash("An item with that same name" "already exists in that category!") categories = session.query(Categories).all() return render_template("newitem.html", categories=categories, login_session=login_session) else: categories = session.query(Categories).all() return render_template("newitem.html", categories=categories, login_session=login_session)
def new_item(): """ Create a new item. """ if 'username' not in login_session: flash('You must login for this functionality.', 'danger') return redirect('/login') # get categories categories = session.query(Categories).all() if request.method == 'POST': # get item item = session.query(Items).filter_by(name=request.form['name'])\ .filter_by(user_id=login_session['user_id']).first() # does the item exist if item: flash('The item already exists in the database!', 'info') return redirect(url_for("new_item")) else: new_item = Items(name=request.form['name'], category_id=request.form['category'], description=request.form['description'], user_id=login_session['user_id']) session.add(new_item) session.commit() flash('New item successfully created!', 'success') return redirect(url_for('new_item')) return render_template('item-new.html', categories=categories)
def add_item(self, name, description, category, user_id): """ This method add item in our database :parameter name: name of item to be created :parameter description: description of item to be created :parameter category: category of item to be created :parameter user_id: id of user/owner """ # cleaning parameter via bleach for protection against xss item_name = bleach.clean(name) item_description = bleach.clean(description) item_category = bleach.clean(category) # trying because user can enter duplicate names try: # creating item object item = Items(name=item_name, description=item_description, category=item_category, user_id=user_id) self.session.add(item) self.session.commit() return True except IntegrityError: self.session.rollback() return False
def get(self, uid): my_user = User.get_by_id(dbs, uid) if not my_user: return self.flash_out("No user found", 404, "/") user_items = Items.get_all_by_user(dbs, uid) for item in user_items: item.uname = my_user.name return self.render_template( "user_view.html", my_user=my_user, items=user_items)
def post(self, category, item_id): state = self.request.form.get("csrf") if state != session['state']: return self.flash_out( "The CSRF state is not valid, try again", 401, "/") item = Items.get_by_id(dbs, item_id) if not item or item.user_id != self.user_info['uid']: return self.flash_out( "The item you are trying to delete does not belong to you or this item was already deleted.", 401, "/") result = Items.delete_by_item(dbs, item) if not result: return self.flash_out( "The item you are trying to delete does not exist", 401, "/") return self.flash_out("Your item was deleted successfully", 200, "/")
def newItem(category_id): if 'username' not in login_session: return redirect('/login') if request.method == 'POST': addItem = Items(name=request.form['name'], description=request.form['description'], category_id=category_id) session.add(addItem) session.commit() return redirect(url_for('showItem', category_id=category_id)) else: return render_template('newItem.html', category_id=category_id)
def get(self, category, item_id): my_item = Items.get_by_id(dbs, item_id) # Check if the item requested is in the db or if it belongs to the # session user if not my_item or my_item.user_id != self.user_info['uid']: return self.flash_out( "The item you are looking for does not exist or you are not allowed to delete it", 401, "/") return self.render_template("item_update.html", my_item=my_item, my_category=category, categories=other_info.item_categories)
def add_item(): """App route function to create items with POST requests.""" # Verify user login. If not, redirect to login page. login_status = None if 'email' in login_session: login_status = True else: flash('Please log in.') return redirect(url_for('home')) if request.method == 'POST': # Get form fields name = request.form['name'] description = request.form['description'] category = request.form['item_category'] # Retrieve the database ID of the selected category category_id = (session.query(Categories).filter_by( name=category.replace('-', ' ')).one()) # Retrieve user's database ID for the item's database entry user_db_id = (session.query(Users).filter_by( email=login_session['email']).one()).id print( "Current user's database primary key id is {}.".format(user_db_id)) print('Database ID of category is {}.'.format(category_id.id)) # Flash messages for incomplete item info if not request.form['name']: flash('Please add item name') return redirect(url_for('add_item')) if not request.form['description']: flash('Please add a description') return redirect(url_for('add_item')) # Query database for item name item_name_in_db = (session.query( Items.name).filter_by(name=name).all()) # If the item name is already in the database, don't add if item_name_in_db: print('Item name "{}" already in database.'.format(name)) flash('Item name "{}" already in database.'.format(name)) return redirect(url_for('add_item')) # Create object with form field info to add to database new_item = Items(name=name, description=description, category_id=category_id.id, creator_db_id=user_db_id) session.add(new_item) session.commit() print('Item "{}" created.'.format(new_item.name)) # Return to homepage return redirect(url_for('home')) else: # Query database with SQLAlchemy to display categories on page categories = session.query(Categories).all() # Render webpage return render_template('add_item.html', categories=categories, login_status=login_status)
def get(self, category): # Routing regardless of case, make category a title in order to match # the db category = category.title() my_items = Items.get_by_category_w_names(dbs, category) if my_items == False: return self.flash_out( "This category does not exist: {}".format(category), 404, url_for("home_view")) return self.render_template("category.html", items=my_items, my_category=category, categories=other_info.item_categories)
def newItem(category_id): if request.method == 'POST': newItem = Items(item=request.form['item'], category_id=category_id, description=request.form['description']) session.add(newItem) session.commit() flash("new item created!") return redirect(url_for('showCategory', category_id=category_id)) else: return render_template('newitem.html', category_id=category_id)
def get(self, category, item_id): category = category.title() my_item = Items.get_by_id(dbs, item_id) if not my_item: return self.flash_out( "The item you are looking for does not exist", 404, "/") owner = User.get_by_id(dbs, my_item.user_id) # This really shouldn't happen but it's good to account for this # possibility if not owner: return self.flash_out( "Something went wrong, try again, if the problem persists contact us!", 500, "/") return self.render_template("item.html", my_category=category, owner=owner, my_item=my_item, categories=other_info.item_categories)
def newItem(collection_id): """Allows a logged-in user to add a new item to the database, associating an image file, if desired, as well as a number of metadata categories Args: collection_id""" if 'username' not in login_session: return redirect('/login') if request.method == 'POST': # Get the list of files to work with, multiple files supported upload_files = request.files.getlist('up_files') print "upload_files length is: " print len(upload_files) print upload_files[0] # Get the title information title = request.form['name'] if not title: title = 'untitled' # Get the subject(s) associated with the item subject_ids = request.form.getlist('subject') # Get the author(s) associated with the item, # then add the author's name to the database if it isn't present author_names = request.form.getlist('author') handleAuthors(author_names) # Get the person/people associated with the item, # then add the name(s) to the database if not present people_names = request.form.getlist('people') handlePeople(people_names) if len(upload_files[0].filename) > 0: for file in upload_files: # Save the creation date of the record now = datetime.datetime.now() create_datetime = now # Copy the file to the correct location, and return its path item_url, newPath = uploadFile(file, now) # Collect relevant EXIF information from the file file_create, orientation = getExif(newPath) # If there was EXIF information about the date the image was created, # save this as the create_date, otherwise continue to use 'now' if file_create: file_string = ''.join(file_create) dt_obj = datetime.datetime.strptime(file_string, "%Y:%m:%d %H:%M:%S") create_datetime = dt_obj # Create the new item newItem = Items(title = title, description = request.form['description'], item_type = 'image', note = request.form['notes'], ## the only difference ## create_date = create_datetime, date_added = datetime.datetime.now(), user_id=login_session['user_id']) newItem.archive_url = item_url # Create many-to-many associations for subj_id in subject_ids: subj = session.query(Subject).filter_by(id = subj_id).one() newItem.subject.append(subj) for auth_name in author_names: thisAuth = session.query(Authors).filter_by(name = auth_name).one() newItem.authors.append(thisAuth) for person_name in people_names: thisPerson = session.query(People).filter_by(name = person_name).one() newItem.people.append(thisPerson) # Eventually, we will add the ability to assign an image to multiple # collections, but for now, we just add to the current collection. coll = session.query(Collections).filter_by(id = collection_id).one() newItem.collections.append(coll) # Whew! Let's add this item and commit it. session.add(newItem) session.commit() else: # Create the new item newItem = Items(title = title, description = request.form['description'], ## change item type to unknown ## item_type = 'unknown', note = request.form['notes'], date_added = datetime.datetime.now(), user_id=login_session['user_id']) ## NO item url # Create many-to-many associations for subj_id in subject_ids: subj = session.query(Subject).filter_by(id = subj_id).one() newItem.subject.append(subj) for auth_name in author_names: thisAuth = session.query(Authors).filter_by(name = auth_name).one() newItem.authors.append(thisAuth) for person_name in people_names: thisPerson = session.query(People).filter_by(name = person_name).one() newItem.people.append(thisPerson) # Eventually, we will add the ability to assign an image to multiple # collections, but for now, we just add to the current collection. coll = session.query(Collections).filter_by(id = collection_id).one() newItem.collections.append(coll) # Whew! Let's add this item and commit it. session.add(newItem) session.commit() flash("New Item(s) Created!") return redirect(url_for('showCollection', collection_id=collection_id)) else: # Pass the list of all subjects to populate the dropdown menu subjectList = session.query(Subject).all() # So, eventually, there will be some sort of autofill using these lists, # so we're passing them even though it's not in place yet. collectionList = session.query(Collections).all() authorList = session.query(Authors).all() personList = session.query(People).all() return render_template('additem.html', collection_id=collection_id, collectionList=collectionList, authorList=authorList, subjectList=subjectList, personList=personList)
def get(self): # get all items and the name fo their owner from the db, limit 9 my_items = Items.get_all_w_names(dbs, limit=9) return self.render_template( "home.html", items=my_items, categories=other_info.item_categories)
def newItem(collection_id): if 'username' not in login_session: return redirect('/login') if request.method == 'POST': #We will use now to save the creation date of the record, #and as a default value for the file creation date. now = datetime.datetime.now() #Get the list of files to work with, multiple files supported upload_files = request.files.getlist('up_files') #Get the create date, which will be reassigned if not specified create_datetime = request.form['create_date'] #Get the subject(s) associated with the item subject_ids = request.form.getlist('subject') #Get the author(s) associated with the item, #then add the author's name to the database if it isn't present allAuthors = session.query(Authors.name).all() authorList = [i[0] for i in allAuthors] author_names = request.form.getlist('author') for auth_name in author_names: if auth_name not in authorList: addAuthor(auth_name) #Get the person/people associated with the item, #then add the name(s) to the database if not present allPeople = session.query(People.name).all() peopleList = [i[0] for i in allPeople] people_names = request.form.getlist('people') for person_name in people_names: if person_name not in peopleList: addPerson(person_name) for file in upload_files: filename = secure_filename(file.filename) savename = file.filename.rsplit('.',1)[0]+now.strftime("%Y-%m-%d-%H-%M-%S-%f"), file.filename.rsplit('.', 1)[1] item_url = ''.join(savename) newPath = os.path.join(app.config['UPLOAD_FOLDER'], item_url) photos.save(newPath) file_create, orientation = getExif(newPath) flash("File Uploaded!") if create_datetime == '': if file_create: file_string = ''.join(file_create) dt_obj = datetime.datetime.strptime(file_string, "%Y:%m:%d %H:%M:%S") create_datetime = dt_obj else: create_datetime = now newItem = Items(title = request.form['name'], description = request.form['description'], type = request.form['type'], note = request.form['notes'], create_date = create_datetime, collection_id = collection_id, shelf_location = request.form['shelf'], date_added = datetime.datetime.now(), user_id=login_session['user_id']) newItem.archive_url = item_url for subj_id in subject_ids: subj = session.query(Subject).filter_by(id = subj_id).one() newItem.subject.append(subj) for auth_name in author_names: thisAuth = session.query(Authors).filter_by(name = auth_name).one() newItem.authors.append(thisAuth) for person_name in people_names: thisPerson = session.query(People).filter_by(name = person_name).one() newItem.people.append(thisPerson) coll = session.query(Collections).filter_by(id = collection_id).one() newItem.collections.append(coll) session.add(newItem) session.commit() flash("New Item Created!") return redirect(url_for('showCollection', collection_id=collection_id)) else: collectionList = session.query(Collections).all() subjectList = session.query(Subject).all() authorList = session.query(Authors).all() personList = session.query(People).all() return render_template('additem.html', collection_id=collection_id, collectionList=collectionList, authorList=authorList, subjectList=subjectList, personList=personList)
def post(self, category, item_id): # Check CSRF state state = self.request.form.get("csrf") if state != session['state']: return self.flash_out( "The CSRF state is not valid, try again", 401, "/") # Check if item is in the db item = Items.get_by_id(dbs, item_id) if not item or item.user_id != self.user_info['uid']: return self.flash_out( "The item you are trying to update does not belong to you.", 401, "/") # List of fileds allowed to be updated update_fields = ["name", "description", "category", "link"] new_vals = {} for field in update_fields: new_val = self.request.form.get(field) # if the user is choosing to update this field and it's not the # same value as before if new_val and not getattr(item, field) == new_val: new_vals[field] = new_val setattr(item, field, new_val) # if there are updates and they are valid properties if new_vals: new_vals_valid, new_vals_test_error = utils.test_item_prop( new_vals) if not new_vals_valid: return self.flash_out(new_vals_test_error, 401, "/") prev_img_id = None upload_file = self.request.files["picture"] if upload_file: if item.picture: # Changing the image name in order to prevent atomicity # problems (deleting and immediately writing to the same id) image_name = item.picture.split(".")[0] image_number = ( (int(image_name[-1]) + 1) if image_name[-1].isdigit() else 1) image_name = image_name + str(image_number) else: image_name = utils.remove_special_characters( item.name + item.category) + "_img" img = self.upload_image_file(upload_file, image_name) if img: prev_img_id = item.picture item.picture = img.id # if there are no new values and no new image elif not new_vals: return self.flash_out(" No new updates submitted", 200, url_for( "item_view", category=item.category, item_id=item.id)) # persist the changes Items.update_item(dbs, item) # Erase the previous picture from the db if prev_img_id: Images.delete_by_id(dbs, prev_img_id) return self.flash_out("Item has been updated", 200, url_for( "item_view", category=item.category, item_id=item.id))