示例#1
0
def newItem(category_id):
    ''' This allows the user to create a new item from the category page'''
    # First we check to see if the user is actaully logged in
    # if 'username' not in login_session:
    #     return redirect('/login')
    print 'open'
    form = newItemForm()

    cat = session.query(Category).filter_by(id=category_id).one()

    if form.validate_on_submit():
        newItem = Item(name=request.form['name'],
                       description=request.form['description'],
                       picture=request.form['picture'])
        session.add(newItem)
        newItem.user_id = login_session['user_id']
        newItem.category_id = category_id
        session.add(newItem)

        flash('Item has been created!')
        return redirect(url_for('itemList', category_id=cat.id))

    if form_errors(form) == False:
        return redirect(url_for('itemList', category_id=cat.id))

    # if form.errors:
    #     for error in form.errors:
    #         flash(error)
    #     flash('There was an error in your input')
    #     return redirect(url_for('itemList', category_id=cat.id))

    return render_template('newItem.html', category_id=category_id, form=form)
示例#2
0
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')
示例#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 addItem():
    """
    Take user to add item screen, POST method does not work if all required
     fields are not filled out.
    Post request adds new item to the database
    User redirected to home if not logged in.
    """

    if 'username' not in login_session:
        return catalog()
    if request.method == 'POST' and request.form['name'] and \
            request.form['description'] and request.form['catagory']:
        catagory = session.query(Catagory).filter_by(
            name=request.form['catagory']).one()
        newItem = Item(title=request.form['name'],
                       description=request.form['description'],
                       catagory=catagory)
        if request.form['image']:
            newItem.image = request.form['image']
        session.add(newItem)
        session.commit()
        return redirect(url_for('getItems', catagory_id=catagory.id))
    else:
        catagories = session.query(Catagory).all()
        return render_template('new.html', catagories=catagories)
示例#5
0
def item_create(cid = None):
  if request.method == 'POST':
    print 'To process item creation.'
    item = Item()
    item.category_id = request.form['item-category_id']
    item.name = request.form['item-name']
    item.longtext = request.form["item-longtext"]
    file = request.files["item-image"]
    print type(file)
    item.image = file.read()
    item.user_id = get_user_id_from_session()
    result = item.add()
    if result[1] == 'error':
      flash(result[2], result[1])
    else:
      item.commit()
      return redirect(url_for('item.item_display', item_id = item.id))
  else:
    if cid == None:
      flash('Please select a category.', 'error')
      return redirect_common(url_for('category.home'))

  return render_template('item.html', title = 'Create item',\
                         item = Item(category_id = cid),\
                         display = False
                        )
  
示例#6
0
def newItem():
    if 'username' not in login_session:
        return redirect('/login')
    Categories = session.query(Category).order_by(asc(Category.name)).all()
    if request.method == 'POST':
        category = session.query(Category).filter_by(
            name=request.form['category_name']
        ).one()
        if not request.form['title']:
            flash('Title can not be empty for new item', category='Danger')
            return render_template('newitem.html', categories=Categories)
        if category:
            item = Item(
                    title=request.form['title'],
                    description=request.form['description'],
                    category_id=category.id,
                    user_id=login_session['user_id']
            )
            photo = request.files['photo']
            bin_data = photo.read()
            item.photo = bin_data
            try:
                session.add(item)
                session.commit()
                flash(
                    'New Menu %s Item Successfully Created'
                    % (item.title),
                    category='Success'
                )
                return redirect(
                    url_for(
                        'showCategory',
                        category_name=item.category.name
                    )
                )
            except IntegrityError:
                flash(
                    'An item with same title exists.'
                    'Item titles must be unique.',
                    category='Danger'
                )
                session.rollback()
                return render_template('newitem.html', categories=Categories)
        else:
            flash('Category not selected for new item', category='Danger')
            return render_template('newitem.html', categories=Categories)
    else:
        return render_template('newitem.html', categories=Categories)
示例#7
0
def home(cid = None, item_id = None):

  #Check input: Category ID
  if cid == None:
    category_id = Category.get_root().id
  else:
    category_id = cid
  
  #Get one that is specified
  categories = [] + [Category.get_by_id(category_id)]
  
  #Get children
  if len(categories) == 1:
    children = Category.get_children(category_id, count_items = True)
    if len(children) == 0: #If no children, then get parent of it
      parent_id = categories[0].parent
      categories = [] + [Category.get_by_id(parent_id)]
      #get children of the parent
      children = Category.get_children(parent_id, count_items = True)
    
    if len(children) > 0:
      categories += children
  
    categories[0].parent_flag = True
  
  #Assign selected_flag
  for c in categories:
    if c.id == int(category_id):
      c.selected_flag = True
    else:
      c.selected_flag = False
  
  #Get item or items
  item = None
  items = []
  if item_id == None:
    items = Item.get_by_category(category_id)
  else:
    item = Item.get_by_id(item_id)
    if isinstance(item, Item) and item.category_id != category_id:
      item = None
  
  return render_template('home.html', title = 'Catalog Excercise',\
                         categories = categories,\
                         items = items,\
                         item = item
                        )
  
