Beispiel #1
0
def create_item():
    """Create item"""

    username = login_session.get('username', None)

    if request.method == 'GET':
        catalogs = session.query(Catalog).all()
        catalogs_display = [{
            'id': catalog.id,
            'name': catalog.name
        } for catalog in catalogs]
        return render_template('create_item.html',
                               catalogs_display=catalogs_display,
                               username=username)

    if request.method == 'POST':
        title = request.form['title']
        results = session.query(Item).filter_by(title=title).all()
        if len(results) > 0:
            return redirect(url_for('createItem'))

        user = session.query(User).filter_by(name=username).one()
        item = Item(title, request.form['desc'])
        item.catalog_id = request.form['catalog_id']
        item.user_id = user.id
        session.add(item)
        session.commit()
        return redirect(url_for('home'))
Beispiel #2
0
def load_items():
    """Load sample items into database."""

    item_1 = Item(user_id=1,
                  name="Blue Shirt",
                  image="/static/blue.jpg",
                  quantity=1,
                  size="S")
    item_2 = Item(user_id=2,
                  name="Red Shirt",
                  image="/static/red.jpg",
                  quantity=1,
                  size="M")
    item_3 = Item(user_id=1,
                  name="Yellow Shirt",
                  image="/static/yellow.jpg",
                  quantity=1,
                  size="L")
    item_4 = Item(user_id=2,
                  name="Pink Shirt",
                  image="/static/pink.jpg",
                  quantity=1,
                  size="XL")

    db.session.add(item_1)
    db.session.add(item_2)
    db.session.add(item_3)
    db.session.add(item_4)

    db.session.commit()
Beispiel #3
0
def newItem():
	"""This page will be for adding a new item."""
	error=None
	login_already=current_user.is_authenticated()
	#   This function will return to homepage if it found user is not login. 
	#  	There are same setting in pages below which are able to edit the database. 
	if login_already:
		if request.method == "POST":
			error = vacant_input()
			if not error:
				"""go on input database if no empty imput. If there any, 
				   reload and labels of the empty form will turn red."""
				time_now=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
				""" Get currunt time and insert to create_time. 
				 	This will use for index items display order"""
				i = Item(create_time=time_now, 
						 name=request.form['name'], 
						 discription=request.form['discription'], 
						 category=request.form['category'])
				session.add(i)
				session.flush()
				i.photo=upload_image(i.id)
				session.commit()
				return redirect("/")
			c = session.query(Category).all()
			return render_template("add.html", c=c, login_already=login_already, error=error)
		c = session.query(Category).all()
		return render_template("add.html", c=c, login_already=login_already, error=error)
	else:
		return redirect("/")
Beispiel #4
0
    def get(self, ranking_uid):
        ranking = Ranking.get_or_none(id=ranking_uid)
        if ranking is None:
            return {'message': f'Ranking `{uid}` not found.'}, 404
        if ranking.user.id != current_user.id:
            return {'message': f'Ranking belongs to another user.'}, 409

        model = ranking.get_pairwise_model()
        comp = model.next_comparison()
        item1 = Item.get_or_none(id=UUID(comp[0]))
        if item1 is None:
            return {'message': f'Item `{comp[0]}` not found'}, 404
        item2 = Item.get_or_none(id=UUID(comp[1]))
        if item2 is None:
            return {'message': f'Item `{comp[1]}` not found'}, 404

        items = []
        items.append({
            'id': item1.id,
            'label': item1.label,
            'img_url': item1.img_url
        })
        items.append({
            'id': item2.id,
            'label': item2.label,
            'img_url': item2.img_url
        })
        return jsonify(comparison=items)
