コード例 #1
0
def try_delete():
    """
    Try to delete an item
    Called from AJAX
    """

    # Make sure something was posted
    if 'itemname' not in request.form:
        ret = {'html': "ERROR. No item selecte for delete", 'status': "ERROR"}
        return json.dumps(ret)
    itemname = request.form["itemname"]

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

    # check if user owns the item
    if not owns_item(itemname):
        ret = {'html': "ERROR. You don't own that item", 'status': "ERROR"}
        return json.dumps(ret)

    # delete item
    session.query(Item).filter(Item.item_name == itemname).delete()
    session.commit()

    ret = {'html': "Item successfully deleted!", 'status': "SUCCESS"}
    return json.dumps(ret)
コード例 #2
0
ファイル: app.py プロジェクト: flauberjp/CatalogApp
def newItem():
    loggedIn = 'access_token' in login_session \
        and login_session['access_token'] is not None
    name = ''
    user_email = ''
    if loggedIn:
        name = login_session['name']
        user_email = login_session['email']

    if request.method == 'POST':
        if loggedIn == False and user_email == request.form['user_email']:
            abort(403)

        userId = getUserID(request.form['user_email'])

        newItem = Item(name=request.form['name'],
                       description=request.form['description'],
                       category_id=request.form['category_id'],
                       user_id=userId)
        session.add(newItem)
        session.commit()
        category = session.query(Category).filter(
            Category.id == request.form['category_id']).first()
        return redirect(
            url_for('showItems',
                    category_name=category.name,
                    item_name=request.form['name']))
    else:
        categories = session.query(Category).all()
        return render_template('catalog/newItem.html',
                               categories=categories,
                               loggedIn=loggedIn,
                               name=name,
                               user_email=user_email)
コード例 #3
0
ファイル: server.py プロジェクト: irsol/item-catalog-app
def edit_item(category_name, item_name):
    category = session.query(Category).filter_by(name=category_name).one()
    edited_item = session.query(Item).filter_by(name=item_name,
                                                category_id=category.id).one()

    # Authorisation - check if current user can edit the item
    # Only a user who created an item can edit/delete it
    user_id = get_user_id(login_session['email'])
    if edited_item.user_id != user_id:
        message = json.dumps('You are not allowed to edit the item')
        response = make_response(message, 403)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Post method
    if request.method == 'POST':
        if request.form['name']:
            edited_item.name = request.form['name']
        if request.form['description']:
            edited_item.description = request.form['description']
        if request.form['category']:
            category = session.query(Category).filter_by(name=request.form
                                                         ['category']).one()
            edited_item.category = category

        session.add(edited_item)
        session.commit()
        return redirect(url_for('show_category',
                                category_name=edited_item.category.name))
    else:
        categories = session.query(Category).all()
        return render_template('edititem.html', item=edited_item,
                               categories=categories)
コード例 #4
0
ファイル: server.py プロジェクト: irsol/item-catalog-app
def item_json(category_name, item_name):
    category = session.query(Category).filter_by(name=category_name).one()
    item = session.query(Item).filter_by(category_id=category.id,
                                         name=item_name).one()
    result = {}
    result['Item'] = item.serialize
    return jsonify(result)
コード例 #5
0
def editItem(item_id):
    # If the method is POST, connect to the database and update it
    if request.method == "POST":
        item_update = database_session.query(Items).filter_by(id=item_id).one()
        # Check if the editing user is the user creating this item
        if item_update.user_id != session['user_id']:
            flash('You have no permession to edit item %s' % (item.name,))
            return redirect('/')
        item_update.name = request.form["name"]
        item_update.catagory_id = request.form["catagory_id"]
        item_update.description = request.form["description"]
        # Commit the changes and except the errors
        try:
            database_session.add(item_update)
            database_session.commit()
            flash("Item \"%s\" has been updated!" % (item_update.name,))
            return redirect("/")
        except SQLAlchemyError:
            flash("Cannot edit the item! Please contact developer!")
            return redirect("/")
    else:
        # Render the item edited to user
        try:
            item = database_session.query(Items).filter_by(id=item_id).join(
                Items.catagory).one()
            catagory = database_session.query(Catagory).all()
            return render_template(
                "itemForm.html", item=item, catagory=catagory, editFlag=True)
        except NoResultFound:
            flash("Cannot find the item!")
            return redirect('/')