示例#8
0
def item_json(cid = None, item_id = None):
  if item_id == None and cid == None:
    abort(404)
  if item_id != None:
    item = Item.get_by_id(item_id)
    if item == None:
      return abort(404)
    else:
      json_response = json.jsonify(Item=item.serialize)
  elif cid != None:
    items = Item.get_by_category(cid)
    if items == []:
      abort(404)
    else:
      json_response = json.jsonify(Items = [i.serialize for i in items])
  
  return json_response
示例#9
0
def add_item():
    name = None
    description = None
    category_id = '0'
    if request.method == 'POST':
        category_id = request.form['category_id']
        name = request.form['name'].strip()
        description = request.form['description']
        # validate name is not empty
        if name:
            item = Item(name=name, description=description,
                        category_id=category_id, user_id=session['user_id'])
            db.add(item)
            db.commit()
            f = request.files['photo']
            # validate file is with allowed extension and
            # get back the extension
            extension = get_extension(f)
            if extension:
                # photo named after item id to avoid overwriting
                # use timestamp in name to avoid caching headache after update
                filename = secure_filename(
                    str(item.id) + datetime.datetime.now().isoformat() +
                    '.' + extension)
                f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
                item.photo = filename
                db.add(item)
                db.commit()
            flash("New item %s Successfully Added" % item.name)
            return redirect(url_for('show_item',
                                    category_id=category_id, item_id=item.id))
        flash("Name cannot be empty!")
    categories = db.query(Category).all()
    if category_id == '0' and request.args.get('category_id'):
        category_id = request.args.get('category_id')
    item = {'name': name,
            'description': description,
            'category_id': int(category_id)}
    # if reload the page when validation for name is failed
    # so it needs to refill previous entered data when reload
    # for that, it use item variable
    return render_template('add_item.html', categories=categories,
                           item=item, logged_in=True)
示例#10
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)
示例#11
0
def recentItemsAtom():
    """
    ####Returns####
        + Recent Items:  Atom feed of recent books
    """
    return Item.getRecentItemsAtom(
        session,
        'Recent Items',
        request.url,
        request.url_root).get_response()
示例#12
0
def newItem():
    '''
    Create a new item.

    :return: Template to add a new item to any category.
    '''
    if 'username' not in login_session:
        return redirect('/login')
    # Fetch all the categories
    categories = session.query(Category).all()
    if request.method == 'POST':
        newItem = Item(name=request.form['name'], description=request.form['description'],
                       category_id=request.form['category'], image=request.form['image'],
                       user_id=login_session['user_id'])
        newItem.image = getImageUrl(newItem)
        session.add(newItem)
        session.commit()
        flash('New Menu %s Item Successfully Created' % (newItem.name))
        return redirect(url_for('showCatalog'))
    return render_template('newItem.html', categories=categories)
def addItem(category_id):
    if 'username' not in login_session:
        return redirect('/login')
    category = session.query(Category).filter_by(id=category_id).one()
    if request.method == 'POST':
        
        newItem = Item(name=request.form['item-name'], 
                       category_id=category.id,
                       description=request.form['description'],
                       creation_date=request.form['creation-date'],
                       image_url=request.form['item-image'],
                       user_id=category.user_id)
        print(request.form.get('in-use'))
        if request.form.get('in-use') is None:
            newItem.in_use = False
        else:
            newItem.in_use = True

        session.add(newItem)
        session.commit()
        return(redirect(url_for("viewCategory", category_id=category_id)))
    return(render_template("additem.html", category_id=category_id))
示例#14
0
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
        )
示例#15
0
def ItemAdd():
    """
    Add Item - any user can add an item as long as they are logged in
    """
    if "username" not in login_session:
        loggedIn = False
        return redirect("/login")
    else:
        loggedIn = True

    categories = session.query(Category).all()
    if request.method == "POST":
        itemToAdd = Item()
        itemToAdd.item_name = request.form["item_name"]
        itemToAdd.item_description = request.form["item_description"]
        itemToAdd.category_id = request.form["category"]
        itemToAdd.user_id = login_session["user_id"]
        session.add(itemToAdd)
        session.commit()
        flash("Item Added")
        return redirect(url_for("HomePage"))
    else:
        return render_template("item_add.html", categories=categories, loggedIn=loggedIn)
