コード例 #1
0
ファイル: project.py プロジェクト: danjferg/The-Junk-Drawer
def newItem(category_name):
    # Verify authentication
    if 'username' not in login_session:
        return redirect(url_for('showLogin'))
    category = session.query(Category).filter_by(name=category_name).one()
    #Verify authorization
    if login_session['user_id'] != category.user_id:
        flash('Danger: You are not authorized to add items to this category. \
            Please create your own category in order to add items.')
        return redirect(url_for('showCategory', category_name=category_name))
    if request.method == 'POST':
        newItem = Item(name = request.form['name'], \
            description = request.form['description'], \
            category_id = category.id)
        # Make sure the item name isn't used
        oldItem = session.query(Item). \
            filter_by(category_id=category.id). \
            filter_by(name=newItem.name).first()
        if oldItem != None:
            flash('Danger: New item %s was not created. There is already \
                an item by that name.' % (newItem.name))
            return render_template('itemNew.html')
        # Create the new item
        session.add(newItem)
        session.flush()
        if request.files['image']:
            filename = uploadFile(newItem)
            newItem.picture = filename
        session.commit()
        flash('Success: Created New Item %s' % (newItem.name))
        return redirect(url_for('showCategory', category_name=category_name))
    else:
        return render_template('itemNew.html')
コード例 #2
0
ファイル: project.py プロジェクト: titolins/catalog_app
def newItem(category_id):
    category = getCategoryInfo(category_id)
    # create the WTForm
    form = NewItem(request.form)
    # The picture is mandatory, but we need to pass it separately to WTForm as
    # the constructor only receives the form itself..
    if request.files:
        form.picture.data = request.files['picture']
    if request.method == 'POST' and form.validate():
        # After validating the form, we build the item object with the
        # formatted title and with an empty string for the picture.
        # We need to do this because we will use the item id to save the
        # picture.
        new_item = Item(
            title=' '.join(
                name.capitalize() for name in form.title.data.split()
            ),
            description=form.description.data,
            picture='',
            category_id=category.id,
            user_id=login_session['user_id']
        )
        session.add(new_item)
        session.commit()
        # Now that we have the new item id, we save the picture and update the
        # item with the picture path
        path = saveItemPicture(form.picture.data, new_item.id)
        new_item.picture = path
        session.add(new_item)
        session.commit()
        flash("Added %s to %s!" % (new_item.title, category.title))
        return redirect(url_for('showCategory', category_id=category.id))
    else:
        return render_template(
            'newitem.html',
            category=category,
            form=form
        )
コード例 #3
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)
コード例 #4
0
def newItem():
    ''' Add a new item to the database. '''
    if request.method == 'POST':
        newItem = Item(name=request.form['name'],
                       description=request.form['description'],
                       category_id=request.form['category_id'],
                       user_id=login_session['user_id'])
        session.add(newItem)
        session.commit()

        # If picture was chosen, save to static folder and update item.
        if request.files['picture']:
            newItem.picture = savePicture(request.files['picture'], newItem.id)
            session.commit()
        flash("New item created!")
        return redirect(url_for('catalog'))

    else:
        user = getUserInfo(login_session['user_id'])
        categories = session.query(Category).all()
        return render_template('newItem.html',
                               user=user,
                               categories=categories)
コード例 #5
0
def newItem():
    ''' Add a new item to the database. '''
    if request.method == 'POST':
        newItem = Item(
            name=request.form['name'],
            description=request.form['description'],
            category_id=request.form['category_id'],
            user_id=login_session['user_id'])
        session.add(newItem)
        session.commit()

        # If picture was chosen, save to static folder and update item.
        if request.files['picture']:
            newItem.picture = savePicture(request.files['picture'], newItem.id)
            session.commit()
        flash("New item created!")
        return redirect(url_for('catalog'))

    else:
        user = getUserInfo(login_session['user_id'])
        categories = session.query(Category).all()
        return render_template(
            'newItem.html', user=user, categories=categories)
コード例 #6
0
def newItem():
    ''' Add a new item '''
    logger.debug("newItem called with method: " + request.method)
    if request.method == 'POST':
        logger.debug("POST: " + request.form['name'])
        if request.files['picture']:
            logger.debug("POST: has picture")

    if 'username' not in login_session:
        logger.debug("newItem redirect to login")
        return redirect('/login')

    if request.method == 'POST':
        item_name = ""
        item_desc = ""
        item_cat = DEFAULT_CAT
        item_price = ""

        logger.debug("POST: " + request.form['name'])

        if request.form['name']:
            item_name = request.form['name']
        
        if request.form['category']:
            item_cat = request.form['category']
            if item_cat == ALL_CATEGORIES:
                item_cat = DEFAULT_CAT

        if request.form['description']:
            item_desc = request.form['description']

        if request.form['price']:
            item_price = request.form['price']

        try:
            logger.debug("POST: querying categories")
            categories = db_session.query(Category).order_by(asc(Category.name))

            category = db_session.query(Category).filter_by(name=item_cat).one()
            newItem = Item(name=item_name, 
                           description=item_desc, 
                           price=item_price,
                           category_id=category.id, 
                           picture="", 
                           user_id=login_session['user_id'])
            db_session.add(newItem)
            db_session.commit()
            logger.debug("POST: about to savePicture")

            # If picture, save with unique name to static folder and update item.
            if request.files['picture']:
                newItem.picture = savePicture(request.files['picture'], 
                                              newItem.id)
                db_session.commit()

            flash('Successfully Created: %s' % (newItem.name))
            return redirect(url_for('showItem', 
                                    item_name=newItem.name, 
                                    category_name=newItem.category.name))
        except:
            logger.debug("POST: exception")
            flash('Invalid input, could not create new item. Please specify a unique name, and use a category.')
            db_session.rollback()
            return render_template('newItem.html', categories=categories)

    else:
        logger.debug("GET: querying categories")
        categories = db_session.query(Category).order_by(asc(Category.name))
        logger.debug("GET: returning")
        return render_template('newItem.html', categories=categories)