コード例 #6
0
def edit_contact(contact):
    if 'email' not in session:
        return redirect(url_for('login'))
    form = ContactForm()
    contactDetail = db_session.query(Contact).filter_by(
        contactId=contact).first()
    if request.method == 'POST':
        useremail = db_session.query(User).filter_by(
            id=contactDetail.UserId).first()
        if useremail.email == session['email']:
            if form.email.data != contactDetail.email:
                contactDetail.email = form.email.data
            if form.address.data != contactDetail.address:
                contactDetail.address = form.email.data
            if form.phone_number.data != contactDetail.phoneNumber:
                contactDetail.phoneNumber = form.phone_number.data
            db_session.commit()
            flash('Contact has been updated.')
            return redirect(url_for('contacts'))
        else:
            flash('This is not your account')
            return redirect(url_for('contacts'))

    elif request.method == 'GET':
        form.first_name.content = contactDetail.name
        form.last_name.content = contactDetail.name
        form.phone_number.content = contactDetail.phoneNumber
        form.email.content = contactDetail.email
        form.address.content = contactDetail.address
        return render_template('editcontact.html',
                               contact=contactDetail,
                               form=form)
コード例 #7
0
def edit_item(itemname):
    """
    This function edits an item
    """

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

    # check if user owns the item
    if not owns_item(itemname):
        return render_template('denied.html', title="denied",
                               logged=url_for('.gdisconnect'), logact="Logout")

    # generate form to edit item
    categories = show_categories()
    query = session.query(Item).filter(Item.item_name == itemname).first()
    t_desc = query.description
    query2 = session.query(Category).join(Item)
    query2 = query2.filter(Item.item_name == itemname)
    t_cat = query2.first().category_name
    return render_template('edit.html', title="edit", item=itemname,
                           logged=url_for('.gdisconnect'), logact="Logout",
                           categories=categories, name=itemname, desc=t_desc,
                           cur_cat=t_cat)
コード例 #8
0
ファイル: server.py プロジェクト: irsol/item-catalog-app
def show_catalog():
    """Show all catalog categories and items
    """

    categories = session.query(Category).all()
    items = session.query(Item).all()
    return render_template('catalog.html', categories=categories, items=items)
コード例 #9
0
def contacts():
    if 'email' not in session:
        return redirect(url_for('login'))
    else:
        mail = str(session['email'])
        user = db_session.query(User).filter_by(email=mail).first()
        contacts = db_session.query(Contact).filter_by(UserId=user.id)
        return render_template('contacts.html', contacts=contacts)
コード例 #10
0
def indexDisplayTemp(catagoryTarget):
    # Query the items with selected catagory
    catagory = database_session.query(Catagory).all()
    itemTitle = catagoryTarget
    itemShow = database_session.query(Items).join(
        Items.catagory).filter_by(name=catagoryTarget).all()
    return render_template(
        "index.html", catagory=catagory, itemShow=itemShow,
        itemTitle=itemTitle, login=session['logined'])
コード例 #11
0
def show_items():
    """
    This function shows all items
    returns a list of (item,category) tuples
    """
    query = session.query(Item).order_by(desc(Item.created_date))
    ret = []
    for x in query:
        t_name = x.item_name
        t_cat = session.query(Category).filter(Category.id == x.cat_id).one()
        ret.append((t_name, t_cat.category_name))
    return ret
コード例 #12
0
def is_user_the_creator(item_id):
    """
    Return Item for specified ID if logged in
    user is also the creator of the target item
    Otherwise, redirect to safe home page with user message
    :param item_id:
    :return: The item + user record
    """
    # User must be logged in for GET and POST
    if 'userid' not in login_session:
        # flash('Unfortunately you need to be logged in to make changes', 'error')
        # return redirect(url_for('show_homepage'))
        raise InvalidUsage(
            'Unfortunately you need to be logged in to make changes',
            status_code=403)

    item = session.query(
        Item, User).outerjoin(User).filter(Item.id == item_id).first()

    # For existing items, user must be item creator
    if item and item.Item.user_id != login_session['userid']:
        # flash('Unfortunately this item was not created by you', 'error')
        # return redirect(url_for('show_homepage'))
        raise InvalidUsage('Unfortunately this item was not created by you',
                           status_code=403)
    return item