Beispiel #5
0
def item_add(category_id=1):
    if request.method == 'POST':

        new_item = Item(name=request.form['name'],
                        price=request.form['price'],
                        description=request.form['description'],
                        category_id=request.form['category-id'],
                        user_id=login_session['user_id'])

        picture = request.files['profile-pic']

        if picture and allowed_file(picture.filename):
            filename = secure_filename(picture.filename)
            extension = os.path.splitext(filename)[1]
            unique_filename = str(uuid.uuid4()) + str(extension)
            picture.save(
                os.path.join(app.config['UPLOAD_FOLDER'], unique_filename))
            new_item.picture = unique_filename

        session.add(new_item)
        session.commit()

        return redirect(
            url_for('item_view', category_id=request.form['category-id']))

    else:
        categories = session.query(Category).all()
        return render_template('add_item.html',
                               categories=categories,
                               category_id=category_id)
    def get(self):

        cover_url = None
        # if IDENTIFIER_ITEM_PHOTO in req_json:
        #     cover_url = req_json[IDENTIFIER_ITEM_PHOTO]

        item_id = uuid.uuid4()
        # req_json = json.loads(self.request.body)

        # item_name = req_json[IDENTIFIER_ITEM_NAME]
        item_name = self.request.get(IDENTIFIER_ITEM_NAME)

        # expense_name = req_json[IDENTIFIER_EXPENSE_NAME]
        expense_name = self.request.get(IDENTIFIER_EXPENSE_NAME)

        # buyer_email = req_json[IDENTIFIER_BUYER_EMAIL]
        buyer_email = self.request.get(IDENTIFIER_BUYER_EMAIL)

        # sharer_email_lst = req_json[IDENTIFIER_SHARER_LIST]
        sharer_emails = self.request.get(IDENTIFIER_SHARER_LIST)
        sharer_email_lst = sharer_emails.split(",")

        expense_lst = Expense.query(Expense.expense_name == expense_name)
        expense_id = None

        # total_cost = float(req_json[IDENTIFIER_TOTAL_COST])
        cost = self.request.get(IDENTIFIER_TOTAL_COST)
        total_cost = float(cost)


        target_expense = None


        for expense in expense_lst:
            if buyer_email in expense.user_email_lst:
                expense_id = expense.expense_id
                target_expense = expense
                break

        if expense_id == None:
            response = {}
            response['error'] = 'the buyer email: ' + buyer_email + ' is not valid for this expense/apartment'
            return self.respond(**response)

        new_item = Item(item_id = str(item_id),
                        item_name = item_name,
                        cover_url = cover_url,
                        expense_id = expense_id,
                        buyer_email = buyer_email,
                        sharer_email_lst = sharer_email_lst,
                        total_cost = total_cost
                        )
        new_item.put()
        target_expense.item_id_lst.insert(0, str(item_id))
        target_expense.put()


        self.respond(item_id_id = str(item_id), status="Success")
Beispiel #7
0
    def get(self):

        cover_url = None
        # if IDENTIFIER_ITEM_PHOTO in req_json:
        #     cover_url = req_json[IDENTIFIER_ITEM_PHOTO]

        item_id = uuid.uuid4()
        # req_json = json.loads(self.request.body)

        # item_name = req_json[IDENTIFIER_ITEM_NAME]
        item_name = self.request.get(IDENTIFIER_ITEM_NAME)

        # expense_name = req_json[IDENTIFIER_EXPENSE_NAME]
        expense_name = self.request.get(IDENTIFIER_EXPENSE_NAME)

        # buyer_email = req_json[IDENTIFIER_BUYER_EMAIL]
        buyer_email = self.request.get(IDENTIFIER_BUYER_EMAIL)

        # sharer_email_lst = req_json[IDENTIFIER_SHARER_LIST]
        sharer_emails = self.request.get(IDENTIFIER_SHARER_LIST)
        sharer_email_lst = sharer_emails.split(",")

        expense_lst = Expense.query(Expense.expense_name == expense_name)
        expense_id = None

        # total_cost = float(req_json[IDENTIFIER_TOTAL_COST])
        cost = self.request.get(IDENTIFIER_TOTAL_COST)
        total_cost = float(cost)

        target_expense = None

        for expense in expense_lst:
            if buyer_email in expense.user_email_lst:
                expense_id = expense.expense_id
                target_expense = expense
                break

        if expense_id == None:
            response = {}
            response[
                'error'] = 'the buyer email: ' + buyer_email + ' is not valid for this expense/apartment'
            return self.respond(**response)

        new_item = Item(item_id=str(item_id),
                        item_name=item_name,
                        cover_url=cover_url,
                        expense_id=expense_id,
                        buyer_email=buyer_email,
                        sharer_email_lst=sharer_email_lst,
                        total_cost=total_cost)
        new_item.put()
        target_expense.item_id_lst.insert(0, str(item_id))
        target_expense.put()

        self.respond(item_id_id=str(item_id), status="Success")