コード例 #7
0
ファイル: project.py プロジェクト: kjg531/UFS-P3
    description = request.form['description'].strip()

    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('create_item.html', categories=categories, nonce=createNonce())

        picture_data = picture.read()

    item = Item(name=name, description=description, category=category, creation_date=datetime.utcnow())
    if picture_data:
        item.picture = picture.filename
        item.picture_data = picture_data

    session.add(item)
    session.commit()
    flash("The item '%s' has been created." % name, "success")

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

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ['jpg', 'jpeg', 'png']

@app.route('/item/<int:item_id>/edit/', methods=['GET','POST'])
@login_required
def editItem(item_id):
コード例 #8
0
    if picture:
        if not allowed_file(picture.filename):
            flash("The picture must be a JPEG or PNG file.", "danger")
            return render_template('create_item.html',
                                   categories=categories,
                                   nonce=createNonce())

        picture_data = picture.read()

    item = Item(name=name,
                description=description,
                category=category,
                creation_date=datetime.utcnow())
    if picture_data:
        item.picture = picture.filename
        item.picture_data = picture_data

    session.add(item)
    session.commit()
    flash("The item '%s' has been created." % name, "success")

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


def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ['jpg', 'jpeg', 'png']


@app.route('/item/<int:item_id>/edit/', methods=['GET', 'POST'])
コード例 #9
0
def newItem(category_id=''):
    """ Create new item
    Args:
        category_id: (optional) the id of the category
    """

    categories = session.query(Category).all()

    if request.method == 'POST':

        nonce = request.form['nonce'].strip()

        # Check if nonce is set correct
        if not useNonce(nonce):
            flash("An error occurred. Please try again.", "danger")
            return render_template('forms/newItem.html',
                                   categories=categories,
                                   nonce=createNonce())

        # Check if a name is set
        if not request.form['item_name'].strip():
            flash("Please enter a name", "danger")
            return render_template('forms/newItem.html',
                                   categories=categories,
                                   nonce=createNonce())

        # Check if a category is selected
        if not request.form['item_category'].strip():
            flash("Please enter a name", "danger")
            return render_template('forms/newItem.html',
                                   categories=categories,
                                   nonce=createNonce())

        try:
            category = session.query(Category).filter_by(
                id=request.form['item_category'].strip()).one()
        except Exception, e:
            flash("Please choose a valid category.", "danger")
            return render_template('forms/newItem.html',
                                   categories=categories,
                                   nonce=createNonce())

        # check if an items with the same name already exists in this category
        existingItem = session.query(Item).filter_by(
            category_id=category.id,
            name=request.form['item_name'].strip()).first()
        if existingItem:
            flash(
                "An item with the same name already exists "
                "in this category. Please choose a different name", "danger")
            return render_template('forms/newItem.html',
                                   categories=categories,
                                   nonce=createNonce())

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

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

            picture_data = picture.read()

        newItem = Item(name=request.form['item_name'],
                       description=request.form['item_description'],
                       category_id=request.form['item_category'],
                       user_id=login_session['user_id'],
                       created_on=datetime.utcnow())

        if picture_data:
            newItem.picture = picture.filename
            newItem.picture_data = picture_data

        session.add(newItem)
        session.commit()
        flash('New Item %s successfully created' % newItem.name)
        session.commit()
        return redirect(url_for('home'))
コード例 #10
0
def newItem(category_id=''):
    """ Create new item
    Args:
        category_id: (optional) the id of the category
    """

    categories = session.query(Category).all()

    if request.method == 'POST':

        nonce = request.form['nonce'].strip()

        # Check if nonce is set correct
        if not useNonce(nonce):
            flash("An error occurred. Please try again.", "danger")
            return render_template('forms/newItem.html',
                                   categories=categories, nonce=createNonce())

        # Check if a name is set
        if not request.form['item_name'].strip():
            flash("Please enter a name", "danger")
            return render_template('forms/newItem.html',
                                   categories=categories, nonce=createNonce())

        # Check if a category is selected
        if not request.form['item_category'].strip():
            flash("Please enter a name", "danger")
            return render_template('forms/newItem.html',
                                   categories=categories, nonce=createNonce())

        try:
            category = session.query(Category).filter_by(
                id=request.form['item_category'].strip()).one()
        except Exception, e:
            flash("Please choose a valid category.", "danger")
            return render_template('forms/newItem.html',
                                   categories=categories, nonce=createNonce())

        # check if an items with the same name already exists in this category
        existingItem = session.query(Item).filter_by(
            category_id=category.id, name=request.form['item_name'].strip()).first()
        if existingItem:
            flash("An item with the same name already exists "
                  "in this category. Please choose a different name", "danger")
            return render_template('forms/newItem.html',
                                   categories=categories, nonce=createNonce())


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

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

            picture_data = picture.read()

        newItem = Item(name=request.form['item_name'],
                       description=request.form['item_description'],
                       category_id=request.form['item_category'],
                       user_id=login_session['user_id'],
                       created_on=datetime.utcnow())

        if picture_data:
            newItem.picture = picture.filename
            newItem.picture_data = picture_data


        session.add(newItem)
        session.commit()
        flash('New Item %s successfully created' % newItem.name)
        session.commit()
        return redirect(url_for('home'))
コード例 #11
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
        )