Beispiel #1
0
    def test_delete_an_item(self):
        """ Delete an Item """
        item = Item(wishlist_id=1,
                    product_id=1,
                    name="toothpaste",
                    description="toothpaste for 2")
        item.save()
        self.assertEqual(len(Item.all()), 1)

        item.delete()
        self.assertEqual(len(Item.all()), 0)
Beispiel #2
0
    def test_delete_an_item(self):
        """ Delete an Item """
        item = Item(order_id=1,
                    product_id=1,
                    name="wrench",
                    quantity=1,
                    price=10.50)
        item.save()
        self.assertEqual(len(Item.all()), 1)

        item.delete()
        self.assertEqual(len(Item.all()), 0)
Beispiel #3
0
def saveimage(key):
	category = Category.get(key)
	items = Item.all().ancestor(category)
	item = Item.all().ancestor(category).filter('title =',request.form.get('items')).get()
	if request.method == 'POST':
		image_file = request.files['image']
		headers = image_file.headers['Content-Type']
		blob_key = parse_options_header(headers)[1]['blob-key']
		item.blob_key = blob_key
		item.image_url = images.get_serving_url(blob_key)
		item.put()
	return redirect('edit/images/'+key)
Beispiel #4
0
def saveimage(key):
    category = Category.get(key)
    items = Item.all().ancestor(category)
    item = Item.all().ancestor(category).filter("title =", request.form.get("items")).get()
    if request.method == "POST":
        image_file = request.files["image"]
        headers = image_file.headers["Content-Type"]
        blob_key = parse_options_header(headers)[1]["blob-key"]
        item.blob_key = blob_key
        item.image_url = images.get_serving_url(blob_key)
        item.put()
    return redirect("edit/images/" + key)
Beispiel #5
0
    def test_add_an_item(self):
        """ Create an Item and add it to the database """
        items = Item.all()
        self.assertEqual(items, [])
        item = Item(wishlist_id=1,
                    product_id=1,
                    name="toothpaste",
                    description="toothpaste for 2")
        self.assertEqual(item.id, None)
        item.save()

        self.assertEqual(item.id, 1)
        items = Item.all()
        self.assertEqual(len(items), 1)
Beispiel #6
0
    def test_add_an_item(self):
        """ Create an Item and add it to the database """
        items = Item.all()
        self.assertEqual(items, [])
        item = Item(order_id=1,
                    product_id=1,
                    name="wrench",
                    quantity=1,
                    price=10.50)
        self.assertEqual(item.id, None)
        item.save()

        self.assertEqual(item.id, 1)
        items = Item.all()
        self.assertEqual(len(items), 1)
Beispiel #7
0
def main():
	"""Varrer os itens antigos e excluí-los"""
	last_month = datetime.now() - timedelta(days=30)
	last_six_months = datetime.now() - timedelta(days=180)
	# Remover itens não classificados com mais de um mês
	remove_list = Item.all().filter("classified =",False).filter("date <",last_month)
	for remove in remove_list:
		logging.info("O item %s foi removido" % remove.key().name())
		remove.delete()
	# Arquivar itens classificados com mais de seis meses
	archive_list = Item.all().filter("classified =",True).filter("date <",last_six_months)
	for archive in archive_list:
		logging.info("O item %s foi arquivado" % archive.key().name())
		archive.is_archived = True
		archive.put()
Beispiel #8
0
    def show_results(self, account, category):
        items = Item.all()
        cat_key = db.Key.from_path("Account", account, "Category", category)
        items.ancestor(cat_key)

        self.response.out.write("<html>")
        for item in items.run():

            percent = ""
            if (item.win + item.lose) == 0:
                percent = "-"
            else:
                percent = item.win // (item.win + item.lose)

            self.response.out.write(
                """
                    <h2>Item name: %s,
                    win: %s,
                    lose: %s,
                    percentage: %s</h2>
                """
                % (item.item_name, item.win, item.lose, percent)
            )

        self.response.out.write("<h3>Back to <a href='/'> Home </a></h3>")

        self.response.out.write("</html>")