Beispiel #8
0
    def get(self):
        print("get finish task request")

        task_id = self.request.get(IDENTIFIER_TASK_ID)
        total_cost = self.request.get(IDENTIFIER_TOTAL_COST)
        user_email = self.request.get(IDENTIFIER_USER_EMAIL)

        total_cost = float(total_cost)
        print("get cost " + str(total_cost))

        tasks = Task.query(Task.task_id == task_id).fetch()
        task = tasks[0]

        print("Found the task " + task.task_name)

        if task.finished:
            response = {}
            response['error'] = 'the task has already been finished'
            return self.respond(**response)
        if user_email != task.charger_email:
            response = {}
            response['error'] = 'the task has been assigned to other roommate'
            return self.respond(**response)
        task.finished = True
        task.put()
        item_id = str(uuid.uuid4())
        sharer_lst = task.candidate_lst
        # sharer_lst.remove(task.charger_email)   # newly removed this line

        print("creating item ")

        new_Item = Item(item_id=item_id,
                        cover_url=str(task.photo_blobkey),
                        expense_id=task.expense_id,
                        total_cost=total_cost,
                        buyer_email=task.charger_email,
                        sharer_email_lst=sharer_lst,
                        item_name=task.task_name)
        new_Item.put()

        expenses = Expense.query(Expense.expense_id == task.expense_id).fetch()
        if len(expenses) == 0:
            print("cannot find the expense")
        else:
            expense = expenses[0]
            item_ids = expense.item_id_lst
            item_ids.append(item_id)
            expense.item_id_lst = item_ids
            expense.put()
            print("done ")

        self.respond(item_name=task.task_name,
                     item_id=task.task_id,
                     status="Success")
Beispiel #9
0
def testing(paper_id, index='1'):
    index_index = get_page_index(index)
    num = Item.select().where(Item.paper == paper_id)
    if not num:
        error = '暂无题目'
        return render_template("error.html", error=error)
    p = Page(len(num), index_index, 1)
    items = Item.select().where((Item.paper == paper_id)
                                & (Item.index == index))
    item = items[0]
    return render_template("items.html", item=item, page=p)
Beispiel #10
0
def insert_item():
	user = db_session.query(User).get(g.user_id)#get user
	name_string = str(request.form["name"]) #take in new item name as a string
	descr_string = str(request.form["description"]) #take in new item description as a string 
	cat_id= int(request.form["category"]) #take in cat id as integer
	new_name = Item(
		name=name_string, description=descr_string,
		cat_id=cat_id) #creates new item object from user's input
	new_name.user = user #attach item object to user object
	
	db_session.commit()
	return redirect(url_for('manage_items'))