示例#16
0
def NewItem():
    if logged_in():
        if request.method == 'POST' and request.form["name"]!= "":
            category_name = request.form['category']
            category = session.query(Category).filter_by(name=category_name).one()
            existing_name = session.query(Item).filter_by(category_id=category.id, name=request.form["name"]).first()
            if not existing_name:
                item = Item(category_id=category.id, name=request.form["name"], description=request.form["description"])
                session.add(item)
                session.commit()
                image = request.files["image"]
                if image and allowed_file(image.filename):
                    filename = secure_filename(image.filename)
                    image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
                    item.image = filename
                    session.add(item)
                    session.commit()
                return redirect(url_for('ShowCategory', category_name=category_name))
        else:
            categories = session.query(Category).all()

            return render_template("items/new.html", categories=categories)
    return redirect(url_for('login'))
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)
def newItem():
    if 'username' not in login_session:
        return redirect('/login')
    if request.method == 'POST':
        
        item = Item(name = request.form['name'],
                    user_id = login_session['user_id'],
                    description = request.form['description'],
                    category_id = request.form['category_id'])
          
        session.add(item)
        try:
            session.commit()
        except sqlalchemy.exc.IntegrityError, exc:
            reason = exc.message
            if reason.endswith('is not unique'):
                print "%s already exists" % exc.params[0]
            session.rollback()
            flash('Item Already Exist %s' % item.name, 'danger')
            return redirect(url_for('newItem'))
        
        # Get item id for storing an item image at folder uploads/img/<item.id>
        item = session.query(Item).filter_by(name = request.form['name']).one()
        
        # Get file from request and store it in appropriate directory
        file = request.files['file']
        if file and allowed_file(file.filename):
            ext = os.path.splitext(file.filename)[1]
            image_path = _genImgPath(ext, item.id)
            file.save(image_path)
            item.image_path = image_path
            session.add(item)
            session.commit()
        
        flash('Item Successfully Created %s' % item.name, 'success')
        return redirect(url_for('showItem', item_name = item.name,
                                category_name = item.category.name))
示例#19
0
def itemXML(category_id, item_id):
    """
    ####Args####
        + category_id:  the id of the category of the book
        + item_id:  the id of the book

    ####Returns####
        + book:  XML object of the book
    """
    root = ET.Element('book')
    return app.response_class(
        ET.tostring(
            Item.getItemXML(session, item_id, root),
            encoding='us-ascii',
            method='xml'),
        mimetype='application/xml')
示例#20
0
def item_edit(item_id = None):
  item = Item.get_by_id(item_id)
  
  if request.method == 'POST':
    item.name = request.form['item-name']
    item.longtext = request.form["item-longtext"]
    file = request.files["item-image"]
    print type(file)
    item.image = file.read() #stream.getvalue()

    #file.save(os.path.join(current_app.root_path, file.filename))
    
    item.update()
    item.commit()
    return redirect(url_for('item.item_display', item_id = item_id))
  
  return render_template('item.html', title = 'Edit item',\
                         item = item,\
                         display = False
                        )
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)
示例#22
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)
示例#23
0
                       connect_args={'check_same_thread': False})

# Bind engine to a session
Session = sessionmaker(bind=engine)

# Create session object.
session = Session()

user = User(
    name='Miaan Kramer',
    email='*****@*****.**',
)

session.add(user)
session.commit()

category = Category(name='Gaming', user=user)

session.add(category)
session.commit()

item = Item(
    name='Headphones',
    description='The Razer Kraken Chroma is a top of the range headhone',
    category=category,
    user=user)

session.add(item)
session.commit()

print('Database Populated')
示例#24
0
def item_display(item_id = None):
  return render_template('item.html', title = 'Display item',\
                         item = Item.get_by_id(item_id),\
                         display = True
                        )
示例#25
0
db_session.add(category1)
db_session.add(category2)
db_session.add(category3)
db_session.add(category4)
db_session.add(category5)
db_session.add(category6)
db_session.add(category7)
db_session.add(category8)
db_session.add(category9)
db_session.commit()

item1 = Item(name="Batman: Arkham City (2011)",
             description="Batman: Arkham City is a 2011 action-adventure "
             "video game developed by Rocksteady Studios and released by "
             "Warner Bros. Interactive Entertainment for the PlayStation 3 "
             "and Xbox 360 video game consoles, and Microsoft Windows.",
             created_at=datetime.datetime.now(),
             updated_at=datetime.datetime.now(),
             category=category1,
             user=user1)

item2 = Item(name="Dead Island (2011)",
             description="Dead Island is a 2011 open world survival horror "
             "action role-playing video game developed by Polish developer "
             "Techland and published by German studio Deep Silver[5] for "
             "Microsoft Windows, Linux, OS X, PlayStation 3, and Xbox 360.",
             created_at=datetime.datetime.now(),
             updated_at=datetime.datetime.now(),
             category=category1,
             user=user1)
session.add(categorySchool)
session.commit()
session.add(categoryElectronics)
session.commit()
session.add(categoryDogs)
session.commit()
session.add(categoryFoods)
session.commit()
session.add(categoryHalloween)
session.commit()


# Items for School

item = Item(name="Pencil", description="wooden tool for writing",category=categorySchool)
session.add(item)
session.commit()