Beispiel #9
0
 def post(self):
     user = users.get_current_user()
     
     if user == None:
         self.redirect("/")
         return 
     
     # get category information
     category = self.request.get('category') 
     item = self.request.get('item')
     newname = self.request.get(item)
     if newname != "":
         cs = Category.all()
         cs.filter('user ='******'category =', category) # get category
         c = cs.get()
         if c != None:
             items = Item.all()
             items.filter('item =', item)
             items.ancestor(c.key())
             i = items.get()
             if i != None:
                 # reset
                 i.item = newname
                 i.win = 0
                 i.lose = 0
                 i.rate = 0
                 i.put()
                 message = 'Reset "%s" successfully.' % newname
                 self.redirect("/manageCategory?category=%s&message=%s" % (category, message))
                 return
                 
     self.redirect("/manageCategory?category=%s" % category)
     # return 
Beispiel #10
0
    def get(self):  
        user = users.get_current_user()
        
        if user:
            login = True
            url = users.create_logout_url(self.request.uri)
        else:
            login = False
            url = users.create_login_url(self.request.uri)
            self.redirect("/")
            return 
        
        creator = self.request.get('creator')
        category = self.request.get('category') 
        cats = Category.all()
        cats.filter('user ='******'category =', category) # get category
        c = cats.get()
        
        if c == None:
            self.redirect("/")
            return
        
        items = Item.all()
        items.ancestor(c.key()) # get all the items of c
        itemList = []
        for item in items.run():
            itemList.append(item.item)
        
        if len(itemList) > 1:
            length = len(itemList)
            i = random.randint(0, length - 1)
            j = random.randint(0, length - 1)
            while i == j:
                j = random.randint(0, length - 1)

            choice1 = itemList[i]
            choice2 = itemList[j]
            error = None
        else:
            choice1 = None
            choice2 = None
            error = "Options not enough!"
        
        template_values = {
            'user': user,
            'login': login, 
            'url': url,
            'winner': None,
            'loser': None,
            'choice1': choice1, 
            'choice2': choice2,
            'creator': creator,
            'creatorName': c.username,
            'category': category,
            'error': error
        }
        
        path = os.path.join(os.path.dirname(__file__), 'templates/vote.html')
        self.response.out.write(template.render(path, template_values))
Beispiel #11
0
def results(key, expired=None):
    my_votes = {}
    my_comments = {}
    user_comments = {}
    category = Category.get(key)
    items = Item.all().ancestor(category).order("-wins").order("losses")
    count = 0
    for i in items:
        item = (
            UserVote.all().ancestor(i).order("-wins").order("losses").filter("voter =", users.get_current_user()).get()
        )
        if not item:
            my_votes[count] = [i.title, "-", "-"]
        else:
            my_votes[count] = [i.title, item.wins, item.losses]  # the count helps maintain the order -wins and losses
        count += 1

    for c in items:
        user_comments[c.title] = UserComment.all().ancestor(c)
        my_comment = UserComment.all().ancestor(c).filter("commenter =", users.get_current_user()).get()
        if my_comment:
            my_comments[c.title] = my_comment.comment
    return render_template(
        "results.html",
        items=items,
        key=key,
        title=category.title,
        owner=category.owner.email(),
        my_votes=my_votes,
        my_comments=my_comments,
        user_comments=user_comments,
        expired=expired,
    )
Beispiel #12
0
def save_edited_category():
	cat_name = request.form.get('category')
	key = request.form.get('key')
	existing = Category.all().filter('owner =',users.get_current_user())
	for e in existing:
		if e.title.lower() == cat_name.lower():
			if not str(e.key()) == key:
				error = "You already have a category with that name. Please choose a different name"
				return Response(status=400)
	category = Category.get(key)
	items_from_form = request.form.get('items').split(',')
	old_items_from_db = Item.all().ancestor(category)
	for item in old_items_from_db:
		if not item.title in items_from_form:
			db.delete(item)
		else:
			items_from_form.remove(item.title)

	for new_item in items_from_form:
		if not new_item == '':
			i = Item(parent=category,title=new_item)
			i.put()
	category.title = request.form.get('category')
	category.put()
	return jsonify(new_items = items_from_form)