コード例 #13
0
ファイル: app.py プロジェクト: flauberjp/CatalogApp
def deleteItem(category_name, item_name):
    loggedIn = 'access_token' in login_session \
        and login_session['access_token'] is not None
    name = ''
    user_email = ''
    if loggedIn:
        name = login_session['name']
        user_email = login_session['email']

    itemToDelete = session.query(Item).join(Category).filter(
        Category.name == category_name, Item.name == item_name).first()
    if request.method == 'POST':
        if loggedIn == False and user_email == request.form['user_email']:
            abort(403)
        session.delete(itemToDelete)
        session.commit()
        return redirect(
            url_for('showItems',
                    category_name=category_name,
                    item_name='items'))
    else:
        return render_template('catalog/deleteItem.html',
                               category_name=category_name,
                               item_name=item_name,
                               loggedIn=loggedIn,
                               name=name,
                               user_email=user_email)
コード例 #14
0
def fbconnect():
    # If the state variable from request is not the same as the one
    # in session,
    # Reject the request
    if request.args.get('state') != session['state']:
        response = make_response(json.dunps("Invalid Request!!!"), 401)
        response.header['Content-type'] = 'application/json'
        return response
    session['logined'] = True

    # Get the server token from facebook
    clientToken = request.data
    file = open('secret.json', 'r')
    fbsecret = json.loads(file.read())
    url = 'https://graph.facebook.com/oauth/access_token?' \
        'grant_type=fb_exchange_token&client_id=%s&client_secret=%s' \
        '&fb_exchange_token=%s' % (
            fbsecret['app_id'], fbsecret['secret'], clientToken)
    http = httplib2.Http()
    result = http.request(url, 'GET')[1]
    serverToken = result.split(',')[0].split(':')[1].replace('"', '')
    session['token'] = serverToken

    # Get the user information
    userinfo_url = 'https://graph.facebook.com/v2.8/me'\
        '?access_token=%s&fields=name,id,email' % serverToken
    http = httplib2.Http()
    userinfo = json.loads(http.request(userinfo_url, 'GET')[1])
    # Attach the result to session
    session['provider'] = 'facebook'
    session['user'] = userinfo["name"]
    session['email'] = userinfo["email"]
    session['facebook_id'] = userinfo["id"]

    # Insert the user into the database
    try:
        item = database_session.query(
            User).filter_by(
            provider=session['provider'],
            provider_id=session['facebook_id']).one()
        session['user_id'] = item.id
    except NoResultFound:
            # Try to add the new catagory
        newUser = User(
            provider=session['provider'],
            provider_id=session['facebook_id'])
        try:
            database_session.add(newUser)
            database_session.flush()
            database_session.commit()
            session['user_id'] = newUser.id
        except SQLAlchemyError:
            flash("The system cannot add the user")
            return redirect("/")

    # Flash the system message
    flash('Login Successfully via %s as %s.' % (
        session['provider'], session['user']))

    return 'success'
コード例 #15
0
ファイル: server.py プロジェクト: irsol/item-catalog-app
def add_item():
    categories = session.query(Category).all()
    if request.method == 'POST':
        new_item = Item(
            name=request.form['name'],
            description=request.form['description'],
            category=session.query(Category).
            filter_by(name=request.form['category']).one(),
            user_id=login_session['user_id'])

        session.add(new_item)
        session.commit()

        return redirect(url_for('show_catalog'))
    else:
        return render_template('additem.html', categories=categories)
コード例 #16
0
def contact_details(contact):
    if 'email' not in session:
        return redirect(url_for('login'))
    else:
        contactDetails = db_session.query(Contact).filter_by(
            contactId=contact).first()
        return render_template('contactInfo.html', contact=contactDetails)
コード例 #17
0
def new_contact():
    if 'email' not in session:
	    return redirect(url_for('login'))
    form = ContactForm()
    if request.method == 'POST':
        if form.validate() is False:
            return render_template('newcontact.html', form=form)
        else:
            email = session['email']
            user = db_session.query(User).filter_by(email=email).first()
            contacts = Contact()
            contacts.UserId = user.id
            if form.first_name.data and form.last_name.data:
                contacts.name = form.first_name.data+' '+form.last_name.data
            if form.email.data:
                contacts.email = form.email.data
            if form.phone_number:
                contacts.phoneNumber = form.phone_number.data
            if form.address.data:
                contacts.address = form.address.data
            db_session.add(contacts)
            db_session.commit()
            return redirect(url_for('contacts'))
    elif request.method == 'GET':
        return render_template('newcontact.html', form=form)