Beispiel #11
0
 def __init__(self, max_item_size: Optional[int]) -> None:
     self.max_item_size = self.DEFAULT_MAX_ITEM_SIZE if max_item_size is None else max_item_size
     self._data: Dict[int, Item] = {
         1: Item(
             id=1,
             name="Bag",
         ),
         2: Item(
             id=2,
             name="Shoes",
         ),
     }
     self.next_id = 3
    def get(self):
        print("get finish task request")

        task_id = self.request.get(IDENTIFIER_TASK_ID)
        total_cost = self.request.get(IDENTIFIER_TOTAL_COST)
        user_email = self.request.get(IDENTIFIER_USER_EMAIL)

        total_cost = float(total_cost)
        print("get cost " + str(total_cost))

        tasks = Task.query(Task.task_id == task_id).fetch()
        task = tasks[0]

        print("Found the task " + task.task_name)

        if task.finished:
            response = {}
            response['error'] = 'the task has already been finished'
            return self.respond(**response)
        if user_email != task.charger_email:
            response = {}
            response['error'] = 'the task has been assigned to other roommate'
            return self.respond(**response)
        task.finished = True
        task.put()
        item_id = str(uuid.uuid4())
        sharer_lst = task.candidate_lst
        # sharer_lst.remove(task.charger_email)   # newly removed this line

        print("creating item ")

        new_Item = Item(item_id = item_id, cover_url = str(task.photo_blobkey), expense_id = task.expense_id,
                        total_cost = total_cost,
                        buyer_email = task.charger_email,
                        sharer_email_lst = sharer_lst,
                        item_name = task.task_name)
        new_Item.put()

        expenses = Expense.query(Expense.expense_id == task.expense_id).fetch()
        if len(expenses) == 0:
            print("cannot find the expense");
        else:
            expense = expenses[0]
            item_ids = expense.item_id_lst
            item_ids.append(item_id)
            expense.item_id_lst = item_ids
            expense.put()
            print("done ")

        self.respond(item_name = task.task_name, item_id = task.task_id, status="Success")
Beispiel #13
0
 def writeToDB(title, link, description, date):
     newEntry = Item(title=title,
                     link=link,
                     description=description,
                     published_date=date)
     DBSession.add(newEntry)
     DBSession.commit()
Beispiel #14
0
 def generate_items(self):
     """Generation of random location of items (sirynge, needle, tube)
     each time the game is opened"""
     number_of_items = 3
     # Image list
     png = [
         "./images/needle.png", "./images/syringe.png", "./images/tube.png"
     ]
     # Generate x location list
     x_location = random.sample(range(self.dsp.max_sprite), number_of_items)
     # Generate y location list
     y_location = random.sample(range(self.dsp.max_sprite), number_of_items)
     # Loop for create item instance from class Item
     for i in range(number_of_items):
         # While position in lab list is not a wall
         while self.labyrinth.lab[y_location[i]][x_location[i]]\
                 == '1':
             # Change value x_location element list in position i
             x_location[i] = random.randint(self.dsp.min_sprite,
                                            self.dsp.max_sprite)
             # Change value y_location element list in position i
             y_location[i] = random.randint(self.dsp.min_sprite,
                                            self.dsp.max_sprite)
         # Creation of item in items list (Controller's attribute)
         self.items.append(Item(y_location[i], x_location[i], png[i]))
Beispiel #15
0
def add_items():
    try:
        category = request.json.get('category')
        item_name = request.json.get('name')
        short_desc = request.json.get('shortdesc')
        long_desc = request.json.get('longdesc')
        picture_name = request.json.get('pictureName')
        user_id = request.json.get("username")

        # check whether inputs are blank
        if not picture_name or picture_name is None:
            picture_name = NO_IMAGE
        print picture_name
        # check whether category is present in the database
        category_row = session.query(Category).filter_by(name=category).first()
        if category_row is None:
            return jsonify(message="Category doesn't exists", code="7867")

        # insert new item
        new_item = Item(category_item_fkey=category_row.id,
                        title=item_name,
                        description=short_desc,
                        long_description=long_desc,
                        item_photo=picture_name,
                        item_user_fkey=user_id)
        session.add(new_item)
        session.commit()

        return jsonify(message="New item created successfully", code="0000")

    except:
        return jsonify(message="Some unexpected error occurred", code="7864")
Beispiel #16
0
def add():
    """ Add book form view """
    form = forms.BookForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            # store actual image in filesystem (not in db !)
            img_filename = images.save(request.files['image'])
            img_url = images.url(img_filename)

            new_book = Item(title=form.title.data,
                            author=form.author.data,
                            genre_id=form.genre.data.id,
                            description=form.description.data,
                            img_url=img_url,
                            owner=current_user.get_id(),
                            img_filename=img_filename)
            db.session.add(new_book)
            db.session.commit()
            return redirect(url_for('show_collection'))
        else:

            return render_template('add_form.html', form=form)

    elif request.method == 'GET':
        return render_template('add_form.html', form=form)
