예제 #1
0
def update_item(item_id):
    """Handle request to update an item."""

    # validate ownership
    item = item_dao.get_item(item_id)
    if "user_id" not in login_session:
        return redirect(url_for("showLogin"))

    elif item.user_id != login_session["user_id"]:
        flash("Unauthorized operation")
        return redirect(url_for("view_items_html"))

    # update item
    item = Item()

    item.id = item_id
    item.name = request.form["name"]
    item.category_id = request.form["category_id"]

    if request.form["description"] != "":
        item.description = request.form["description"]

    item = item_dao.edit_item(item)

    return jsonify(item.serialize)
예제 #2
0
def createItem():
    if 'username' not in login_session:
        return redirect(url_for('showLogin'))
    if request.method == 'POST':
        category = session.query(Category).filter_by(
            name=request.form['item-category']).first()
        newItem = Item()
        newItem.name = request.form['item-name']
        newItem.description = request.form['description']
        newItem.category = category
        newItem.user_id = getUserID(login_session['email'])
        try:
            with store_context(fs_store):
                if request.files['item_photo']:
                    newItem.picture.from_file(request.files['item_photo'])
                else:
                    newItem.picture.from_file(urlopen(dummy_item_photo))
                session.add(newItem)
                session.commit()
        except Exception:
            session.rollback()
            raise
        return redirect(url_for('showCategories'))
    else:
        categories = session.query(Category).order_by(asc(Category.name))
        return render_template('create_item.html', categories=categories,
                               login_session=login_session)
예제 #3
0
def createItem():
    if 'username' not in login_session:
        return redirect(url_for('showLogin'))
    if request.method == 'POST':
        category = session.query(Category).filter_by(
            name=request.form['item-category']).first()
        newItem = Item()
        newItem.name = request.form['item-name']
        newItem.description = request.form['description']
        newItem.category = category
        newItem.user_id = getUserID(login_session['email'])
        try:
            with store_context(fs_store):
                if request.files['item_photo']:
                    newItem.picture.from_file(request.files['item_photo'])
                else:
                    newItem.picture.from_file(urlopen(dummy_item_photo))
                session.add(newItem)
                session.commit()
        except Exception:
            session.rollback()
            raise
        return redirect(url_for('showCategories'))
    else:
        categories = session.query(Category).order_by(asc(Category.name))
        return render_template('create_item.html',
                               categories=categories,
                               login_session=login_session)
예제 #4
0
def create_item():
    """Handle request to create a new item."""

    item = Item()
    item.name = request.form["name"]
    item.category_id = request.form["category_id"]
    item.user_id = login_session["user_id"]

    if request.form["description"] != "":
        item.description = request.form["description"]

    item = item_dao.create_item(item)

    return jsonify(item.serialize)
예제 #5
0
def newItem(category_name):
    category = session.query(Category).filter_by(name=category_name).one()
    if request.method == 'POST':
        item = Item(name=request.form['name'],
                    category_id=category.id,
                    user_id=login_session['user_id'])
        if request.form['description']:
            item.description = request.form['description']
        session.add(item)
        session.commit()
        flash('New %s Item Successfully Created' % (item.name))
        return redirect(url_for('showAllItems', category_name=category_name))
    else:
        return render_template('newItem.html', category_name=category_name)
예제 #6
0
def addItem():
	if request.method == 'POST':
		if request.form['name'] and request.form['description']:
			newItem = Item()
			newItem.name = request.form['name']
			newItem.description = request.form['description']
			newItem.category = session.query(Category).filter_by(id=request.form['category']).one()
			session.add(newItem)
			session.commit()
			flash('new item added!')
			return redirect(url_for('showItems', category_id=request.form['category']))
	else:
		isLoggedIn = 'username' in login_session
		categories = session.query(Category).all()
		return render_template('newItem.html', categories=categories, isLoggedIn=isLoggedIn)
예제 #7
0
def addItem(category_name):
    """Page to display for adding an item"""

    category = session.query(Category).filter_by(name=category_name).first()
    if request.method == 'POST':
        print request.form
        new_item = Item(category_id=category.id)
        new_item.description = request.form['description']
        new_item.name = firstThreeWords(new_item.description)
        new_item.author = request.form['author']
        new_item.user_id = login_session['user_id']

        session.add(new_item)
        session.commit()
        flash('"%s" item successfully added to "%s" category' %
              (new_item.name, category_name))
        return redirect(url_for('showCategory', category_name=category_name))
    else:
        return render_template('addItem.html', category_name=category_name)