Beispiel #13
0
 def get(self, subdomain, to_cache):
     logging.info(subdomain)
     '''Saving current namespace'''
     namespace = namespace_manager.get_namespace()
     '''Changing the namespace'''
     namespace_manager.set_namespace(subdomain)
     
     '''MEMCACHE OF THE NAMESPACE'''
     data = memcache.get('lastopinion')
     if data:
         to_write = 'The last buyer said: <blockquote>%s</blockquote>' %data
         if not memcache.set('lastopinion',to_cache):
             to_write = 'A cache error happened :('
             pass
         
     else:
         to_write = 'We have not stored what the last buyer said'
         if not memcache.add('lastopinion',to_cache):
             to_write = 'A cache error happened 2 :('
         
     
     query = Item.all().fetch(10)
     to_write += '<br>Items in this shop</br>'
     for i in query:
         to_write += '<blockquote>item: %s qty: %s</blockquote>' %(i.name,i.qty)
     
     namespace_manager.set_namespace(namespace)
     self.response.write(to_write)
Beispiel #14
0
def search(keywordslist):
	keywords = keywordslist.split(" ")
	categories = {}
	keys = {}
	cat_count = {}
	for key in keywords:
		for category in Category.all():
			if category.title.lower().__contains__(key.lower()):
				categories[category.title] = Item.all().ancestor(category)
				keys[category.title] = category.key()
	for key in keywords:
		for item in Item.all():
			if item.title.lower().__contains__(key.lower()):
				categories[item.parent().title] = Item.all().ancestor(item.parent())
				keys[item.parent().title] = item.parent().key()
	return render_template('search_results.html',categories=categories, keys=keys, keywords=keywordslist)
Beispiel #15
0
def search(keywordslist):
    keywords = keywordslist.split(" ")
    categories = {}
    keys = {}
    cat_count = {}
    for key in keywords:
        for category in Category.all():
            if category.title.lower().__contains__(key.lower()):
                categories[category.title] = Item.all().ancestor(category)
                keys[category.title] = category.key()
    for key in keywords:
        for item in Item.all():
            if item.title.lower().__contains__(key.lower()):
                categories[item.parent().title] = Item.all().ancestor(item.parent())
                keys[item.parent().title] = item.parent().key()
    return render_template("search_results.html", categories=categories, keys=keys, keywords=keywordslist)
Beispiel #16
0
def save_edited_category():
    cat_name = request.form.get("category")
    key = request.form.get("key")
    existing = Category.all().filter("owner =", users.get_current_user())
    for e in existing:
        if e.title.lower() == cat_name.lower():
            if not str(e.key()) == key:
                error = "You already have a category with that name. Please choose a different name"
                return Response(status=400)
    category = Category.get(key)
    items_from_form = request.form.get("items").split(",")
    old_items_from_db = Item.all().ancestor(category)
    for item in old_items_from_db:
        if not item.title in items_from_form:
            db.delete(item)
        else:
            items_from_form.remove(item.title)

    for new_item in items_from_form:
        if not new_item == "":
            i = Item(parent=category, title=new_item)
            i.put()
    category.title = request.form.get("category")
    category.put()
    return jsonify(new_items=items_from_form)
Beispiel #17
0
 def post(self):
     user = users.get_current_user()
     
     if user == None:
         self.redirect("/")
         return 
     
     # get category information
     category = self.request.get('category') 
     item = self.request.get('item')
     if item != "":
         cs = Category.all()
         cs.filter('user ='******'category =', category) # get category
         c = cs.get()
         if c != None:
             items = Item.all()
             items.filter('item =', item)
             items.ancestor(c.key())
             i = items.get()
             if i == None:
                 self.redirect("/manageCategory?category=%s" % category)
                 return
             else:
                 i.delete()
     
     self.redirect("/manageCategory?category=%s" % category)
Beispiel #18
0
def get_item_list():

    """ 
    Returns all of the Items in a wishlist

    ---
    tags:
      - Item
    produces:
        - application/json

    parameters:
      - name: wishlist_id
        in: path
        description: the id of the wishlist
        type: integer
        required: true

    responses:
        200:
            description: A list of all Items in the wishlist
            schema:
                type: array
                items:
                    schema:
                        $ref: '#/definitions/Item'
    """
    items = Item.all()

    results = [item.serialize() for item in items]
    return make_response(jsonify(results), status.HTTP_200_OK)
