Esempio n. 1
0
def newItem():  # Add item base on category name.
    """ Renders a form for input of a new item - GET request. if I get a post -redirect to 'showItem' after creating new item.
    """
    # ADD LOGIN PERMISSION
    # Protect app modification from non-users
    # If a username is not detected for a given request.
    # Lets redirect to login page.

    if 'username' not in login_session:
        return redirect('/login')

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

    # Add SQLAlchemy statements
    if request.method == 'POST':
        # This is key to retreiving category from the form.
        try:
            category = (session.query(Category).filter_by(
                name=request.form.get('category')).one_or_none())
        except None:  # If a NoneType object is returned
            return PageNotFound

        newItem = Item(category=category,
                       title=request.form['title'],
                       description=request.form['description'],
                       price=request.form['price'],
                       user_id=login_session['user_id'])
        # access the file from the files dictionary
        # on request object:
        #file = request.files['file']

        # Process optional item image.
        image_file = request.files['file']
        if image_file and allowed_file(image_file.filename):
            filename = secure_filename(image_file.filename)
            if os.path.isdir(app.config['UPLOAD_FOLDER']) is False:
                os.mkdir(app.config['UPLOAD_FOLDER'])
            image_file.save(os.path.join(app.config['UPLOAD_FOLDER'],
                                         filename))
            newItem.image_filename = filename
        elif request.form['basic_url']:
            newItem.basic_url = request.form['basic_url']

        session.add(newItem)
        session.commit()
        flash('New Item %s successfully Created' % newItem.title)
        # Now define the url variable path to the newItem created.

        creator = getUserInfo(newItem.user_id)
        # Show response to my post request in the client.
        return redirect(
            url_for('showItem',
                    category_name=category_name,
                    category_id=category_id,
                    item_title=item_title,
                    item_id=item_id,
                    creator=creator))
    else:
        return render_template('newitem.html', categories=categories)
def createNewItem():
    """Allow users to create a new item in the catalog."""
    if 'username' not in login_session:
        return redirect('/login')

    session = dbconnect()

    if request.method == 'POST':
        if not request.form['name']:
            flash("New item not created: No name provided.")
            return redirect(url_for('showCatalogHome'))

        if request.form['name'] == "items":
            flash("Error: Can't have an item called 'items'.")
            return redirect(url_for('showCatalogHome'))

        # make sure item names are unique
        qry = session.query(Item).filter(Item.name == request.form['name'])
        already_exists = (session.query(literal(True)).filter(
            qry.exists()).scalar())
        if already_exists is True:
            flash("Error: There is already an item with the name '%s'" %
                  request.form['name'])
            session.close()
            return redirect(url_for('showCatalogHome'))

        category = (session.query(Category).filter_by(
            name=request.form['category']).one())
        add_new_item = Item(category=category,
                            name=request.form['name'],
                            description=request.form['description'],
                            quantity=request.form['quantity'],
                            price=request.form['price'],
                            user_id=login_session['user_id'])

        try:
            createimagefile = request.files['file']
        except Exception:
            createimagefile = None
        try:
            createimageurl = request.form['image_url']
        except Exception:
            createimageurl = None

        if createimagefile and allowedFile(createimagefile.filename):
            filename = secure_filename(createimagefile.filename)
            if os.path.isdir(app.config['UPLOAD_FOLDER']) is False:
                os.mkdir(app.config['UPLOAD_FOLDER'])
            createimagefile.save(
                os.path.join(app.config['UPLOAD_FOLDER'], filename))
            add_new_item.image_filename = filename

        elif createimageurl:
            add_new_item.image_url = request.form['image_url']

        session.add(add_new_item)
        session.commit()

        flash("New Item successfully created!")
        category_name = category.name
        item_name = add_new_item.name
        session.close()
        return redirect(
            url_for('showItem',
                    category_name=category_name,
                    item_name=item_name))
    else:
        categories = session.query(Category).all()

        # See, if any, which category page new item was click on.
        ref_category = None
        if request.referrer and 'catalog' in request.referrer:
            ref_url_elements = request.referrer.split('/')
            if len(ref_url_elements) > 5:
                ref_category = ref_url_elements[4]

        session.close()
        return render_template('create_new_item.html',
                               categories=categories,
                               ref_category=ref_category)