def add_item():

    body = request.json
    item_type = body['item_type']
    material = body['material']
    description = body['description']
    storage_location = body['storage_location']
    quantity = body['quantity']
    price_each = body['price_each']
    budget_source = body['budget_source']
    note = body['note']

    try:
        item = Item(item_type=item_type,
                    material=material,
                    description=description,
                    storage_location=storage_location,
                    quantity=quantity,
                    price_each=price_each,
                    budget_source=budget_source,
                    note=note)

        db.session.add(item)
        db.session.commit()
        return "add item. item id={}".format(item.item_id), 200

    except Exception as e:
        return (str(e)), 400
Beispiel #18
0
 def post(self):
     category_name = request.args.get("category_name").upper()
     item = request.args.get("title").lower()
     if not item:
         abort(404, message="please enter name for item")
     if not category_name:
         abort(404, message="please enter category for item")
     if not request.form.get("ranking"):
         abort(404, message="please a rank for item")
     if request.form.get("description"):
         if len(request.form.get("description")) < 10:
             abort(404, message="please provide more description for item")
     titles = Item.query.filter_by(title=item)
     current_category = Category.query.filter_by(id=category_name).first()
     for title in titles:
         if category_name == current_category.name and title.title == item:
             abort(404, message="{} already exist in {}".format(item, category_name))
     category_row = Category.query.filter_by(name=category_name).first()
     item = Item(title = request.args.get("title").lower(), description = request.args.get("description"), category_name =category_row.name,category_id=category_row.id, rank=request.args.get("ranking"))
     db.session.add(item)
     db.session.commit()
     reorder_priorities(int(category_row.id))
     log = Logs(title=item.title,category=item.category_name, action="added")
     db.session.add(log)
     db.session.commit()
     return jsonify({'Success':"{} added successfully to {}".format(item.title, item.category_name)})
Beispiel #19
0
def items():
    error = None
    if request.method == 'POST':
        error = None
        if not request.form['name']:
            error = 'You have to enter a item name'
        elif not request.form['rfidNum']:
            error = 'You have to enter the RFID number'
        else:
            db.session.add(
                Item(name=request.form['name'],
                     tagID=request.form['rfidNum'],
                     userID=session['user_id'],
                     status=0))
            db.session.commit()
            items = Item.query.filter_by(
                userID=session['user_id'],
                name=request.form['name'],
                tagID=request.form['rfidNum']).first()

            db.session.add(
                Pattern(userID=session['user_id'],
                        itemID=items.id,
                        dayOfWeek='Monday',
                        startTime=','.join(defaultPatternTime),
                        presentItems=','.join(defaultPatternPresent)))
            db.session.add(
                Pattern(userID=session['user_id'],
                        itemID=items.id,
                        dayOfWeek='Tuesday',
                        startTime=','.join(defaultPatternTime),
                        presentItems=','.join(defaultPatternPresent)))
            db.session.add(
                Pattern(userID=session['user_id'],
                        itemID=items.id,
                        dayOfWeek='Wednesday',
                        startTime=','.join(defaultPatternTime),
                        presentItems=','.join(defaultPatternPresent)))
            db.session.add(
                Pattern(userID=session['user_id'],
                        itemID=items.id,
                        dayOfWeek='Thursday',
                        startTime=','.join(defaultPatternTime),
                        presentItems=','.join(defaultPatternPresent)))
            db.session.add(
                Pattern(userID=session['user_id'],
                        itemID=items.id,
                        dayOfWeek='Friday',
                        startTime=','.join(defaultPatternTime),
                        presentItems=','.join(defaultPatternPresent)))

            db.session.commit()
            items2 = Pattern.query.filter_by(userID=session['user_id'],
                                             itemID=items.id).all()

            for item in items2:
                print(item.startTime)
            flash('You were successfully added an item')
    items = Item.query.filter_by(userID=session['user_id']).all()
    return render_template("items.html", user=g.user, error=error, items=items)