Beispiel #19
0
 def post(self):
     user = users.get_current_user()
     
     if user == None:
         self.redirect("/")
         return 
     
     # get category information
     category = self.request.get('category') 
     item = self.request.get('newItem')
     if item != "":
         cs = Category.all()
         cs.filter('user ='******'category =', category) # get category
         c = cs.get()
         if c != None:
             items = Item.all()
             items.filter('item =', item)
             items.ancestor(c.key())
             if items.get() == None:
                 newItem = Item(item = item, win = 0, lose = 0, rate = 0, parent = c.key()) # post a new item
                 newItem.put() # save 
             else:
                 errorMessage = "Item %s already exists!" % item
                 self.redirect("/manageCategory?category=%s&error=%s" % (category, errorMessage))
                 return 
     
     self.redirect("/manageCategory?category=%s" % category)
Beispiel #20
0
    def vote_page(self, category, account):
        cat_key = db.Key.from_path("Account", account, "Category", category)
        category = db.get(cat_key)

        items = Item.all()
        items.ancestor(cat_key)

        rand1 = -1
        rand2 = -1
        if items.count() < 2:
            self.response.out.write(
                "<html><h2>Item number smaller than two, \
                            please choose another category</h2></html>"
            )
            self.choose_category_page(account)
            return
        else:
            rand1 = random.randint(0, items.count() - 1)
            rand2 = random.randint(0, items.count() - 1)
            while rand1 == rand2:
                rand2 = random.randint(0, items.count() - 1)

        template_values = {
            "item1": items[rand1],
            "item2": items[rand2],
            "account": account,
            "category": category,
            "logout_url": users.create_logout_url("/"),
        }
        path = os.path.join(os.path.dirname(__file__), "vote.html")
        self.response.out.write(template.render(path, template_values))
Beispiel #21
0
async def get_rate():
    qs = Item.all()
    dates = await DatePydantic.from_queryset(qs.only('date', ))
    resp_dict = {}
    for date in dates:
        q = await ItemPydantic.from_queryset(qs.filter(date=date.date))
        resp_dict[date.date] = q
    return resp_dict
Beispiel #22
0
 def get(self):
   for item in Item.all().filter("deleted ==", True):
     if item.item_set.count(1) == 0:
       item.delete()
   
   for cl in Checklist.all().filter("deleted ==", True):
     if cl.checklist_set.count(1) == 0:
       cl.delete()
Beispiel #23
0
    def test_fetch_all_items(self):
        """ Test fetching all Items """
        item = Item(order_id=1,
                    product_id=1,
                    name="wrench",
                    quantity=1,
                    price=10.50)
        item.save()
        item2 = Item(order_id=1,
                     product_id=2,
                     name="hammer",
                     quantity=2,
                     price=11)
        item2.save()
        Item.all()

        self.assertEqual(len(Item.all()), 2)
Beispiel #24
0
def edit_category(key):
	category = Category.get(key)
	expiration = ""
	if category.expiration:
		expiration = category.expiration.strftime("%m/%d/%Y")
	if category.owner != users.get_current_user():
		error = "You cannot edit a category that you do not own!"
		return render_template('errors.html',error=error)
	items = Item.all().ancestor(category)
	return render_template('edit_category.html', items=items, count=items.count(), key=key, title=category.title, owner=category.owner.email(), expiration=expiration)
Beispiel #25
0
    def del_cat(self, del_cat, currt_user):
        cat_key = db.Key.from_path("Account", currt_user.nickname(), "Category", del_cat)
        category = db.get(cat_key)

        items = Item.all()
        items.ancestor(cat_key)
        for item in items.run():
            item.delete()

        category.delete()
Beispiel #26
0
def export_xml(key):
	category = Category.get(key)
	items = Item.all().ancestor(category)
	disposition_filename = category.title + "_" + category.owner.email() + ".xml"
	root = Element('CATEGORY')
	SubElement(root,'NAME').text = category.title
	for item in items:
		i = SubElement(root,'ITEM')
		SubElement(i,'NAME').text = item.title
	return Response(tostring(root),status=200,mimetype="application/xml",headers={"Content-Disposition":"attachment;filename="+disposition_filename})
