Exemplo n.º 1
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)
Exemplo n.º 2
0
def new_item():
    """Creates a new item if it is a POST request and loads the form to
    create one if it is a GET request."""
    if request.method == 'POST':
        if get_user() is None:
            return redirect(url_for('login'))

        item_title = None
        item_description = None
        item_category_id = None

        try:
            csrf_token = request.form['csrf_token']
            if csrf_token != login_session['csrf_token']:
                return redirect(
                    "https://www.youtube.com/watch?v=dQw4w9WgXcQ", code=301)

            user_id = get_user_id(login_session['email'])

            item_title = request.form['title']
            item_description = request.form['description']
            item_category_id = request.form['category']
            filename = None

            try:
                """Try to access the uploaded file and see if it has a valid
                extension."""
                file = request.files['file']
                ext = file.filename.split('.')[-1]
                if valid_ext.__contains__(ext):
                    filename = ''.join(random.choice(string.uppercase +
                                                     string.digits) for x in
                                       xrange(12))
                    filename = filename + file.filename
                    storage_path = os.path.dirname(os.path.realpath(__file__))
                    storage_path = os.path.join(storage_path, 'static/images')
                    file.save(os.path.join(storage_path, filename))

            except:
                pass

            new_item = Item(title=item_title, description=item_description,
                            category_id=item_category_id, user_id=user_id)

            """There was a filename associated that was valid with a valid
            extention, so need to save the file loaction in the image_url."""
            if filename is not None:
                new_item.image_url = filename

            session.add(new_item)
            session.commit()
            flash("Create new item %s!" % new_item.title, 'success')
            return redirect(
                url_for('index'))

        except:
            session.rollback()

            flash(u'Inavlid parameters. Please try again.', 'warning')
            categories = session.query(Category).all()
            return render_template('new_item.html', item_title=item_title,
                                   item_description=item_description,
                                   item_category_id=item_category_id,
                                   categories=categories, user=get_user())

    if request.method == 'GET':
        """Send all the categories as options for the item."""
        if get_user() is None:
            return redirect(url_for('login'))

        categories = session.query(Category).all()
        categories_count = (session.query(func.count(Category.id))).scalar()
        if categories_count == 0:
            flash(u'There are no categories yet. Please create one first',
                  'warning')
            return redirect(url_for('new_category'))

        csrf_token = ''.join(random.choice(string.uppercase + string.digits)
                             for x in xrange(32))
        login_session['csrf_token'] = csrf_token
        return render_template('new_item.html', categories=categories,
                               csrf_token=csrf_token, user=get_user())
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)