コード例 #18
0
def save_item(item, item_id):
    """
    Utility method for updating an existing
    item or creating a new item
    :param item:
    :param item_id:
    :return: Rendered html
    """
    # User is modifying an EXISTING item in the database
    if item_id > 0:
        item.Item.name = request.form['title']
        item.Item.description = request.form['description']
        item.Item.category_id = request.form['category']
        session.add(item.Item)
        session.commit()
        flash("Updated " + item.Item.name)
        return render_template('item_details.html',
                               item=item,
                               login_session=login_session)

    # User is creating a NEW item
    else:
        new_item = Item(name=request.form.get('title'),
                        description=request.form['description'],
                        category_id=request.form['category'],
                        user_id=login_session['userid'])
        session.add(new_item)
        session.commit()
        flash("Created " + new_item.name)
        created_item = session.query(
            Item, User).filter(Item.id == new_item.id).join(User).first()
        return render_template('item_details.html',
                               item=created_item,
                               login_session=login_session)
コード例 #19
0
def deleteitem(itemid):

    # Check if user is authorized
    if isauthorized() == False:
        return redirect('/welcome')

    if request.method == 'GET':
        _user_id = login_session['userid']


        _itemToDelete = session.query(Item).filter_by(
            id=itemid, user_id=_user_id).first()

        # Check if item to be deleted is in databes and if not tell the user.
        if _itemToDelete is None:

            _flashmessage = "Unfortunately you're not authorized to delete \
                            this item!"
            flash(_flashmessage)

            return redirect(url_for('metalitems'))

        else:

            session.delete(_itemToDelete)
            session.commit()

            # Let the user know that his item has been deleted.
            _flashmessage = 'Item ' + _itemToDelete.title \
                + ' has been deleted.'
            flash(_flashmessage)

            # return to main page
            return redirect(url_for('metalitems'))
コード例 #20
0
def reset_password():
    if 'email' in session:
        return redirect(url_for('home'))
    form = RequestPasswordReset()

    if request.method == 'POST':
        print form.email.data
        if form.validate() is False:
            flash('Please enter a valid email.')
            return render_template('resetpassword.html', form=form)
        else:
            user = db_session.query(User).filter_by(
                email=form.email.data).first()
            if user is not None:
                print form.email.data
                msg = Message('Password reset',
                              sender=mail_username,
                              recipients=[form.email.data])
                msg.body = 'http://localhost:5000/changepassword'
                mail.send(msg)
                return redirect(url_for('email_sent'))
            else:
                flash('Email not in database')
                return redirect(url_for('reset_password'))
    elif request.method == 'GET':
        return render_template('resetpassword.html', form=form)
コード例 #21
0
def newItem():
    # If the method is POST, try to add the new record
    if request.method == "POST":
        record = Items(
            name=request.form["name"],
            catagory_id=request.form["catagory_id"],
            description=request.form["description"],
            user_id=session['user_id'])
        # Try to add the new items
        try:
            database_session.add(record)
            database_session.commit()
        except SQLAlchemyError:
            flash("Cannot edit the item! Please contact developer!")
            return redirect("/")
        # Flash the system message
        flash("Item \"%s\" has already created!" %
              (record.name,))
        return redirect("/")
    else:
        # Render the existing catagories for selection
        catagory = database_session.query(Catagory).all()
        item = None
        return render_template(
            "itemForm.html", catagory=catagory, item=item, editFlag=False)
コード例 #22
0
def deleteitem(itemid):

    # Check if user is authorized
    if isauthorized() == False:
        return redirect('/welcome')

    if request.method == 'GET':
        _user_id = login_session['userid']

        _itemToDelete = session.query(Item).filter_by(
            id=itemid, user_id=_user_id).first()

        # Check if item to be deleted is in databes and if not tell the user.
        if _itemToDelete is None:

            _flashmessage = "Unfortunately you're not authorized to delete \
                            this item!"

            flash(_flashmessage)

            return redirect(url_for('metalitems'))

        else:

            session.delete(_itemToDelete)
            session.commit()

            # Let the user know that his item has been deleted.
            _flashmessage = 'Item ' + _itemToDelete.title \
                + ' has been deleted.'
            flash(_flashmessage)

            # return to main page
            return redirect(url_for('metalitems'))