Beispiel #27
0
    def post(self):  
        user = users.get_current_user()
        
        if user == None:
            self.redirect("/")
            return 

        content = self.request.get('content')
        if content == None or content == "":
            self.redirect("/category")
            return 
        xmldoc = minidom.parseString(content)
        category = xmldoc.getElementsByTagName('CATEGORY')[0]
        categoryName = category.getElementsByTagName('NAME')[0].childNodes[0].nodeValue
        itemList = category.getElementsByTagName('ITEM')
        
        cats = Category.all()
        cats.filter("category =", str(categoryName))
        c = cats.get()
        
        if c == None: # category not exist
            newCat = Category() # create a new category
            newCat.category = categoryName
            newCat.user = user.email()
            newCat.username = user.nickname()
            newCat.put() # save
            for item in itemList:
                itemName = item.getElementsByTagName('NAME')[0].childNodes[0].nodeValue
                newItem = Item(item = itemName, win = 0, lose = 0, rate = 0, parent = newCat.key())
                newItem.put()
            importMessage = 'Import new category "%s" successfully.' % categoryName
            self.redirect("/category?importMessage=%s" % importMessage)
        else: # category exists
            items = Item.all()
            items.ancestor(c.key())
            
            oldItemNameList = []
            for item in items.run():
                oldItemNameList.append(item.item)
            
            newItemNameList = []
            for item in itemList:
                itemName = item.getElementsByTagName('NAME')[0].childNodes[0].nodeValue
                newItemNameList.append(itemName)
                if itemName not in oldItemNameList: # new item not exist
                    newItem = Item(item = itemName, win = 0, lose = 0, rate = 0, parent = c.key())
                    newItem.put()
            
            for item in items: # get old items
                if item.item not in newItemNameList: # old item not in new list, delete
                    item.delete()
                    
            importMessage = 'Import existed category "%s" successfully.' % categoryName
            self.redirect("/category?importMessage=%s" % importMessage)
Beispiel #28
0
def edit_image(key):
    category = Category.get(key)
    upload_url = blobstore.create_upload_url("/saveimage/" + key)
    items = Item.all().ancestor(category)
    return render_template(
        "edit_images.html",
        items=items,
        key=key,
        title=category.title,
        owner=category.owner.email(),
        upload_url=upload_url,
    )
Beispiel #29
0
def post_comment():
	key = request.form.get('key')
	item_name = request.form.get('item')
	user_comment = request.form.get('comment')
	category = Category.get(key)
	item = Item.all().ancestor(category).filter('title =',item_name).get()
	comment = UserComment.all().ancestor(item.key()).filter('commenter =',users.get_current_user()).get()
	if comment:
		return Response(status=400)
	else:
		comment = UserComment(parent=item.key(),comment=user_comment,commenter=users.get_current_user())
		comment.put()
		return Response(status=200)
Beispiel #30
0
def post_comment():
    key = request.form.get("key")
    item_name = request.form.get("item")
    user_comment = request.form.get("comment")
    category = Category.get(key)
    item = Item.all().ancestor(category).filter("title =", item_name).get()
    comment = UserComment.all().ancestor(item.key()).filter("commenter =", users.get_current_user()).get()
    if comment:
        return Response(status=400)
    else:
        comment = UserComment(parent=item.key(), comment=user_comment, commenter=users.get_current_user())
        comment.put()
        return Response(status=200)
Beispiel #31
0
    def manage_page(self, account_key):
        categories = Category.all()
        categories.ancestor(account_key)

        items = Item.all()

        template_values = {
            'categories': categories,
            'items': items,
            'logout_url': users.create_logout_url("/")
        }
        path = os.path.join(os.path.dirname(__file__), 'manage.html')
        self.response.out.write(template.render(path, template_values))
Beispiel #32
0
    def test_update_an_item(self):
        """ Update an Item """
        item = Item(wishlist_id=1,
                    product_id=1,
                    name="toothpaste",
                    description="toothpaste for 2")
        item.save()
        self.assertEqual(item.id, 1)

        item.description = "toothpaste for 1"
        item.save()

        items = Item.all()
        self.assertEqual(len(items), 1)
        self.assertEqual(items[0].description, "toothpaste for 1")