예제 #8
0
def add_item():
    categories = session.query(Category).all()
    if request.method == 'POST':
        item = Item()
        if not request.form['title'] or not \
                request.form['description'] or \
                request.form['category_select'] == '0':
            return redirect('/catalog/item/new')
        else:
            item.name = request.form['title']
            item.description = request.form['description']
            item.category_id = request.form['category_select']
            item.user_id = login_session['username']
            session.add(item)
            session.commit()
            flash('Item {} added'.format(item.name))
        return redirect(url_for('show_catalog'))
    else:
        return render_template('add_item.html', categories=categories)
예제 #9
0
def addItem(category_name):
    """Page to display for adding an item"""

    category = session.query(Category).filter_by(name=category_name).first()
    if request.method == 'POST':
        print request.form
        new_item = Item(category_id=category.id)
        new_item.description = request.form['description']
        new_item.name = firstThreeWords(new_item.description)
        new_item.author = request.form['author']
        new_item.user_id = login_session['user_id']

        session.add(new_item)
        session.commit()
        flash('"%s" item successfully added to "%s" category' % (
                new_item.name, category_name))
        return redirect(url_for('showCategory', category_name=category_name))
    else:
        return render_template('addItem.html', category_name=category_name)
예제 #10
0
def addItem():
    """Displays the add item page."""

    if request.method == 'POST':
        # verify the user has logged in
        if 'username' not in login_session:
            return redirect(url_for('showLogin'))

        if request.form.get('add', None) == 'add':
            name = bleach.clean(request.form['name'], 
                                strip=True)

            # verify that cleaned name is not blank
            if not name:
                flash("Name field is required")
                categories = get_categories()
                return render_template('addItem.html',
                                       categories=categories)

            #build the new item
            item = Item()
            item.name = name
            item.description = bleach.clean(request.form['description'],
                                            strip=True)
            item.image_url = bleach.clean(request.form['imageUrl'],
                                          strip=True)
            item.category_id = bleach.clean(request.form['category'],
                                            strip=True)

            item.last_update = get_time()
            item.owner_id = login_session['user_id']
            session.add(item)
            session.commit()

            return redirect(url_for('showItem', item_id=item.id))
        else:
            return redirect(url_for('showIndex'))
    else:
        categories = get_categories()
        return render_template('addItem.html', categories=categories)
예제 #11
0
def newItem(category_id=''):
    if 'username' not in login_session:
        return redirect('/login')
    
    item = Item()
    item.category_id = category_id
    
    categories = session.query(Category).order_by(asc(Category.name))
   
    if request.method == 'POST':
        errors = []
        # check blank
        if request.form['name'] == "" or request.form['category_id'] == "" or request.form['description'] == "" or request.form['price'] == "":
            errors.append('Name, Category, Description, and Price are required.')
        # check duplicate
        if session.query(Item).filter(Item.name == request.form['name'], Item.category_id == request.form['category_id']).count()>0:
            errors.append('That item already exists in that category.')
        # too long - not pretty
        if len(request.form['name'])>36:
            errors.append('Please limit item name to 32 characters or less.')
 
        # set these values so we can show them what they tried to enter without passing as separate params
        item.name = request.form['name']
        item.category_id = request.form['category_id']
        item.description = request.form['description']
        item.price = request.form['price']
        item.picture = request.form['picture']
        item.user_id = login_session['user_id']
        
        if len(errors)>0:
            return render_template('newItem.html', category_id = category_id, categories = categories, item = item, errors = errors)
        else:
            session.add(item)
            session.commit()
            flash('Item %s has been added to the catalog.' % item.name)
            return redirect(url_for('showCategory', category_id = item.category.id))
    else:
        return render_template('newItem.html', category_id = category_id, categories = categories, item = item)
예제 #12
0
def addPage():
    """
    Return the Add Item page that allows signedin user to add items
    """
    if request.method == 'POST':
        if 'id' in login_session:
            newItem = Item()
            if request.form['category']:
                newItem.categoryId = session.query(Category)\
                    .filter(Category.name == request.form['category']).one().id
            if request.form['name']:
                newItem.name = request.form['name']
            if request.form['description']:
                newItem.description = request.form['description']
            newItem.userId = login_session['id']

            session.add(newItem)
            session.commit()

        flash("new item has been added")

        return redirect('/', code=302)
    else:
        return render_template('addItem.html')