Beispiel #20
0
def test():
    from model import Item
    session = model.Session()
    session.add(Item(name='alexey'))
    session.commit()

    print(session.query(Item).filter_by(name='alexey').all())
Beispiel #21
0
def criar_item(categoria_id):
    if 'username' not in login_session:
        return redirect('/login')

    categoria = session.query(Categoria).filter_by(id=categoria_id).one()
    if request.method == 'POST':
        creator_id = get_user_id(login_session['email'])
        item = Item(
            nome=request.form["nome"],
            descricao=request.form["descricao"],
            categoria_id=categoria.id,
            usuario_id=creator_id
        )
        session.add(item)
        session.commit()
        flash("Item criado com sucesso!")
        return redirect(
            url_for(
                'detalhar_categoria', categoria_id=categoria.id
            )
        )
    else:
        print("entrei no get")
        return render_template(
            'criar-item.html', categoria_id=categoria.id
        )
Beispiel #22
0
def addItem():
    session = Session()
    if 'username' not in login_session or login_session['username'] is None:
        return redirect(url_for('latestItems'))
    elif request.method == 'POST':
        formName = request.form['name']
        existingItem = session.query(Item).filter_by(name=formName).count()
        if existingItem > 0:
            return redirect(url_for('latestItems'))
        else:
            formDescription = request.form['description']
            formCategoryName = request.form['category']
            formCategory = session.query(Category).filter_by(
                name=formCategoryName).one()
            formUsername = login_session['username']
            formUser = session.query(User).filter_by(
                username=formUsername).one()
            item = Item(name=formName,
                        description=formDescription,
                        category=formCategory,
                        user=formUser)
            session.add(item)
            session.commit()
            return redirect(
                url_for('selectedCategory', category=formCategoryName))
    else:
        categories = session.query(Category).all()
        return render_template('addItem.html', categories=categories)
Beispiel #23
0
def get_items(paper_id):
    if not paper_id:
        raise APIValueError('item', 'not fond')
    items = Item.select().where(Item.paper == paper_id).order_by(
        Item.index).dicts()
    response = {'items': items}
    return jsonify(response)
Beispiel #24
0
 def addItem(self, itemId, itemProperties, valuations):
     propertyName2value = {}
     for keyAndValue in itemProperties.split("&"):
         propertyName2value[keyAndValue.split(":")[0]] = int(
             keyAndValue.split(":")[1])
     newItem = i.Item(itemId, propertyName2value.keys())
     ItemsManager._items.append(newItem)
     ItemsManager._itemId2realProperties[itemId] = propertyName2value
Beispiel #25
0
def create_item(user_id, item_name, item_description, image_url, category_name, status_code):
    """Create and return a new item to seed data and for item upload page"""

    item = Item(user_id=user_id, item_name=item_name, item_description=item_description, image_url=image_url, category_name=category_name, status_code=status_code)

    db.session.add(item)
    db.session.commit()

    return item
Beispiel #26
0
def get_item(paper_id):
    papers = Paper.select().where(Paper.id == paper_id).dicts()
    paper = list(papers)[0]
    paper['state'] = ''
    items = Item.select().where(Item.paper == paper_id).order_by(
        Item.index).dicts()
    state = TestState(paper=paper)
    response = {'state': state.dicts(), 'items': list(items)}
    return jsonify(response)
Beispiel #27
0
def add_item(description, description_key):
    """Adds item description to database"""

    description = description.replace("=C3=A9", "e").replace("=", "")

    item = Item(description=description, description_key=description_key)

    db.session.add(
        item)  # added items commited to db after each order (see add_order)
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.model = Model(None, Item())
        self.model.insertColumns(0, ['m3u line', 'File path'])
        self.ui.tableView.setModel(self.model)
        self.ui.tableView.setItemDelegate(Delegate())