Beispiel #33
0
    def manage_page(self):
        currt_user = users.get_current_user()
        account_key = db.Key.from_path('Account', currt_user.nickname())
        categories = Category.all()
        categories.ancestor(account_key)

        items = Item.all()

        template_values = {
            'categories': categories,
            'items': items,
            'logout_url': users.create_logout_url("/")
        }
        path = os.path.join(os.path.dirname(__file__), 'manage.html')
        self.response.out.write(template.render(path, template_values))
Beispiel #34
0
def export_xml(key):
    category = Category.get(key)
    items = Item.all().ancestor(category)
    disposition_filename = category.title + "_" + category.owner.email() + ".xml"
    root = Element("CATEGORY")
    SubElement(root, "NAME").text = category.title
    for item in items:
        i = SubElement(root, "ITEM")
        SubElement(i, "NAME").text = item.title
    return Response(
        tostring(root),
        status=200,
        mimetype="application/xml",
        headers={"Content-Disposition": "attachment;filename=" + disposition_filename},
    )
Beispiel #35
0
    def do_vote(self, owner, category):
        voted_item_name = self.request.get("voted_item_name")
        item1_name = self.request.get("item1")
        item2_name = self.request.get("item2")

        account = self.request.get("account")
        account_key = db.Key.from_path("Account", account)

        account_items = Item.all()
        account_items = account_items.ancestor(account_key)

        item1 = ""
        item2 = ""

        for item in account_items.run():
            if item.item_name == item1_name:
                item1 = item
            if item.item_name == item2_name:
                item2 = item

        if voted_item_name == item1_name:
            item1.win = item1.win + 1
            item2.lose = item2.lose + 1
            self.response.out.write(
                """
                <html>
                    <h1>You voted for <i>%s</i> over <i>%s</i></h1>
                    <br><br>
                </html>
                """
                % (item1_name, item2_name)
            )

        elif voted_item_name == item2_name:
            item2.win = item2.win + 1
            item1.lose = item1.lose + 1
            self.response.out.write(
                """
                <html>
                    <h1>You voted for <i>%s</i> over <i>%s</i></h1>
                    <br><br>
                </html>
                """
                % (item2_name, item1_name)
            )

        item1.put()
        item2.put()
Beispiel #36
0
    def add_item(self, currt_user, new_item):
        cat_name = self.request.get("cat_name")
        cat_key = db.Key.from_path('Account', currt_user.nickname(), 'Category', cat_name)

        category = db.get(cat_key)

        items = Item.all()
        items.ancestor(cat_key)
        items.filter("item_name =", new_item)


        if items.count() == 0:
            item = Item(key_name=new_item, parent=category, item_name=new_item)
            item.win = 0
            item.lose = 0
            item.put()
Beispiel #37
0
    def test_update_an_item(self):
        """ Update an Item """
        item = Item(order_id=1,
                    product_id=1,
                    name="wrench",
                    quantity=1,
                    price=10.50)
        item.save()
        self.assertEqual(item.id, 1)

        item.price = 12.0
        item.save()

        items = Item.all()
        self.assertEqual(len(items), 1)
        self.assertEqual(items[0].price, 12.0)
Beispiel #38
0
    def edit(self, currt_user, account):
        cat_name = self.request.get("cat_name")
        category_key = db.Key.from_path('Account', currt_user.nickname(), 'Category', cat_name)
        category = db.get(category_key)
        
        items = Item.all()
        items.ancestor(category_key)

        template_values = {
            'account': account,
            'category': category,
            'items': items,
            'logout_url': users.create_logout_url("/")
        }

        path = os.path.join(os.path.dirname(__file__), 'edit.html')
        self.response.out.write(template.render(path, template_values))