예제 #13
0
def createItem():
    '''
    Create a new Catalog Item from the main catalog page
    and no category is selected
    '''
    # if user is not logged in, redirect to login page
    if 'username' not in login_session:
        return redirect('/login')

    # get all the categories from database to populate the newitem.html page
    categories = session.query(Category).all()

    # create an Item instance
    item = Item(user_id=login_session['user_id'])

    # if this is a POST request
    if request.method == 'POST':
        # if 'name' field is non-blank, assign it to the Item object
        if request.form['name']:
            item.name = request.form['name']

        # if 'description' field is non-blank, assign it to the Item object
        if request.form['description']:
            item.description = request.form['description']

        # get the selected category id from the list of options and
        # query the database for category name and user who created it
        if request.form.get('categories'):
            category_id = request.form.get('categories')
            category_name = session.query(Category).filter_by(
                id=category_id).one().name
            category_user = session.query(Category).filter_by(
                id=category_id).one().user_id

        # if user is not the creator of this category, redirect to catalog page
        if category_user != login_session['user_id']:
            flash(
                "You did not create category %s, hence, "
                "hence you are not authorized to add this item: '%s'"
                % (category_name, item.name))
            return redirect(url_for('showCatalog'))
        else:
            # assign the category id to item
            item.category_id = category_id

            # add and commit Item to database
            session.add(item)
            session.commit()

            # add flash message
            flash("Catalog Item '%s' Successfully Added" % item.name)

            # redirect function to show the item details just committed
            return redirect(url_for(
                'showItem',
                category_name=category_name,
                item_name=item.name,
                item_id=item.id))

    # if this is a GET request
    else:
        # redisplay the newitem.html page to create a new catalog item
        return render_template(
            'newitem.html',
            item=item,
            categories=categories,
            username=login_session['username']
            if 'username' in login_session else "")
예제 #14
0
engine = create_engine('sqlite:///catalog.db')
Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
session = DBSession()

user = User(name="omar", email="*****@*****.**")
session.add(user)
session.commit()

catalog = Catalog(name="pop")
session.add(catalog)
session.commit()

item = Item(user_id=1, name="lily", catalog=catalog)
item.description = "written by bla bla bla bla"
session.add(item)
session.commit()

item = Item(user_id=1, name="a", catalog=catalog)
item.description = "written by bla bla bla bla"
session.add(item)
session.commit()

item = Item(user_id=1, name="b", catalog=catalog)
item.description = "written by bla bla bla bla"
session.add(item)
session.commit()

item = Item(user_id=1, name="c", catalog=catalog)
item.description = "written by bla bla bla bla"
예제 #15
0
def addItemToCategory(category_name, category_id):
    '''
    Add an Item to a Category based on the selected category
    This function is called when a logged-in user already selected a category
    to display its items
    '''
    # if user is not logged in, redirect to login page
    if 'username' not in login_session:
        return redirect('/login')

    # get the category creator
    category = session.query(Category).filter_by(id=category_id).one()

    # if logged-in user is not the creator of this category,
    # redirect to catalog page
    if category.user_id != login_session['user_id']:
        flash(
            'You did not create this category,"\
            " hence you are not authorized to add an item to it')
        return redirect(url_for('showCatalog'))

    # create an Item instance
    item = Item(user_id=login_session['user_id'])

    # get all the categories from database
    categories = session.query(Category).all()

    # if this is a POST request
    if request.method == 'POST':

        # if the 'name' field is non-blank
        if request.form['name']:
            item.name = request.form['name']

        # if the 'description' field is non-blank
        if request.form['description']:
            item.description = request.form['description']

        # get the selected category from the list of options
        if request.form.get('categories'):
            # assign the category id to the Item object
            item.category_id = request.form.get('categories')

            # query the database for the creator of this category
            category_user = session.query(Category).filter_by(
                id=item.category_id).one().user_id

        # if user is not the creator of this category, redirect to catalog page
        if category_user != login_session['user_id']:
            flash(
                "You did not create this category, hence,"
                " you are not authorized to add this item: '%s'" % item.name)
            return redirect(url_for('showCatalog'))
        else:
            # add and commit Item to the database
            session.add(item)
            session.commit()

            # add a flash message
            flash("Catalog Item '%s' Successfully Added" % item.name)

            # redirect page to the Item details page
            return redirect(url_for(
                'showItem',
                category_name=category_name,
                item_name=item.name,
                item_id=item.id))

    # if this is a GET request
    else:
        # redisplay the New Item creation page
        return render_template(
            'newitem.html',
            item=item,
            categories=categories,
            category_id=category_id,
            username=login_session['username']
            if 'username' in login_session else "")