Beispiel #29
0
 def save_item(self, item):
     '''写数据库'''
     session = Session()
     try:
         session.add(Item(**item))
         session.commit()
     except Exception as e:
         logger.warning('页面 {} 的数据写入数据库出错,错误原因{}'.format(item['link'], e))
         session.rollback()
     session.close()
Beispiel #30
0
def create_item(wishlist_id, item_name, item_link):

    item = Item(wishlist_id=wishlist_id,
                item_name=item_name,
                item_link=item_link)

    db.session.add(item)
    db.session.commit()

    return item
    def put(self, name):
        data = ItemResource.parser.parse_args()

        item = Item.find_by_name(name)
        if item is None:
            item = Item(name, data['price'], data['store_id'])
        else:
            item.price = data['price']
            item.store_id = data['store_id']

        item.persist()
        return item.json(), 201
Beispiel #32
0
    def get(self):
        user_id = get_jwt_identity()
        items = Item.find_all()
        if user_id:
            return {'items': [item.json() for item in items]}, 200

        return {
            'items': [item.name for item in items],
            'message': 'More data available if you log in.'
        }, 200
Beispiel #33
0
def addItem():
    """Create a new Item."""

    if 'email' not in login_session:
        flash("You need to login to add items!")
        return redirect(url_for('getCatalog'))
    if request.method == 'POST':
        # set created user to current user
        user = session.query(User).filter_by(
            email=login_session['email']).one()
        name = request.form['name']
        if name is not None and len(name) != 0:
            new_item = Item(name=request.form['name'])
            new_item.created_user = user
            category = request.form['category']
            if category is not None and len(category) != 0:
                new_item.category_name = category
            description = request.form['description']
            if description is not None and len(description) != 0:
                new_item.description = description
            session.add(new_item)
            session.commit()
            flash("New Book Added!")
            return redirect(
                url_for('getItem',
                        category_name=new_item.category_name,
                        item_name=new_item.name))
        else:
            flash("Book name cannot be empty!")
            # if name is empty, load the page again

    categories = session.query(Category).order_by("name")
    user_loggedin = 'email' in login_session
    if user_loggedin:
        user_name = login_session['username']
        picture = login_session['picture']
        return render_template('additem.html',
                               categories=categories,
                               user_loggedin=user_loggedin,
                               user_name=user_name,
                               picture=picture)
    return render_template('additem.html', categories=categories)
    def delete(self, name):
        item = Item.find_by_name(name)
        if item is None:
            return {'message': 'item does not exist'}, 400

        try:
            item.delete()
        except Exception:
            return {'message': 'error occurred while deleting item'}, 500
        else:
            return {'message': 'item deleted'}
        def get(self):
            item_id = self.request.get(IDENTIFIER_ITEM_ID)
            print "111111111111111121111"
            print item_id
            items = Item.query(Item.item_id == item_id).fetch()
            item = items[0]

            cur_item = {}
            cur_item['item_cost'] = item.total_cost
            cur_item['is_paid'] = item.is_paid
            cur_item['item_id'] = str(item.item_id)
            cur_item['cover_url'] = item.cover_url
            cur_item['buyer'] = item.getBuyer()
            cur_item['sharer_lst'] = item.getSharersNickName()
            cur_item['item_name'] = item.item_name

            self.respond(item = cur_item, status = 'Success')
import model
from model import Basket, Item, Promotion, Redemption
import random
import time
import json

item_titles = ["bread", "chicken", "keys", "pen", "burger", "book", "speaker",
        "CD", "DVD", "cup", "thumbdrive", "caviar", "joghurt", "magazine"]
items = []


def gtins():
    return random.randint(0, 100)+1000


def ts():
    return random.getrandbits(64)


def price():
    return random.randint(1, 10000)


for title in item_titles:
    tmp = Item(title, gtins(), price())
    items.append(tmp)

tmp = Basket(ts(), items)
print tmp.toJSON()
Beispiel #37
0
def new():
    if request.method == "POST":
        Item.create(name=request.form['name'],description=request.form['description'])
        return redirect(url_for('index'))
    else:
        return render_template('new.html')