Beispiel #39
0
    def export_XML(self, currt_user):
        cat_name = self.request.get("cat_name")
        cat_key = db.Key.from_path('Account', currt_user.nickname(), 'Category', cat_name)

        items = Item.all()
        items.ancestor(cat_key)

        self.response.headers['Content-Type'] = 'text/xml'
        #self.response.out.write('<?xml version="1.0"?>\n')
        self.response.out.write('<CATEGORY>\n')
        self.response.out.write('   <NAME>' + cat_name + '</NAME>\n')
        for item in items.run():
            self.response.out.write('   <ITEM>\n')
            self.response.out.write('       <NAME>' + item.item_name + '</NAME>\n')
            self.response.out.write('   </ITEM>\n')

        self.response.out.write('</CATEGORY>\n')
Beispiel #40
0
def edit_category(key):
    category = Category.get(key)
    expiration = ""
    if category.expiration:
        expiration = category.expiration.strftime("%m/%d/%Y")
    if category.owner != users.get_current_user():
        error = "You cannot edit a category that you do not own!"
        return render_template("errors.html", error=error)
    items = Item.all().ancestor(category)
    return render_template(
        "edit_category.html",
        items=items,
        count=items.count(),
        key=key,
        title=category.title,
        owner=category.owner.email(),
        expiration=expiration,
    )
Beispiel #41
0
def results(key,expired=None):
	my_votes = {}
	my_comments = {}
	user_comments = {}
	category = Category.get(key)
	items = Item.all().ancestor(category).order('-wins').order('losses')
	count = 0
	for i in items:
		item = UserVote.all().ancestor(i).order('-wins').order('losses').filter('voter =', users.get_current_user()).get()
		if not item:
			my_votes[count] = [i.title, "-", "-"]
		else:
			my_votes[count] = [i.title, item.wins, item.losses] # the count helps maintain the order -wins and losses
		count += 1

	for c in items:
		user_comments[c.title] = UserComment.all().ancestor(c)
		my_comment = UserComment.all().ancestor(c).filter('commenter =',users.get_current_user()).get()
		if my_comment:
			my_comments[c.title] = my_comment.comment
	return render_template('results.html',items=items, key=key, title=category.title, owner=category.owner.email(), my_votes=my_votes, my_comments=my_comments, user_comments=user_comments,expired=expired)
Beispiel #42
0
 def post(self):
     user = users.get_current_user()
     
     if user == None:
         self.redirect("/")
         return 
     
     # get category information
     category = self.request.get('category') 
     if category != "":
         cs = Category.all()
         cs.filter('user ='******'category =', category) # get category
         c = cs.get()
         if c != None:
             items = Item.all()
             items.ancestor(c.key())
             for item in items.run():
                 item.delete()
             c.delete()
     
     self.redirect("/category")
Beispiel #43
0
 def get(self):
     user = users.get_current_user()
     
     if user:
         login = True
         url = users.create_logout_url(self.request.uri)
     else:
         login = False
         url = users.create_login_url(self.request.uri)
         self.redirect("/")
         return
     
     # get category information
     category = self.request.get('category')
     cs = Category.all()
     cs.filter('user ='******'category =', category) # get category
     c = cs.get()
     if c != None: # this category
         items = Item.all()
         items.ancestor(c.key())
         isEmpty = items.get()
         
         template_values = {
                            'user': user,
                            'login': login, 
                            'url': url,
                            'isEmpty': isEmpty,
                            'category': category,
                            'items': items,
                            'error': self.request.get('error'),
                            'message': self.request.get('message')
         }
     
         path = os.path.join(os.path.dirname(__file__), 'templates/manage_category.html')
         self.response.out.write(template.render(path, template_values))
     else:       
         self.redirect("/category")
Beispiel #44
0
def list_items():
    """ Returns all of the Items """
    items = Item.all()

    results = [item.serialize() for item in items]
    return make_response(jsonify(results), status.HTTP_200_OK)
Beispiel #45
0
    def test_all(self):
        test_list = Item.all()
        test_class = self.item.__class__

        for item in test_list:
            self.assertIs(type(item), test_class)