예제 #16
0
파일: app.py 프로젝트: ArpanSriv/ica
def displayCategoryContents(catalog_name):
    if request.method == 'POST':
        global user
        # Check if the current user is not the dummy user
        if user is not None and user.id != 999:
            newItem = Item(
                creationtime=datetime.now(),
                category=session
                .query(Category)
                .filter_by(name=catalog_name)
                .one(),
                user=user)
            if request.form['name']:
                newItem.name = request.form['name']
            else:
                flash("Cannot create an item without a name."
                      " Please try again.")
                return redirect(url_for('displayCategoryContents',
                                        catalog_name=catalog_name))

            if request.form['description']:
                newItem.description = request.form['description']
            else:
                newItem.description = "No description provided."

            if request.form['picuri']:
                newItem.picture = request.form['picuri']
            else:
                newItem.picture = url_for('static',
                                          filename='img/'
                                                   'athlete-'
                                                   'beach-'
                                                   'bodybuilder-305239.jpg')

            session.add(newItem)
            session.commit()
            flash("Item {} created.".format(newItem.name))
        else:
            flash(
                "<strong class='flash-message'>"
                "You are currently unauthorized to do this."
                " Please <a href='{}'>sign in</a> to continue."
                "</strong>"
                .format(url_for('showLogin')))
            flash(" If you already logged in,"
                  " try logging out, logging in again.")

        return redirect(
            url_for('displayCategoryContents',
                    catalog_name=catalog_name)
        )

    else:
        category = session.query(Category).filter_by(name=catalog_name).one()
        items = session.query(Item).filter_by(category=category).all()
        return render_template(
            'itemslist.html',
            items=items,
            catalog_name=catalog_name,
            user=user
        )
예제 #17
0
    picture = request.files['picture']
    picture_data = None

    if picture:
        if not allowed_file(picture.filename):
            flash("The picture must be a JPEG or PNG file.", "danger")
            return render_template('edit_item.html',
                                   categories=categories,
                                   item=item,
                                   nonce=createNonce())

        picture_data = picture.read()
        print "Content-Length: %s" % picture.content_length

    item.name = name
    item.description = description
    item.category = category

    if picture_data:
        item.picture = picture.filename
        item.picture_data = picture_data

    session.add(item)
    session.commit()
    flash("Your changes have been saved.", "success")

    return redirect(url_for('listItems', category_id=category.id))


@app.route('/item/<int:item_id>/delete/', methods=['GET', 'POST'])
@login_required
예제 #18
0
파일: project.py 프로젝트: kjg531/UFS-P3
        item.picture = None
        item.picture_data = None

    picture = request.files['picture']
    picture_data = None

    if picture:
        if not allowed_file(picture.filename):
            flash("The picture must be a JPEG or PNG file.", "danger")
            return render_template('edit_item.html', categories=categories, item=item, nonce=createNonce())

        picture_data = picture.read()
        print "Content-Length: %s" % picture.content_length

    item.name = name
    item.description = description
    item.category = category

    if picture_data:
        item.picture = picture.filename
        item.picture_data = picture_data

    session.add(item)
    session.commit()
    flash("Your changes have been saved.", "success")

    return redirect(url_for('listItems', category_id=category.id))

@app.route('/item/<int:item_id>/delete/', methods=['GET','POST'])
@login_required
def deleteItem(item_id):
예제 #19
0
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()

# Empty the tables
session.query(Category).delete()
session.query(Item).delete()

# Add categories
sample_categories = ['guitars', 'pianos', 'drums', 'accessories', 'books']

for category_name in sample_categories:
    category = Category()
    category.name = category_name
    session.add(category)
session.commit()

# First index is for the item
# Second index is for title,category_id respectively
items = [['cort g110 stratocaster', 1], ['Yamaha P155 Contemporary Piano', 2],
         ['Riot PODRT522BK 5-Piece Drum Set', 3], ['Guitar capo', 4],
         ['Fingerstyle & Slide guitar in open tunings', 5]]

for i in range(0, 4):
    itemm = Item()
    itemm.name = items[i][0]
    itemm.description = 'description'
    itemm.category_id = items[i][1]
    session.add(itemm)
session.commit()