コード例 #23
0
ファイル: server.py プロジェクト: irsol/item-catalog-app
def catalog_json():
    """Return list of categories and items in each category
    """

    categories = session.query(Category).all()
    catalog = []

    # iterate over categories and format them
    for c in categories:
        items = session.query(Item).filter_by(category_id=c.id)
        c = c.serialize
        c['Item'] = [i.serialize for i in items]

        catalog.append(c)

    return jsonify(Category=catalog)
コード例 #24
0
def show_profile():
    """
    Show user profile including the APP_ID which is required for modifications using JSON
    """
    print('LOGIN SESSION:', login_session)
    if 'userid' in login_session:
        category = session.query(Category).first()
        item = session.query(Item).first()
        return render_template('profile.html',
                               login_session=login_session,
                               root=app.instance_path,
                               category=category,
                               item=item)
    flash('Unfortunately you need to be logged in to see your profile',
          'error')
    return redirect(url_for('show_homepage'))
コード例 #25
0
def deleteMenuItem(restaurant_id, menu_id):
    menuitem = session.query(MenuItem).filter_by(id=menu_id).one()
    if request.method == 'POST':
        session.delete(menuitem)
        session.commit()
        flash("Menu-Item deleted")
        return redirect(url_for('listMenuItems', restaurant_id=restaurant_id))
    return render_template('deleteMenuItem.html', menuitem=menuitem)
コード例 #26
0
def deleteRestaurant(restaurant_id):
    restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()
    if request.method == 'POST':
        session.delete(restaurant)
        session.commit()
        flash("Restaurant deleted")
        return redirect(url_for('listRestaurants'))
    return render_template('deleteRestaurant.html', restaurant=restaurant)
コード例 #27
0
def api_item_details(item_id):
    """
    Displays or edits specified item
    """
    if request.method == 'GET':
        item = session.query(
            Item, User).join(User).filter(Item.id == item_id).first()
        return jsonify(item.Item.to_json())
コード例 #28
0
ファイル: app.py プロジェクト: flauberjp/CatalogApp
def showItemsJSON(category_name, item_name):
    loggedIn = 'access_token' in login_session \
            and login_session['access_token'] is not None
    userId = None
    if loggedIn:
        userId = getUserID(login_session['email'])

    category = session.query(Category).filter(
        Category.name == category_name).first()
    if item_name == 'items':
        items = session.query(Item).filter(Item.category_id == category.id)
        items_to_JSONinfy = [i.serialize for i in items]
        return jsonify(items_to_JSONinfy)
    else:
        item = session.query(Item).filter(Item.category_id == category.id,
                                          Item.name == item_name).first()
        return jsonify(item.serialize)
コード例 #29
0
def show_categories():
    """
    This function shows all categories
    returns a list of categories
    """
    query = session.query(Category)
    ret = [x.category_name for x in query]
    return ret
コード例 #30
0
def show_item_details(item_id):
    """
    Displays full description of an item
    """
    item = session.query(Item,
                         User).join(User).filter(Item.id == item_id).first()
    return render_template('item_details.html',
                           item=item,
                           login_session=login_session)
コード例 #31
0
ファイル: auth.py プロジェクト: irsol/item-catalog-app
def get_user_id(email):
    """ Takes an email and reterns an id, if email belongs to a user
        stored inour db
    """
    try:
        user = session.query(User).filter_by(email=email).one()
        return user.id
    except:
        return None
コード例 #32
0
def createUser():
    newUser = User(username=login_session['username'],
                   email=login_session['email'])

    session.add(newUser)
    session.commit()

    user = session.query(User).filter_by(email=login_session['email']).one()
    return user.id
コード例 #33
0
def show_category_items(category_id):
    """
    Displays all the items for the specified category
    """
    all_categories = session.execute(
        'SELECT category.name, category.id, count(item.id) AS item_count '
        'FROM category LEFT JOIN item ON category.id = item.category_id '
        'GROUP BY category.name, category.id')
    category = session.query(Category).filter(
        Category.id == category_id).first()
    items = session.query(Item).filter(Item.category_id == category_id)
    item_count = items.count()
    return render_template('category_items.html',
                           all_categories=all_categories,
                           category=category,
                           items=items,
                           item_count=item_count,
                           login_session=login_session)