Beispiel #46
0
    def post(self):  
        user = users.get_current_user()
        
        if user:
            login = True
            url = users.create_logout_url(self.request.uri)
        else:
            login = False
            url = users.create_login_url(self.request.uri)
            self.redirect("/")
            return 
        
        creator = self.request.get('creator')
        category = self.request.get('category') 
        cats = Category.all()
        cats.filter('user ='******'category =', category) # get category
        c = cats.get()
        
        if c == None:
            self.redirect("/")
            return
        
        # check winner
        winner = self.request.get('option')
        lastChoice1 = self.request.get('choice1')
        lastChoice2 = self.request.get('choice2')
        if winner == lastChoice1:
            loser = lastChoice2
        else:
            loser = lastChoice1
        
        items = Item.all()
        items.ancestor(c.key()) # get all the items of c
        itemList = []
        #w, l = None
        for item in items.run():
            itemList.append(item.item)
            
            # update winner and loser data
            if item.item == winner:
                item.win += 1
                item.rate = item.win * 100 / (item.win + item.lose)
                item.put()
                w = item
            if item.item == loser:
                item.lose += 1
                item.rate = item.win * 100 / (item.win + item.lose)
                item.put()
                l = item
                     
        if len(itemList) > 1:
            length = len(itemList)
            i = random.randint(0, length - 1)
            j = random.randint(0, length - 1)
            while i == j:
                j = random.randint(0, length - 1)

            choice1 = itemList[i]
            choice2 = itemList[j]
            error = None
        else:
            error = "Options not enough!"
        
        template_values = {
            'user': user,
            'login': login, 
            'url': url,
            'winner': w,
            'loser': l,
            'choice1': choice1, 
            'choice2': choice2,
            'creator': creator,
            'creatorName': c.username,
            'category': category,
            'error': error
        }
        
        path = os.path.join(os.path.dirname(__file__), 'templates/vote.html')
        self.response.out.write(template.render(path, template_values))
Beispiel #47
0
def admin_index(request):
    list = Item.all()

    return locals()
Beispiel #48
0
 def get(self):  
     user = users.get_current_user()
     
     if user:
         login = True
         url = users.create_logout_url(self.request.uri)
     else:
         login = False
         url = users.create_login_url(self.request.uri)
         self.redirect("/")
         return 
     
     creator = self.request.get('creator')
     category = self.request.get('category') 
     cats = Category.all()
     cats.filter('user ='******'category =', category) # get category
     c = cats.get()
     
     if c == None:
         self.redirect("/")
         return
     
     items = Item.all()
     items.ancestor(c.key()) # get all the items of c
     #items.filter("user ="******"category =", c.category)
     #items.order('-rate')
     
     orderList = {}
     tmpList = {}
     
     for item in items.run():
         tmpList[item.item] = {}
         tmpList[item.item]['win'] = item.win
         tmpList[item.item]['lose'] = item.lose
         tmpList[item.item]['rate'] = item.rate
         orderList[item.item] = item.rate
     
     itemList = []
     for item in sorted(orderList, key=orderList.get, reverse=True):
         r = Result()
         r.item = item
         r.win = tmpList[item]['win']
         r.lose = tmpList[item]['lose']
         r.rate = tmpList[item]['rate']
         
         itemList.append(r)
     
     template_values = {
         'user': user,
         'login': login, 
         'url': url,
         'items': itemList,
         'creator': creator,
         'creatorName': c.username,
         'category': category,
     }
     
     path = os.path.join(os.path.dirname(__file__), 'templates/result.html')
     self.response.out.write(template.render(path, template_values))
Beispiel #49
0
def options_to_comment(key):
	category = Category.get(key)
	items = Item.all().ancestor(category)
	return render_template('comment.html',items=items,key=key,title=category.title,owner=category.owner.email())	
Beispiel #50
0
def edit_image(key):
	category = Category.get(key)
	upload_url = blobstore.create_upload_url('/saveimage/'+key)
	items = Item.all().ancestor(category)
	return render_template('edit_images.html',items=items,key=key,title=category.title,owner=category.owner.email(),upload_url=upload_url)
Beispiel #51
0
async def get_items():
    return await ItemPydantic.from_queryset(Item.all())
Beispiel #52
0
def get_item(category,title):
	items = Item.all().filter('title =',title).ancestor(category)
	return items.get()
Beispiel #53
0
 def test_prop(self):
     self.load_user_and_item()
     item = Item.all().filter("place_name =",
                              self.item_data[ITEM_NAME]).get()
     assert item.prop('address') == self.item_data[ITEM_ADDRESS]