class CategoryDAOTest(unittest.TestCase): def setUp(self): self.testbed = testbed.Testbed() self.testbed.activate() self.testbed.init_datastore_v3_stub() self.testbed.init_memcache_stub() self.cat_dao = CategoryDAO() self.cat_arroces = Category(name="Arroces", description="Arrocitos") self.cat_sopas = Category(name="Sopas e cremas", description="Categoria chula") self.cat_pastas = Category(name="Pastas", description="Fresco, fresco") self.cat_arroces_key = self.cat_arroces.put() self.assertEqual(Category.query().count(), 1, "Failed to initialize test") def tearDown(self): self.testbed.deactivate() def test_save_category(self): self.cat_dao.save(self.cat_sopas) self.assertEqual(Category.query().count(), 2) self.cat_dao.save(self.cat_pastas) self.assertEqual(Category.query().count(), 3) self.assertIsInstance(Category.query().fetch()[0], Category) def test_get_category(self): r = self.cat_dao.get(self.cat_arroces_key.urlsafe()) self.assertIsInstance(r, Category) self.assertEqual(r.name, u"Arroces") def test_delete_category(self): self.cat_dao.delete(self.cat_arroces.key.urlsafe()) num_categories = Category.query().count() self.assertEqual(num_categories, 0) def test_update_category(self): self.cat_arroces.name = "Arrocines" self.cat_dao.update(self.cat_arroces) self.cat_arroces = Category.query().fetch()[0] self.assertEqual(self.cat_arroces.name, "Arrocines") def test_get_all(self): self.cat_pastas.put() self.cat_sopas.put() cat_list = self.cat_dao.get_all() self.assertEqual(len(cat_list), 3) self.assertIsInstance(cat_list[0], Category) self.assertEqual(cat_list[0].name, u"Arroces") self.assertIsInstance(cat_list[1], Category) self.assertEqual(cat_list[1].name, u"Pastas") self.assertIsInstance(cat_list[2], Category) self.assertEqual(cat_list[2].name, u"Sopas e cremas")
def setUp(self): self.testbed = testbed.Testbed() self.testbed.activate() self.testbed.init_datastore_v3_stub() self.testbed.init_memcache_stub() self.cat_dao = CategoryDAO() self.cat_arroces = Category(name="Arroces", description="Arrocitos") self.cat_sopas = Category(name="Sopas e cremas", description="Categoria chula") self.cat_pastas = Category(name="Pastas", description="Fresco, fresco") self.cat_arroces_key = self.cat_arroces.put() self.assertEqual(Category.query().count(), 1, "Failed to initialize test")
def submit_category(): name = bottle.request.forms.get("name") user = active_user() if not has_permission(user,'create-board'): return flash_message("You're not allowed to do that!","/","Error") elif name is None or len(name)<1: return flash_message("You need to enter a name!","/category","Error") else: tags = bottle.request.forms.get("tags","") description = bottle.request.forms.get("desc","") MIN_TAG_LENGTH = 3 tags = [t.strip() for t in tags.split() if len(t.strip())>=MIN_TAG_LENGTH] board = Category() board.update({"name":name,"tags":tags,"description":description}) return flash_message("Your board has been created!","/category/"+board.key,"Success")
def category_photo(category_id): category = Category.get_by_id(category_id) if not category.photo: return "error", 500 return send_file(io.BytesIO(category.photo), attachment_filename='category_photo.png', mimetype=category.photo_mimetype)
def new_thread(key=None): user = active_user() if has_permission(user,'new-thread'): new_thread = Thread() first_post = Post() name = bottle.request.forms.get("name") content = bottle.request.forms.get("content") tags = parse_tags(bottle.request.forms.get("tags","")) first_post.update({ "owner":user.key, "content":content }) new_thread.update({ "name":name, "owner":user.key, "posts":[first_post.key], "tags":tags }) forum = Forum.load(forum_key()) target = Category.load(decrypt(key)) if key else forum target.threads.append(new_thread.key) target.save() new_thread.save() return flash_message("Your thread has been created.","/thread/"+new_thread.slug+"/","Success") raise bottle.HTTPError(404, """Sorry, but we weren't able to find what you were looking for. I hope that someday you do find it, but when you do, it won't be here. """)
def get_by_name(self, name): """ Obtains a category by name. @param name: Name of category. @return: Category object. """ return Category.query(Category.name == name).fetch()[0]
def delete_category(category_code): if Product().is_product_by_category_code(category_code): flash("There is a Product in this Category, Deleted Failed!") flash("You can delete this product from 'Product Page'") return redirect(url_for('categories_manager.index')) Category().delete_category(category_code) flash('Deleted Successfully!') return redirect(url_for('categories_manager.index'))
def admin(): if not session.get("admin"): return login() if request.method == "POST": file = request.files.get("file", None) content_type = None photo = None if file: file_data = file.read() content_type = file.content_type # photo=images.Image(file_data) photo = images.resize(file_data, width=500, height=500) category = Category(id=request.form["name"].strip(), categoryID=request.form["name"], name=request.form["name"], photo=photo, photo_mimetype=content_type) category.put() fields = [] fields.append( Field(name="name", title="Category Name", the_type='text', identifier='name', placeholder="Category Name")) fields.append( Field(name='file', title="Upload Photo", the_type="file", placeholder="Upload Photo", identifier="file", tag="file")) title = "Create Category" form = Form(fields=fields, title=title) reviews = Review.query(Review.flagged == True) categories = Category.query() return render_template("admin_homepage.html", reviews=reviews, categories=categories, category_form=form)
def loadUserDataById(self, user_id): self.transactions.clear() self.categories.clear() self.family_users.clear() conn = pymysql.connect(host=HOST, user=USER, password=PASSWORD, db=DB, charset='utf8') cursor = conn.cursor() sql = "SELECT * FROM `users` WHERE `ID` = '%s'" % (user_id) cursor.execute(sql) result = cursor.fetchone() self.user = User(result[0], result[1], result[2], result[3], result[4], result[5]) sql = "SELECT * FROM `families` WHERE `ID` = '%d'" % ( self.user.family_id) cursor.execute(sql) result = cursor.fetchone() self.family = Family(result[0], result[1], result[2], result[3], result[4]) sql = "SELECT * FROM `categories` WHERE `Owner_ID` = '%d' OR `Owner_ID` = '0'" % ( self.user.family_id) cursor.execute(sql) result = cursor.fetchall() for s in result: self.categories.append(Category(s[0], s[1], s[2])) sql = "SELECT * FROM `users` WHERE `Family_ID` = '%d'" % ( self.user.family_id) cursor.execute(sql) result = cursor.fetchall() for s in result: self.family_users.append(User(s[0], s[1], s[2], s[3], s[4], s[5])) sql = "SELECT * FROM `transactions` WHERE `Family_ID` = '%d' ORDER BY `Datetime` DESC" % ( self.user.family_id) cursor.execute(sql) result = cursor.fetchall() for s in result: if self.family.safemode == 1 and self.user.status == 3: b_user = self.getFamilyUserById(s[4]) if b_user.status != 3: continue else: self.transactions.append( Transaction(s[0], s[1], s[2], s[3], s[4], s[5], s[6])) else: self.transactions.append( Transaction(s[0], s[1], s[2], s[3], s[4], s[5], s[6])) cursor.close() conn.close()
def new_thread_form(key=None): user = active_user() if has_permission(user,"new-thread"): forum = Forum.load(forum_key()) target = Category.load(decrypt(key)) if key else forum return template("new_thread",target=target,user=user,forum=forum) raise bottle.HTTPError(404, """Sorry, but we weren't able to find what you were looking for. I hope that someday you do find it, but when you do, it won't be here. """)
def update_category(): # Updates another field which isn't the category code if request.form['given-code'] != request.form['category-code']: # if Category().is_category_code(request.form['category-code']): # flash("Category Code is already exist. Try again!") flash( "Can't update Category code, You can delete and add new category.") return redirect(url_for('categories_manager.index')) Category().update_category(request.form['category-code'], request.form['category-name'], request.form['img']) flash('Updated Successfully!') return redirect(url_for('categories_manager.index'))
def category_page(key): key=decrypt(key) user=active_user() forum = Forum.load(forum_key()) board = Category.load(key) if board.has_permission(user,'list'): data={} data['user']=user data['forum']=forum data['threads']=board.threads data['trends']=board.topics(user) or [] data['tags'] = board.tags data['mode']='trending' return template("home",**data) return flash_message("No permission. :(","/","No permission.")
def add_category(): if not request.form['category-code'].isdigit(): flash("Category Code must be an integer. Try again!") return redirect(url_for('categories_manager.index')) if Category().is_category_code(request.form['category-code']): flash("Category Code is already exist. Try again!") return redirect(url_for('categories_manager.index')) if int(request.form['category-code']) < 0 or int( request.form['category-code']) > 127: flash( "Category Code is not valid (should be between 0 to 127). Try again!" ) return redirect(url_for('categories_manager.index')) category = Category() category.category_code = request.form['category-code'] category.category_name = request.form['category-name'] category.img = request.form['img'] category.add_category() flash('Added Successfully!') return redirect(url_for('categories_manager.index'))
def browse(category_id): if not session.get("logged_in"): return login() items = Item.query(Item.category == category_id, Item.sold == False) for item in items: item.item_id = item.key.id() notifications = Notification.query( Notification.user == session["user_id"]).order(-Notification.time) category = Category.get_by_id(category_id) return render_template("browse.html", items=items, category=category, category_id=category_id, notifications=notifications)
def update(): # Checks that the category code exists: if not Category().is_category_code(request.form['category-code']): flash("Category Code doesn't exist. Try again!") return redirect(url_for('product_manager.index')) # # Checks that the ID inserted in the range # if int(request.form['id']) < 0 or int(request.form['id']) > 2147483647: # flash("The ID is not valid. Try again!") # return redirect(url_for('product_manager.index')) if request.form['given-id'] != request.form['id']: flash("Can't update ID, You can delete and add new product.") return redirect(url_for('product_manager.index')) Product().update_product(request.form['name'], request.form['price'], request.form['prev-price'], request.form['description'], request.form['img'], request.form['category-code'], request.form['given-id']) flash('Updated Successfully!') return redirect(url_for('product_manager.index'))
def home(): if not session.get("logged_in"): return login() the_categories = Category.query() # categories=[] # num_categories=0 # for category in the_categories : # categories.append(category) # num_categories+=1 # dividers=[2,4,3] # category_lists=[] # count=2 # index=0 # current_list=[] # left_over=False # for category in categories : # left_over=True # current_list.append(category) # count-=1 # if count==0 : # category_lists.append((current_list,100.0/len(current_list))) # current_list=[] # index+=1 # count=dividers[index] # left_over=False # if left_over : # category_lists.append((current_list,100.0/len(current_list))) notifications = Notification.query( Notification.user == session["user_id"]).order(-Notification.time) # return render_template("home2.html", # category_lists=category_lists, # notifications=notifications) return render_template("home.html", categories=the_categories, notifications=notifications)
def add_product(): product = Product() product.id = request.form['id'] product.name = request.form['name'] product.price = request.form['price'] product.description = request.form['description'] product.img = request.form['img'] product.category_code = request.form['category-code'] # Checks that the ID doesnt exist already if Product().get_product(request.form['id']): flash("The ID is already exist. Try again!") return redirect(url_for('product_manager.index')) # Checks that the category code exists: if not Category().is_category_code(product.category_code): flash("Category Code doesn't exist. Try again!") return redirect(url_for('product_manager.index')) # Checks that the ID inserted in the range if int(request.form['id']) < 0 or int(request.form['id']) > 2147483647: flash("The ID is not valid. Try again!") return redirect(url_for('product_manager.index')) product.add_product() flash('Added Successfully!') return redirect(url_for('product_manager.index'))
def do_inserts(): cat_arroces = Category(name="Arroces", description="Arrocitos") code = cat_arroces.put().urlsafe() cat_arroces.id = code cat_arroces.put() cat_pastas = Category(name="Pastas", description="Lorem ipsum") code = cat_pastas.put().urlsafe() cat_pastas.id = code cat_pastas.put() cat_sopas = Category(name="Sopas e cremas", description="Fresco, fresco") code = cat_sopas.put().urlsafe() cat_sopas.id = code cat_sopas.put() rec1 = Recipe(name="Arroz con chícharos", category=cat_arroces, servings=4, ingredients=[Ingredient(name="Arroz", quantity="500gr"), Ingredient(name="Chícharos", quantity="300gr")], steps=["Cocemos o arroz", "Botámoslle os chícharos", "Servir en quente"]) rec2 = Recipe(name="Macarróns con tomate", category=cat_pastas, servings=6, ingredients=[Ingredient(name="Macarróns", quantity="600gr"), Ingredient(name="Tomate frito", quantity="100gr")], steps=["Cocemos os macarróns", "Botámoslleo tomate frito", "Servimos en quente"]) rec3 = Recipe(name="Gazpacho andaluz", category=cat_sopas, servings=6, ingredients=[Ingredient(name="Aceite de oliva", quantity="120cc"), Ingredient(name="Auga", quantity="500cc"), Ingredient(name="Dente de allo", quantity="2"), Ingredient(name="Ovo duro", quantity="1"), Ingredient(name="Miga de pan", quantity="100gr"), Ingredient(name="Pepino", quantity="50gr"), Ingredient(name="Pemento verdeo", quantity="50gr"), Ingredient(name="Sal", quantity="1 pizca"), Ingredient(name="Tomates naturais", quantity="1kg"), Ingredient(name="Vinagre", quantity="60cc"), Ingredient(name="Cebola picada", quantity="1/2")], steps=[ "No bol da batidora ponse o aceite, a vinagre, a sal e ben cortados, os allos, o pepino e o pemento." " Triturase todo ben e vaise metendo na batidora", "Vaise incorporando o tomate, previamente escaldado e pelado, e siguese pasando pola batidora", "Ponse o pan en remollo e escorese e engadeselle o anterior", "Incorporase a auga para que non quede tan espeso e uns cubiños de xeo para que este mais grio", "Servese en tazons e en diferentes pratos individuais. Disponse un pouco de pemento picado, a " "cebola, o pepino, o tomate natural e o ovo duro, previamente cocido, e todo elo finalmente " "picado para engadir se se desexa ao gazpacho"]) rec1.put() rec2.put() rec3.put()
def test_save_category(self): self.cat_dao.save(self.cat_sopas) self.assertEqual(Category.query().count(), 2) self.cat_dao.save(self.cat_pastas) self.assertEqual(Category.query().count(), 3) self.assertIsInstance(Category.query().fetch()[0], Category)
def test_delete_category(self): self.cat_dao.delete(self.cat_arroces.key.urlsafe()) num_categories = Category.query().count() self.assertEqual(num_categories, 0)
def test_update_category(self): self.cat_arroces.name = "Arrocines" self.cat_dao.update(self.cat_arroces) self.cat_arroces = Category.query().fetch()[0] self.assertEqual(self.cat_arroces.name, "Arrocines")
def c(): """Return a friendly HTTP greeting.""" for i in xrange(10): category = Category(categoryID=str(i), name=str(i)) category.put() return "splash!"
def my_item(item_id): if not session.get("logged_in"): return login() item_id = int(item_id) item = Item.get_by_id(item_id) if request.method == "POST": if item.seller_id != session["user_id"]: return "Uninformative Error", 500 if request.form.get("tags"): tags = request.form["tags"].split(" ") for tag in tags: if tag == "": continue tag = tag.strip().lower() exists = Tag.get_by_id(tag) if not exists: new_tag = Tag(id=tag, name=tag) new_tag.put() exists = Item_Tag.get_by_id(str(item_id) + tag) if not exists: new_item_tag = Item_Tag(id=str(item_id) + tag, item=item_id, tag=tag) new_item_tag.put() else: item.name = request.form.get("name") item.description = request.form.get("description") item.category = request.form.get("category") item.price = float(request.form.get("price")) item.biddable = False if request.form.get("biddable"): item.biddable = True item.put() offers = Offer.query(Offer.item == item_id).order(Offer.amount) fields = [] fields.append( Field(name="name", title="Name", the_type='text', identifier='name', placeholder="Item Name", value=item.name)) fields.append( Field(name='description', title="Description", the_type="textarea", identifier='description', placeholder='Descriptive Description', tag="textarea", value=item.description)) categories = Category.query() options = [] for category in categories: option = {} option["name"] = category.name option["value"] = category.categoryID options.append(option) fields.append( Field(name='category', title="Item Category", the_type="select", identifier="category", placeholder="Select Item Category", tag="select", options=options, value=item.category)) fields.append( Field(name='price', title="Price", the_type="number", identifier="price", placeholder="10.95", step=True, value=item.price)) fields.append( Field(name='biddable', title="Allow offer amounts other than suggested price.", the_type="number", identifier="biddable", tag="checkbox", value="checked" if item.biddable else "")) fields.append( Field(name='item_id', the_type="hidden", identifier="item_id", value=item.key.id(), hidden="hidden")) title = "Edit Item" form = Form(fields=fields, title=title) fields1 = [] fields1.append( Field(name="tags", title="Tags", the_type='text', identifier='name', placeholder="Enter descriptive words seperated by spaces.")) title1 = "" submit = "Add Tag" form1 = Form(fields=fields1, title=title1, submit=submit) tags = Item_Tag.query(Item_Tag.item == item_id) notifications = Notification.query( Notification.user == session["user_id"]).order(-Notification.time) return render_template("view_my_item.html", offers=offers, item=item, notifications=notifications, item_form=form, tag_form=form1, tags=tags)
def getCategoryById(self, id): for i in self.categories: if i.id == id: return i return Category(-1, "None", -1)
def post_item(): if not session.get("logged_in"): return login() if request.method == "GET": fields = [] fields.append( Field(name="name", title="Name", the_type='text', identifier='name', placeholder="Item Name")) fields.append( Field(name='description', title="Description", the_type="textarea", identifier='description', placeholder='Descriptive Description', tag="textarea")) categories = Category.query() options = [] for category in categories: option = {} option["name"] = category.name option["value"] = category.categoryID options.append(option) fields.append( Field(name='category', title="Item Category", the_type="select", identifier="category", placeholder="Select Item Category", tag="select", options=options)) fields.append( Field(name='price', title="Price", the_type="number", identifier="price", placeholder="10.95", step=True)) fields.append( Field(name='file', title="Upload Photo", the_type="file", placeholder="Upload Photo", identifier="file", tag="file")) fields.append( Field(name='biddable', title="Allow offer amounts other than suggested price.", the_type="number", identifier="biddable", tag="checkbox")) title = "Post Item" form = Form(fields=fields, title=title, submit="Post") notifications = Notification.query( Notification.user == session["user_id"]).order(-Notification.time) return render_template("post_item.html", item_form=form, notifications=notifications) if request.method == "POST": name = request.form.get("name") description = request.form.get("description") category = request.form.get("category") price = float(request.form.get("price")) seller_id = session["user_id"] biddable = False if request.form.get("biddable"): biddable = True # print "nooo" # return json.dumps(request.files) file = request.files.get("file", None) # print "whaattt??" file_data = None content_type = None photo = None if file: file_data = file.read() photo = images.resize(file_data, width=500, height=500) content_type = file.content_type new_item = Item(name=name, description=description, category=category, price=price, seller_id=seller_id, seller_name=session["first_name"] + " " + session["last_name"], biddable=biddable, sold=False, best_offer=0.0, photo=photo, photo_mimetype=content_type) new_item.put() return my_items()
def index(): categories_data = Category().get_all() return render_template('categories_manager.html', categories=categories_data)