コード例 #34
0
def editRestaurant(restaurant_id):
    restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()
    if request.method == 'POST':
        restaurant.name = request.form.get('name', '')
        session.add(restaurant)
        session.commit()
        flash("Restaurant edited")
        return redirect(url_for('listRestaurants'))
    return render_template('editRestaurant.html', restaurant=restaurant)
コード例 #35
0
def no_email():
    """
    This function checks if email is in database
    returns True if user email in database
    returns False if not
    """
    query = session.query(User).filter(User.email == login_session['email'])
    print query.count()
    return query.count() == 0
コード例 #36
0
def createUser():
    newUser = User(username=login_session[
                   'username'], email=login_session['email'])

    session.add(newUser)
    session.commit()

    user = session.query(User).filter_by(email=login_session['email']).one()
    return user.id
コード例 #37
0
ファイル: auth.py プロジェクト: irsol/item-catalog-app
def create_user(login_session):
    """ User helper functions
        Creates a new user in our db
    """
    new_user = User(name=login_session['username'],
                    email=login_session['email'])
    session.add(new_user)
    session.commit()
    user = session.query(User).filter_by(email=login_session['email']).one()
    return user.id
コード例 #38
0
def metalitems():
    # Check if user is looged in, otherwiese redirect to welcome page.
    if 'logged_in' not in login_session:

        return redirect('/welcome')

    else:
        # Check for user with loginsession, who had logged out and redirect to welcome
        # page.
        if login_session['logged_in'] == False:

            return redirect('/welcome')
        # query categories and items of looged in user and render metal items.
        _user_id = login_session['userid']
        _categories = session.query(Category).filter_by(user_id=_user_id)
        _items = session.query(Item).filter_by(user_id=_user_id)

    return render_template('metalitems.html', categories=_categories,
                           items=_items)
コード例 #39
0
def getUserId(email):
    # check if user with email provided from google is already there  and..
    try:
        user = session.query(User).filter_by(
            email=login_session['email']).one()
    # if so return his user id which is used to show only his stuff.
        return user.id
   # If user is not there return none in this case
   # createUser is invoked to creat him on the fly.
    except:
        return None
コード例 #40
0
def owns_item(item):
    """
    This function checks if currently logged in user owns an item
    returns True if is owner
    returns False if not
    """
    query = session.query(Item).join(User)
    query = query.filter(User.email == login_session['email'])
    query = query.filter(Item.item_name == item)
    print query.count()
    return query.count() != 0
コード例 #41
0
def updatecategory(categoryid):

    # Check if user is authorized
    if isauthorized() == False:
        return redirect('/welcome')

    # Go here in case user clicks on update categroy button on metal items
    # page.
    if request.method == 'GET':
        # Get userid for query of category user whants to update
        _user_id = login_session['userid']

        # Qurey for category to update.
        _categoryToUpdate = session.query(Category).filter_by(
            id=categoryid, user_id=_user_id).first()

        # render template for editing ategory name
        return render_template('updatecategory.html',
                               categoryToUpdate=_categoryToUpdate)
# In case user clicks button update category on update category site go here.
    else:
        # Check if category name is not an empty string
        if request.form['newcategoryname'] == '':
            # If so tell user
            _flashmessage = 'Name of category must not be empty!'
            flash(_flashmessage)

        else:
            # In case propper category name is submitted, update category table
            # with it.
            session.query(Category).filter_by(id=categoryid).update(
                {"name": request.form['newcategoryname']})
            session.commit()

            # Tell user category has been updated.
            _flashmessage = 'Name of category has been changed to: ' + \
                request.form['newcategoryname']
            flash(_flashmessage)
            # Go back to main page.
        return redirect(url_for('metalitems'))