item = Item(name="Eraser", description="used to remove lead from paper", category=categorySchool)
session.add(item)
session.commit()

item = Item(name="Paper", description="used to write on", category=categorySchool)
session.add(item)
session.commit()

item = Item(name="Books", description="used to read", category=categorySchool)
session.add(item)
session.commit()
示例#27
0
# Create a dummy user to initialize the database

user1 = User(name="Dummy User", email="*****@*****.**")
session.add(user1)
session.commit()

# Read all the categories from a txt file, and create categories in the
# database

with open("category.txt") as fp:
    for line in fp:
        if (len(line) > 0):
            newCategory = Category(name=line.strip())
            session.add(newCategory)
            session.commit()

# Read all the items from a txt file, and create items in the database

items = []
with open("item.txt") as fp:
    for line in fp:
        item = line.split("|")
        if (len(item) == 5):
            newItem = Item(name=item[0].strip(),
                           description=item[1].strip(),
                           image=item[2].strip(),
                           category_id=item[3].strip(),
                           user_id=item[4].strip())
            session.add(newItem)
            session.commit()
                      'name': 'Frisbee',
                      'description': 'Description of Frisbee'
                  }]
              ],
              [
                  'baseball',
                  [{
                      'name': 'Bat',
                      'description': 'Description of Bat'
                  }]
              ]]

current_user = User(name="System User", email="*****@*****.**")
session.add(current_user)
session.commit()

for category in categories:
    current_category = Category(name=category[0], user=current_user)
    session.add(current_category)
    session.commit()

    for item in category[1]:
        current_item = Item(name=item['name'],
                            description=item['description'],
                            category=current_category,
                            user=current_user)
        session.add(current_item)
        session.commit()

print("Database seeding complete!")
示例#29
0
super_user = User(name="Super User", email="super_user")
session.add(super_user)
session.commit()

# Items for Books Category
category1 = Category(name="Books", user_id=1)

session.add(category1)
session.commit()

item1 = Item(
    name="Audiobooks",
    description="An audiobook (or talking book) is a" +
    " recording of a text being read. A reading of the complete text is noted"
    +
    "as 'unabridged', while readings of a reduced version, or abridgement of the"
    + "text are labeled as 'abridged'.",
    category=category1,
    user_id=1)

session.add(item1)
session.commit()