コード例 #42
0
def try_add():
    """
    This function receives data from the create item page from ajax call
    Attempts add that item to database
    """

    # Check that user is logged in
    if 'username' not in login_session:
        ret = {'html': "Not logged in",
               'status': "ERROR"}
        return json.dumps(ret)

    # Check that values were posted
    if 'name' not in request.form or 'desc' not in request.form:
        ret = {'html': "No values given",
               'status': "ERROR"}
        return json.dumps(ret)

    # needed variables
    t_name = request.form["name"]
    t_desc = request.form["desc"]

    # check if item exists already
    # does not make sense to have more than 1 item with same name
    if session.query(Item).filter(Item.item_name == t_name).count() != 0:
        ret_str = "Sorry. "
        ret_str += t_name
        ret_str += " is already in the database"
        ret = {'html': ret_str, 'status': "ERROR"}
        return json.dumps(ret)

    # get one and only one category id
    t_cat = return_one_category(request.form["category"])
    if t_cat == "ERROR":
        ret = {'html': "Error getting category id", 'status': "ERROR"}
        return json.dumps(ret)

    # get one and only one user id
    t_user = return_one_user(login_session['email'])
    if t_user == "ERROR":
        ret = {'html': "Error getting user id", 'status': "ERROR"}
        return json.dumps(ret)

    # add to database
    t_itm = Item(item_name=t_name, description=t_desc,
                 cat_id=t_cat, creator=t_user)
    session.add(t_itm)
    session.commit()

    # Return
    ret = {'html': "Item successfully added!", 'status': "SUCCESS"}
    return json.dumps(ret)
コード例 #43
0
def serializebyitemid(categoryid, itemid):

    # Check if user is authorized.
    if isauthorized() == False:
        return redirect('/welcome')

# Get items of the user filtered by categoryid.
    _items = session.query(Seri).filter_by(user_id=login_session['userid'], \
    category_id=categoryid, item_id=itemid)
    session.commit()

# Return them as a json
    return jsonify(Metalitems=[i.serialize for i in _items])
コード例 #44
0
def make_item(catname, itemname):
    """
    This function makes the page for items
    Shows description of item
    If the user is logged in will check if user owns item
    If user owns item, will have edit and delete buttons
    """

    # Check if logged in or not
    if 'username' not in login_session:
        t_logact = "Login"
        t_logged = url_for('.login')
        try:
            query = session.query(Item).filter(Item.item_name == itemname)
            query = query.one()
        except:
            return render_template('notfound.html', title="denied",
                                   logged=url_for('.login'), logact="Login")
        return render_template('item.html', title=itemname, item=itemname,
                               desc=query.description, logged=t_logged,
                               logact=t_logact)
    else:
        t_logact = "Logout"
        t_logged = url_for('.gdisconnect')
        if owns_item(itemname):
            t_edit = True
        else:
            t_edit = False
        try:
            query = session.query(Item).filter(Item.item_name == itemname)
            query = query.first()
        except:
            return render_template('notfound.html', title="denied",
                                   logged=url_for('.gdisconnect'),
                                   logact="Logout")
        return render_template('item.html', title=itemname, item=itemname,
                               desc=query.description, logged=t_logged,
                               logact=t_logact, edit=t_edit)
コード例 #45
0
def make_category(catname):
    """
    This function makes a category page
    The category page shows every item in the category
    """

    # Check if logged in to change login/logout link
    if 'username' not in login_session:
        t_logact = "Login"
        t_logged = url_for('.gdisconnect')
    else:
        t_logact = "Logout"
        t_logged = url_for('.login')

    # Get all items in category
    query = session.query(Item).join(Category)
    query = query.filter(Category.category_name == catname)
    ret = [x.item_name for x in query]
    return render_template('category.html', title=catname, catlist=ret,
                           logged=t_logged, logact=t_logact)
コード例 #46
0
def newitem(categoryid):

    # Check if user is authorized
    if isauthorized() == False:
        return redirect('/welcome')

    # If user clicks button add item, check if item title is not an ampty
    # string. Then store the new item in table items.
    if request.method == 'POST':
        _itemtitle = request.form['newitemtitle']

        if _itemtitle == '':
            _flashmessage = 'Name of item must not be empty!'
            flash(_flashmessage)
            return render_template('newmetalitem.html', categoryid=categoryid)

        else:
            _itemdescription = request.form['newitemdescription']
            _user_id = login_session['userid']
            _newItem = Item(title=_itemtitle, description=_itemdescription,
                            category_id=categoryid, user_id=_user_id)
            session.add(_newItem)
            session.commit()

            # Let the user know his new item has been safed.
            _flashmessage = 'Item ' + _itemtitle + ' has been created.'
            flash(_flashmessage)
            # Return to main page.
            return redirect(url_for('metalitems'))

    # If request is not post but get go here (comming from main page
    # metalitems).
    else:

        _category = session.query(Category).filter_by(
            id=categoryid).first()
        return render_template('newmetalitem.html', categoryid=categoryid,
                               categoryname=_category.name)
コード例 #47
0
def try_edit():
    """
    Try to edit an item
    Called from AJAX
    """

    # Check that user is logged in
    if 'username' not in login_session:
        ret = {'html': "Not logged in",
               'status': "ERROR"}
        return json.dumps(ret)

    # make sure data was posted
    if ('name' not in request.form or 'desc' not in request.form or
            'original' not in request.form or 'category' not in request.form):
        ret = {'html': "No values given",
               'status': "ERROR"}
        return json.dumps(ret)

    # get data
    original_name = request.form["original"]
    new_name = request.form["name"]
    new_desc = request.form["desc"]
    new_cat = return_one_category(request.form["category"])

    # update data
    item = session.query(Item).filter(Item.item_name == original_name).first()
    item.item_name = new_name
    item.description = new_desc
    item.cat_id = new_cat
    session.commit()

    # return to ajax call
    ret = {'status': "SUCCESS",
           'html': "Successfully updated item"}

    return json.dumps(ret)
コード例 #48
0
def deletecategory(categoryid):

    # Check if user is authorized
    if isauthorized() == False:
        return redirect('/welcome')

    # Make sure site is only accessible by clicking the button and not by typing
    # url in browser.
    if request.method == 'POST':

        _user_id = login_session['userid']


        _categoryToDelete = session.query(Category).filter_by(
            id=categoryid, user_id=_user_id).first()
        # Check if category to be deleted is in database. And if not, tell the
        # user.
        if _categoryToDelete is None:

                _flashmessage = "Unfortunately you're not authorized to delete \
                this category!"
                flash(_flashmessage)

                return redirect(url_for('metalitems'))
        else:

                # Tell user category has been deleted.
                _flashmessage = 'Category ' + _categoryToDelete.name \
                + ' has been delete!'
                flash(_flashmessage)

                # Do it!
                session.delete(_categoryToDelete)
                session.commit()

                return redirect(url_for('metalitems'))
コード例 #49
0
def updateitem(itemid):

    # Check if user is authorized
    if isauthorized() == False:
        return redirect('/welcome')

    # If request is get go here and show site where one can edit an existing
    # item.
    if request.method == 'GET':
        _user_id = login_session['userid']

        _itemToUpdate = session.query(Item).filter_by(
            id=itemid, user_id=_user_id).first()
        _categories = session.query(Category).filter_by(user_id=_user_id)

        # Check if item to be updated is in database and if not let the user
        # know.
        if _itemToUpdate is None:

            _flashmessage = "Unfortunately you're not authorized to update \
                                this item!"
            flash(_flashmessage)

            return redirect(url_for('metalitems'))

        else:

            return render_template('updatemetalitem.html',
                    itemToUpdate=_itemToUpdate, categories=_categories)

    # Go here when user has updatet his item und clicks the save button.
    else:
        _user_id = login_session['userid']

        _itemToUpdate = session.query(Item).filter_by(
            id=itemid, user_id=_user_id).first()

        _newcategory = session.query(Category).filter_by(
            name=request.form['chosencategory']).first()

        # Check if item to be updated is in database or new category is in
        # database. If not tell the user.
        if _itemToUpdate is None or _newcategory is None:

            _flashmessage = "Unfortunately you're not authorized to update \
                                this item!"
            flash(_flashmessage)

            return redirect(url_for('metalitems'))

        else:

            session.query(Item).filter_by(id=itemid).update(
                {"title": request.form['newitemtitle'],
                "description": request.form['newitemdescription'],
                "category_id": _newcategory.id})
            session.commit()

                # Let the user know that his item has been updated.
            _flashmessage = 'Item ' + _itemToUpdate.title \
                        + ' has been updated.'
            flash(_flashmessage)

            return redirect(url_for('metalitems'))
コード例 #50
0
# Full Stack Web Developer Nanodegree
# Project 3 Catalog


import database_setup
from database_setup import User, Category, Item, session, get_categories
from database_setup import return_one_category, make_json


"""
This script adds sample categories to database
"""


# Reset the Database
session.query(User).delete()
session.query(Category).delete()
session.query(Item).delete()


# Art Supplies Store Categories
cat_brush = Category(category_name="Brushes")
cat_mats = Category(category_name="Materials")
cat_pen = Category(category_name="Pens")
session.add_all([
    cat_brush,
    cat_mats,
    cat_pen])


# Add users