item2 = Item(
    name="Children Literature",
    description="Children's literature or juvenile" +
    "literature includes stories, books, magazines, and poems that are enjoyed by children. "
    +
    "Modern children's literature is classified in two different ways: genre or the intended age of the reader.",
    category=category1,
示例#30
0
# session.rollback()
session = DBSession()
# Add my info
User1 = User(name="John Bitner", email="*****@*****.**")
session.add(User1)
session.commit()

# Add Category 1 for the item catalog project
category1 = Category(user_id=1, name="Mr Noodles")

session.add(category1)
session.commit()

# Add Item 1 under Catalog 1 for the item catalog project
itemc1i1 = Item(user_id=1,
                name="Beef Pho",
                description="Classic Pho with beef.",
                category=category1)

session.add(itemc1i1)
session.commit()

# Add Item 2 under Catalog 1 for the item catalog project
itemc1i2 = Item(user_id=1,
                name="Vegan Pho",
                description="Classic Pho with plant based ingredients.",
                category=category1)

session.add(itemc1i2)
session.commit()

itemc1i3 = Item(user_id=1,
示例#31
0
def new_item(state=None):
    error = None
    name = None
    description = None
    category_id = request.args.get('category_id', '')
    subcategory_id = request.args.get('subcategory_id', '')
    catalog = list_category()
    subcategories = []
    if request.method == 'POST':
        category = None
        subcategory = None
        name = request.form.get('name', '').strip()
        description = request.form.get('description', '').strip()
        category_id = request.form.get('category', '').strip()
        subcategory_id = request.form.get('subcategory', '').strip()
        image_file = request.files.get('image', '')
        if not name:
            error = 'item name is missing'
        elif not category_id:
            error = 'category is missing'
        else:
            category = get_category(category_id)
            if not category:
                error = 'category is not found'
            else:
                if subcategory_id:
                    subcategory = get_subcategory(subcategory_id)
                    if not subcategory:
                        error = 'subcategory is not found'
        if error is None:
            item = Item(name=name,
                        description=description,
                        added=datetime.now(),
                        updated=datetime.now(),
                        category_id=category.id)
            if subcategory:
                item.subcategory_id = subcategory.id
            db_session.add(item)
            db_session.commit()
            if image_file and allowed_file(image_file.filename):
                filename = "{0}-{1}".format(item.id, secure_filename(image_file.filename))
                image_file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
                image = ItemImage(item_id=item.id, filename=filename)
                db_session.add(image)
                db_session.commit()
            flash('New item %s successfully created' % name)
            return redirect(url_for('show_item', category_id=item.category.id, category_name=item.category.name,
                                    item_id=item.id, item_name=item.name))
    if category_id:
        category = get_category(category_id)
        if category:
            subcategories = list_subcategory(category)
    return render_template('item_new_edit.html',
                           error=error,
                           user=login_session.get('user'),
                           name=name,
                           description=description,
                           category_id=category_id,
                           subcategories=subcategories,
                           subcategory_id=subcategory_id,
                           catalog=catalog,
                           item_image=None,
                           state=state,
                           edit_or_add="Add")
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'))
示例#33
0
    picture=
    'https://pbs.twimg.com/profile_images/2671170543/18debd694829ed78203a5a36dd364160_400x400.png'
)
session.add(User1)
session.commit()

#Items form Category Soccer
category = Category(user_id=1, name="Soccer")
session.add(category)
session.commit()

item = Item(
    user_id=1,
    category=category,
    title="Two shinguards",
    description=
    '''The shin guard was inspired by the concept of a greave. A greave is a piece of armor
                          used to protect the shin. It is a Middle English term, derived from an Old French word,
                          greve (pronounced gri\'v), meaning shin or shin armor.[1] The etymology of this word not
                          only describes the use and purpose of shin guards, but also contributes to dating the
                          technology.''')
session.add(item)
session.commit()

item = Item(
    user_id=1,
    category=category,
    title="Jersey",
    description=
    '''A jersey is an item of knitted clothing, traditionally in wool or cotton, with sleeves,
             worn as a pullover, as it does not open at the front, unlike a cardigan. It is usually close-fitting
             and machine knitted in contrast to a guernsey that is more often hand knit with a thicker yarn.
示例#34
0
session.commit()

# Add category values in table = category

categoryArray = ['Full Stack Web Developer','Data Analyst','Android Developer','Front End Web Developer','Machine Learning','IOS Developer','Big Data Analyst','Business Analyst','Drools Developer','Enterprise Architect']

for category in categoryArray:
    category = Category(user_id=1, name=category)
    session.add(category)
    session.commit()


# Add items for each category
    
# items for category_id 1
item1 = Item(user_id=1, name="Python", description="Python is a programming language", category_id=1)
item2 = Item(user_id=1, name="Html", description="Hyper text mark up language", category_id=1)
item3 = Item(user_id=1, name="Css", description="Cascaded Style Sheet", category_id=1)

session.add(item1)
session.add(item2)
session.add(item3)

session.commit()

# items for category_id 2

item1 = Item(user_id=1, name="Statistics", description="Statistics", category_id=2)
item2 = Item(user_id=1, name="Python", description="Python is a programming language", category_id=2)
item3 = Item(user_id=1, name="R", description="R is a programming language and free software environment for statistical computing and graphics", category_id=2)
示例#35
0
User1 = User(name='public', email='*****@*****.**')
session.add(User1)

User2 = User(name='private', email='*****@*****.**')
session.add(User2)
session.commit()

# item for privary coin
catalog1 = Catalog(catalogName="smart contract")

session.add(catalog1)
session.commit()

item1 = Item(user_id=1, itemName="Ethereum", description="""Ethereum is an open-source, public,\
            blockchain-based distributed computing platform and operating \
            system featuring smart contract (scripting) functionality. \
            It supports a modified version of Nakamoto consensus \
            via transaction-based state transitions.""", catalog=catalog1)

session.add(item1)
session.commit()

item2 = Item(user_id=1, itemName="NEO", description="""NEO (formerly Antshares) was founded \
    in 2014 by Da HongFei and Erik Zhang. NEO is an open-source, \
    community driven platform for decentralized applications. \
    Along with the rebranding from Antshares in 2017, \
    the vision to realise a “smart economy” was established. \
    It is to utilize blockchain technology and digital identity to \
    digitize assets, smart contracts are employed to automate \
    the management of these digital assets.\
""", catalog=catalog1)
示例#36
0
session = DBSession()

User1 = User(username="******",
             email="*****@*****.**",
             password="******")
session.add(User1)
session.commit()

category1 = Category(user_id=1, name='Vegetables')
session.add(category1)
session.commit()

item1 = Item(
    name='Cabbage',
    size='74cm2mm',
    description=
    'Very hard to make smaller just by peeling.  The center doesn\'t taste so good.',
    category_id=1,
    user_id=1)
session.add(item1)
session.commit()

item2 = Item(
    name='Daikon Radish',
    size='76cm9mm',
    description=
    'It\'s very white.  You shouldn\'t tell a lady she has legs this color.',
    category_id=1,
    user_id=1)
session.add(item2)
session.commit()
示例#37
0
DBSession = sessionmaker(bind=engine)

session = DBSession()

user = User(name="Bob", email="bob@mail")
session.add(user)
session.commit()

country = Category(
    name="Spain", description="Spain, a country on Europe’s Iberian Peninsula")
session.add(country)
session.commit()

city = Item(name="Barcelona",
            description="City Barcelona",
            category=country,
            user=user)
session.add(city)
session.commit()

city = Item(name="Bilbao",
            description="City Bilbao",
            category=country,
            user=user)
session.add(city)
session.commit()

city = Item(name="Malaga",
            description="City Malaga",
            category=country,
            user=user)
示例#38
0
category7 = Category(name="Foosball")
session.add(category7)
session.commit()

category8 = Category(name="Skating")
session.add(category8)
session.commit()

category9 = Category(name="Hockey")
session.add(category9)
session.commit()

item1 = Item(user_id=1,
             name="Stick",
             description="Interdum odio dignissim in nisi metus\
             , a elit sit dis cubilia, fringilla praesent pulvinar porta.\
             Sodales hac bibendum tincidunt risus mus himenaeos erat ac, \
             mollis semper integer tempor lacus turpis libero, ridiculus \
             primis curae aliquet nec rhoncus ante.",
             category=category9)
session.add(item1)
session.commit()

item2 = Item(user_id=1,
             name="Goggles",
             description="Primis dignissim mattis erat bibendum eu arcu quis\
              cursus",
             category=category5)
session.add(item2)
session.commit()

item3 = Item(user_id=1,
def newItem(category_name):
    """
    Allow logged users to create an item
    """
    # check user logged in
    if not user_allowed_to_browse():
        flash("You need to login!")
        flash("danger")
        return redirect('login')

    if request.method == 'POST':
        new_item_name = request.form['name'].strip().lower()
        new_item_description = request.form['description'].strip()
        if new_item_name and new_item_description:
            # if not blank, save to database
            try:
                # if same item in that category, re-render with error
                item(name=new_item_name, category_name=category_name)
                errors = {
                    'name': 'another item has same name, and same category'
                }
                params = {
                    'name': new_item_name,
                    'description': new_item_description
                }
                return render_template('items/new.html',
                                       category_name=category_name,
                                       errors=errors,
                                       params=params)
            except:
                new_item = Item(name=new_item_name,
                                description=new_item_description,
                                category=category(category_name),
                                user=getUserInfo(login_session['user_id']))
                session.add(new_item)
                session.commit()
                flash("Item is successfully created.")
                flash('success')
                return redirect(
                    url_for('showItem',
                            category_name=category_name,
                            item_name=new_item_name))
        else:
            errors = {}
            # store user-entered data to show them in re-rendered form
            params = {'name': '', 'description': ''}
            if new_item_name:
                params['name'] = new_item_name
            else:
                errors['name'] = "can't be blank"

            if new_item_description:
                params['description'] = new_item_description
            else:
                errors['description'] = "can't be blank"

            return render_template('items/new.html',
                                   category_name=category_name,
                                   errors=errors,
                                   params=params)
    else:
        # Show a form to create new item
        return render_template('items/new.html',
                               category_name=category_name,
                               params={
                                   'name': '',
                                   'description': ''
                               })
示例#40
0
    name="Ben Ho",
    email="*****@*****.**",
    picture=
    'https://pbs.twimg.com/profile_images/2671170543/18debd694829ed78203a5a36dd364160_400x400.png'
)
session.add(User1)
session.commit()

# Create new category
category1 = Category(user_id=1, name="Soccer")

session.add(category1)
session.commit()

item1 = Item(user_id=1,
             category=category1,
             name="Jersey",
             description="Awesome jersey!")

session.add(item1)
session.commit()

item1 = Item(user_id=1,
             category=category1,
             name="Pads",
             description="Very comfortable pads")

session.add(item1)
session.commit()

item1 = Item(user_id=1,
             category=category1,
for entry in users:
    user = User(username=entry['username'], email=entry['email'],
                picture=entry['picture'])
    session.add(user)

# Commit users changes to database
session.commit()

# Load Category data
for entry in categories:
    category = Category(name=entry['name'], user_id=entry['user_id'],
                        picture=entry['picture'])
    session.add(category)

# Commit categories changes to database
session.commit()

# Load Item data
for entry in items:
    item = Item(name=entry['name'], picture=entry['picture'],
                description=entry['description'],
                price=entry['price'],
                category_id=entry['category_id'],
                user_id=entry['user_id'])
    session.add(item)

# Commit categories changes to database
session.commit()

print 'Finished populating database...'
示例#42
0
category1 = Category(name="Acoustic Guitars")
category2 = Category(name="Electric Guitars")
category3 = Category(name="Bass Guitars")
category4 = Category(name="Ukeleles")
category5 = Category(name="Drums")

session.add(category1)
session.add(category2)
session.add(category3)
session.add(category4)
session.add(category5)
session.commit()
user1 = User(name="User1", email="*****@*****.**")
item1 = Item(name="German Guitar",
             description="Classic Germany guitar.",category=category1,
             created_at=datetime.datetime.now()
             ,user=user1
            )
# item6 = Item(name="  Guitar",
#              description=" guitar.",category=category2,
#              created_at=datetime.datetime.now()
#             )

item2 = Item(name="Scottish Guitar",
             description="Scotland made this beauty and it tastes great.",category=category2,user=user1,
             created_at=datetime.datetime.now())

item3 = Item(name="The One Guitar",
             description="A guitar that works.",category=category3,user=user1,
             created_at=datetime.datetime.now())
示例#43
0
DBSession = sessionmaker(bind=engine)
session = DBSession()


user1 = User(name="Matt-Bott", email="*****@*****.**")
session.add(user1)
session.commit()


category1 = Category(name="Computer Processors")
session.add(category1)
session.commit()


item1 = Item(user_id=1, name="Intel i7-7700K",
             description="4 cores, 8 threads running at base-clock of 4.2GHz",
             category=category1)
session.add(item1)
session.commit()


item2 = Item(user_id=1, name="Intel i5-7600K",
             description="4 cores, 4 threads running at base-clock of 3.8GHz",
             category=category1)
session.add(item2)
session.commit()


category2 = Category(name="Graphics Cards")
session.add(category2)
session.commit()
示例#44
0
                       connect_args={'check_same_thread': False})

# Bind the above engine to a session.
Session = sessionmaker(bind=engine)

# Create a Session object.
session = Session()

user1 = User(name='Rakshith', email='*****@*****.**', picture='')

session.add(user1)
session.add(user2)
session.commit()

category1 = Category(name='Snowboarding', user=user1)

category1 = Category(name='Snowboarding', user=user1)

session.add(category1)
session.commit()

item1 = Item(name='Snowboard',
             description='Best way for any terrain and condition',
             category=category1,
             user=user1)

session.add(item1)
session.commit()

print('Finished populating the database!')
示例#45
0
def item_delete(item_id = None):
  Item.delete_by_id(item_id)
  return redirect_common(url_for('category.home'))
示例#46
0
for category_name in categories:
    print(category_name)

    category = Category(name=category_name,
                        user=user1,
                        picture=categories.get(category_name).get('picture'))

    session.add(category)
    session.commit()

    for item in categories.get(category_name):
        if item != 'picture':
            print("-- {}".format(item))

            items_dict = categories.get(category_name).get(item)

            desc = items_dict.get('description')
            cat_id = items_dict.get('category_id')
            uid = items_dict.get('user_id')
            picture = items_dict.get('picture')

            print("   {} {} {} {}".format(desc, time, cat_id, uid))
            item = Item(name=item,
                        description=desc,
                        creationtime=datetime.datetime.now(),
                        category=category,
                        user=user1,
                        picture=picture)
            session.add(item)
            session.commit()
示例#47
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())
示例#48
0
    picture=
    'https://pbs.twimg.com/profile_images/2671170543/18debd694829ed78203a5a36dd364160_400x400.png'
)
session.add(user1)
session.commit()

# Items for Suits
category1 = Category(user_id=1, name="Suits")

session.add(category1)
session.commit()

item1 = Item(
    user_id=1,
    name="Selected Homme",
    description=
    "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.",
    category=category1,
    picture="suit1.jpg")

session.add(item1)
session.commit()

item2 = Item(
    user_id=1,
    name="Pier One",
    description=
    "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.",
    category=category1,
    picture="suit2.jpg")
session.add(category1)
session.commit()

# item of category 1

item1 = Item(name="Redmi Note 5",
             description='''
                         How does a day with the Redmi Note 5 phone look like?
                         You will probably wake up admiring the beautiful 15.2
                         cm 18:9 full-screen display with rounded corners. You
                         can download various apps and store media files
                         without a worry owing to the 64 GB memory along with a
                         RAM of 4 GB. You keep yourself occupied en-route by
                         playing your favorite games with absolutely no lags.
                         You then capture your favorite moments of the day with
                         the 12 MP camera with a 12-micrometer large pixel-size
                         that lets you take stunning images even in
                         low-lighting conditions. Not to forget about the
                         must-take selfies with your loved ones, which too, can
                         be captured in low-light using the LED selfie-light
                         feature. And as you come to the end of the day after
                         working, surfing,gaming and chatting, you would be
                         pleased to see the 4000 mAh battery still strong in
                         charge.
            ''',
             price="₹11,999",
             category=category1)
session.add(item1)
session.commit()

item2 = Item(name="Samsung Galaxy J2 ",
             description='''
for user in users:
    user_obj = User(email=user['email'], name=user['username'])
    session.add(user_obj)
    session.commit()
user_id_1 = user_obj.id

category1 = Category(name='Full Stack Web Developer Nanodegree',
                     user_id=user_id_1)
session.add(category1)
session.commit()

item1 = Item(
    name='Programming Foundations with Python',
    user_id=user_id_1,
    category=category1,
    description=
    "Introductory programming class to learn Object-Oriented Programming, a must-have technique to reuse and share code easily. Learn by making projects that spread happiness!"
)
session.add(item1)
session.commit()

item2 = Item(
    name='Intro to Relational Databases',
    user_id=user_id_1,
    category=category1,
    description=
    "Relational databases are a powerful tool used throughout the industry. Learn the basics of SQL and how to connect your Python code to a relational database."
)
session.add(item2)
session.commit()
示例#51
0
from sqlalchemy.orm import sessionmaker

from database_setup import Category, Base, Item

engine = create_engine('sqlite:///catalog.db')
Base.metadata.bind = engine

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

category1 = Category(name="Home Audio")
session.add(category1)
session.commit()

Item2 = Item(title="Home Theater Systems",
             description="Home Theater Systems",
             category=category1,
             creator_email="*****@*****.**")
session.add(Item2)
session.commit()

Item1 = Item(title="Receivers & Amplifiers",
             description="Receivers & Amplifiers",
             category=category1,
             creator_email="*****@*****.**")
session.add(Item1)
session.commit()

Item2 = Item(title="Speakers",
             description="Speakers",
             category=category1,
             creator_email="*****@*****.**")
示例#52
0
# session.rollback()
session = DBSession()

# Create dummy user
User1 = User(name="Robo Barista", email="*****@*****.**")
session.add(User1)
session.commit()

# Items for Soccer
catalog1 = Catalog(user_id=1, name="Soccer")

session.add(catalog1)
session.commit()

item1 = Item(user_id=1,
             title="Soccer Cleats",
             description="The shoes",
             catalog=catalog1)

session.add(item1)
session.commit()

item2 = Item(user_id=1,
             title="Jersey",
             description="The shirt",
             catalog=catalog1)

session.add(item2)
session.commit()

# Items for Basketball
catalog2 = Catalog(user_id=1, name="Basketball")
示例#53
0
cameras = Category(user_id=1, name="Cameras")
session.add(cameras)
laptops = Category(user_id=1, name="Laptops")
session.add(laptops)
pcs = Category(user_id=1, name="PCs")
session.add(pcs)
phones = Category(user_id=1, name="Mobile Phones")
session.add(phones)
monitors = Category(user_id=1, name="Monitors")
session.add(monitors)
session.commit()

# Create camera items for category Cameras
camera1 = Item(name="Nikon D7000 dlsr",
               description="20.2mp CMOS sensor, DX frame size",
               price="$889",
               category=cameras,
               user=User1)
camera2 = Item(name="Canon D80 24.4mp Full Frame Sensor",
               price="$1250",
               category=cameras,
               user=User1)
camera3 = Item(name="Nikon D7000 dlsr",
               description="20.2mp CMOS sensor, DX frame size",
               price="$889",
               category=cameras,
               user=User1)
camera4 = Item(name="Canon D80 24.4mp Full Frame Sensor",
               price="$1250",
               category=cameras,
               user=User1)
示例#54
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 "")
示例#55
0
文件: project.py 项目: kjg531/UFS-P3
        flash("An item with the same name already exists in this category. Please choose a different name", "danger")
        return render_template('create_item.html', categories=categories)

    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'])
示例#56
0
session.add(category1)
session.commit()

category2 = Category(user_id=1, name="Listening Devices")

session.add(category2)
session.commit()

category3 = Category(user_id=1, name="Instruments")

session.add(category3)
session.commit()

Item1 = Item(user_id=1,
             name="12 Vinyl",
             description="12 Vinyl Record",
             category_name="Music Mediums")

session.add(Item1)
session.commit()

Item2 = Item(user_id=1,
             name="Compact Disc",
             description="Compact disc (CD) is \
             a digital optical disc data storage format",
             category_name="Music Mediums")

session.add(Item2)
session.commit()

Item3 = Item(user_id=1,
示例#57
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 "")
示例#58
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)
示例#59
0
文件: data.py 项目: ms10596/catalog
    Category(name="Thriller"),
    Category(name="Comedy"),
    Category(name="Adventure"),
    Category(name="Animation"),
    Category(name="Horror"),
    Category(name="Mystery"),
    Category(name="Biography")
]
users = [
    User(email="*****@*****.**", name="Mohamed Sayed", password="******")
]

items = [
    Item(name="Twin Peaks",
         categoryId=1,
         userId=1,
         description="An idiosyncratic FBI agent investigates "
         "the murder of a young woman in the even "
         "more idiosyncratic town of Twin Peaks."),
    Item(name="The Sopranos",
         categoryId=1,
         userId=1,
         description="New Jersey mob boss Tony Soprano deals "
         "with personal and professional issues "
         "in his home and business life that affect"
         " his mental state, leading him to seek "
         "professional psychiatric counseling."),
    Item(name="Game of Thrones",
         categoryId=3,
         userId=1,
         description="Nine noble families fight for control "
         "over the mythical lands of Westeros, "