コード例 #1
0
ファイル: views.py プロジェクト: frost-byte/catalog
def newCategory():
    """Allow an Authorized User to add a new Category or Process the form for
    adding a new Category.

    Returns:
        For a GET operation returns a Web View containing a form for entering
        data for the new user.

        A successful POST request directs presents a View of the new Category.

    """
    # Only an Authenticated User can add New Categories
    if isActiveSession() is False:
        return redirect(url_for("listCategory"))

    # Process the New Category Form and add it to the Database
    if request.method == "POST":
        newCategory = Category(user_id=getSessionUserInfo()["id"], name=request.form["name"])

        session.add(newCategory)
        session.commit()

        flash("New Category created!")
        # Display the Information for the new Category
        return redirect(url_for("viewCategory", key=newCategory.id))

    else:
        return render_template(
            "generic.html",
            modelType="category",
            viewType=os.path.join("partials", "new.html"),
            traits=Category.defaultTraits(),
        )
コード例 #2
0
ファイル: views.py プロジェクト: frost-byte/catalog
def newUser():
    """Present an Authorized Web User with a View for adding a new user.

    Returns:
        For a GET operation returns a Web View containing a form for entering
        data for the new user.

        A successful POST request directs presents a View of the new Record.

    """
    if isActiveSession() is False:
        return redirect(url_for("listUser"))

    # Process New User Form Submission
    if request.method == "POST":
        # Add the new user record to the database
        newUser = User(name=request.form["name"])

        session.add(newUser)
        session.commit()

        flash("New User created!")

        # Redirect to the User View
        return redirect(url_for("viewUser", key=newUser.id))

    # Present the New User Form
    else:
        return render_template(
            "generic.html", modelType="user", viewType=os.path.join("partials", "new.html"), traits=User.defaultTraits()
        )
コード例 #3
0
ファイル: views.py プロジェクト: frost-byte/catalog
def delItem(item_name):
    """Retrieve the view for Deleting an Item in a Category.

    Requires a user to be authenticated and to have created the item.

    Notes:
        The actual deletion operation, when a POST request is sent, is
        performed by the deleteItem function.

    Args:
        category_name (string): The Category name of the Item to delete.

        item_name (string):     The name of the Item to delete.

    Returns:
        A GET request presents the user with choices for deleting the Item or
        canceling the operation.

    """
    if isActiveSession() is False:
        flash("Please log in to delete an item.")
        return redirect(url_for("listItem"))

    # Find the item's category by name
    category = Category.query.filter_by(name=category_name).one()

    # Find the item by matching it's name and category id to the above category.
    try:
        deleteItem = Item.query.filter_by(name=item_name, cat_id=category.id).one()

    except NoResultFound:
        flash("""No item named {0} was found in the {1} category.""".format(item_name, category_name))
        return redirect(url_for("listItem"))

    if canAlter(deleteItem.user_id) is False:
        flash("You are not authorized to delete that item.")
        return redirect(url_for("viewItem", key=deleteItem.id))

    # Forward the request to the Delete view.
    return render_template(
        "generic.html",
        viewType=os.path.join("partials", "delete.html"),
        modelType="item",
        key=deleteItem.id,
        name=item_name,
    )
コード例 #4
0
ファイル: views.py プロジェクト: frost-byte/catalog
def editCatItem(category_name, item_name):
    """Edit an Item in a Category.

    Requires a user to be authenticated and to have created the item.

    Args:
        category_name (string): The Category of the Item to edit.

        item_name (string): The name of the Item to Edit.

    Returns:
        A GET request presents the user with a form for editing an Item.

        A POST request processes the user's input from the form and updates the
        item.

    """
    # User has been authenticated and the login_session is valid.
    if isActiveSession() is False:
        flash("Please log in to edit an item.")
        return redirect(url_for("listItem"))

    # Find the Item's category by the category's name in the database
    category = Category.query.filter_by(name=category_name).one()

    # Find the item using its name and its category's id
    item = Item.query.filter_by(name=item_name, cat_id=category.id).one()

    # The active user for the session must be the creator of the item being
    # editted.
    if canAlter(item.user_id) is False:
        flash("You are not authorized to alter that item.")
        return redirect(url_for("viewItem", key=item.id))

    # This is the right user, so show them the edit form.
    return render_template(
        "generic.html",
        modelType="item",
        viewType=os.path.join("partials", "edit.html"),
        category=category_name,
        key=item.id,
        name=item.name,
        traits=item.traits(True),
        allowAlter=canAlter(item.user_id),
    )
コード例 #5
0
ファイル: views.py プロジェクト: frost-byte/catalog
def deleteUser(key):
    """Present the Web User with a Delete View for the their User account.

    Args:
        key (int): An ID corresponding to a User record in the database.

    Returns:
        For a GET operation returns a Web View containing buttons for
        canceling or submitting the delete user request.

        A successful POST request would delete the User's record, sign them out
        and revoke the app's authorization to use their Google profile

    """
    if isActiveSession() is False:
        return redirect(url_for("listUser"))
    else:
        return redirect(url_for("viewUser", key=key))
コード例 #6
0
ファイル: views.py プロジェクト: frost-byte/catalog
def editCategory(key):
    """Allow an Authorized User to edit a new Category or Process the form for
    editing a Category.

    Args:
        key (int): The primary key of the category.

    Returns:
        For a GET operation returns a Web View containing a form for altering
        data for the category.

        A successful POST request directs presents a View of the new Category.

    """
    # Only an Authenticated User can add edit a category.
    if isActiveSession() is False:
        return redirect(url_for("listItem"))

    editCategory = Category.query.filter_by(id=key).one()

    # Don't allow a user to change a category they don't 'own'
    if canAlter(editCategory.user_id) is False:
        return redirect(url_for("viewCategory", key=editCategory.id))

    # Process the Edit Form when it is Submitted.
    if request.method == "POST":

        editCategory.name = request.form["name"]

        session.add(editCategory)
        session.commit()

        flash("Category edited!")
        return redirect(url_for("viewCategory", key=key))

    else:
        return render_template(
            "generic.html",
            modelType="category",
            viewType=os.path.join("partials", "edit.html"),
            key=key,
            traits=editCategory.traits(),
            allowAlter=canAlter(editCategory.user_id),
        )
コード例 #7
0
ファイル: views.py プロジェクト: frost-byte/catalog
def deleteCategory(key):
    """Allow an Authorized User to delete a new Category or Process the
    deletion of a Category.

    Args:
        key (int): The primary key of the category.

    Returns:
        For a GET operation returns a View querying whether the user wants to
        delete the Category or cancel and go back to viewing it.

        A successful POST request deletes the Category and redirects to the
        list of Categories.

    """
    # Only an Authenticated User can add delete a category.
    if isActiveSession() is False:
        return redirect(url_for("listCategory"))

    deleteCategory = Category.query.filter_by(id=key).one()

    # If the logged in user did not create this Category then redirect.
    if canAlter(deleteCategory.user_id) is False:
        return redirect(url_for("viewCategory", key=deleteCategory.id))

    # Remove the Category from the Database
    if request.method == "POST":
        session.delete(deleteCategory)
        session.commit()

        flash("Category deleted!")
        # Back to the List of Categories
        return redirect(url_for("listCategory"))
    else:
        # Present options to Delete the Category or Cancel.
        return render_template(
            "generic.html",
            modelType="category",
            viewType=os.path.join("partials", "delete.html"),
            key=key,
            name=deleteCategory.name,
        )
コード例 #8
0
ファイル: views.py プロジェクト: frost-byte/catalog
def editUser(key):
    """Present the Web User with an Edit View for the their User account.

    Args:
        key (int): An ID corresponding to a User record in the database.

    Returns:
        For a GET operation returns a Web View containing a form for editing
        data for the user.

        A successful POST request directs presents the updated Record view.

    """
    # Require Authentication to Edit Users
    if isActiveSession() is False:
        return redirect(url_for("listCategory"))

    edUser = User.query.filter_by(id=key).one()

    # Don't allow a user to change other user records
    if canAlter(edUser.id) is False:
        return redirect(url_for("listItem"))

    # Process the Edit User form when submitted.
    if request.method == "POST":
        edUser.name = request.form["name"]

        session.add(edUser)
        session.commit()

        return redirect(url_for("viewUser", key=edUser.id))

    else:
        # Present the Edit User Form
        return render_template(
            "generic.html",
            modelType="user",
            viewType=os.path.join("partials", "edit.html"),
            key=key,
            traits=edUser.traits(),
        )
コード例 #9
0
ファイル: views.py プロジェクト: frost-byte/catalog
def deleteItem(key):
    """Delete an Item selected by its primary key/id.

    Requires a user to be authenticated and to have created the item.

    Args:
        key (int): The primary key of the Item to delete.

    Returns:
        A GET request presents the user with choices for deleting the Item or
        canceling the operation.
    """
    if isActiveSession() is False:
        flash("Please log in to delete an item.")
        return redirect(url_for("listItem"))

    deleteItem = Item.query.filter_by(id=key).one()

    if canAlter(deleteItem.user_id) is False:
        # The active user did not create the item.
        flash("You are not authorized to delete this item.")
        return redirect(url_for("viewItem", key=key))

    if request.method == "POST":
        # The user submitted this item for deletion.
        session.delete(deleteItem)
        session.commit()

        flash("Item deleted!")
        return redirect(url_for("listItem"))

    else:
        # Present the Deletion View to the User for the given Item/Category
        category = Category.query.filter_by(id=deleteItem.cat_id).one()

        return redirect(url_for("delItem", category_name=category.name, item_name=deleteItem.name))
コード例 #10
0
ファイル: views.py プロジェクト: frost-byte/catalog
def editItem(key):
    """Edit an Item in a Category.

    Requires a user to be authenticated and to have created the item.

    Args:
        key (int): The primary key of the Item to Edit.

    Returns:
        A GET request presents the user with a form for editing an Item.

        A POST request processes the user's input from the form and updates the
        item.

    """
    # User has been authenticated and the login_session is valid.
    if isActiveSession() is False:
        flash("You need to log in to edit items.")
        return redirect(url_for("listItem"))
    else:
        # Find the item to edit using its id.
        item = Item.query.filter_by(id=key).one()

        if request.method == "POST":
            # Make sure that an item associated with this category doesn't already have
            # the name of the one submitted in the form.
            category = Category.query.filter_by(name=request.form["category"]).one()

            itemName = str(request.form["name"])

            try:
                # We should find either zero or one item in a category with a given
                # name.
                items = Item.query.filter_by(cat_id=category.id, name=itemName).one_or_none()
                print "editItem: items = {0}".format(items)

            except MultipleResultsFound as e:
                # We found more than one item with the form's item name for
                # this category.
                print "Multiple " + e
                flash("{0} items named {1} in category {2} already.".format(len(items), itemName, category.name))
                return redirect(url_for("editItem", key=key))

            if items is None or items.id == key:
                # User can edit the item already in the category but can't move it
                # to another category that already has an item with the same name.

                # Different Image uploaded, Save and add url to Item record
                if request.files["upload"]:

                    item.picture = processImageUpload(request.files["upload"])

                item.name = itemName
                item.dateCreated = datetime.strptime(request.form["created"], "%Y-%m-%d")

                item.cat_id = category.id
                item.description = request.form["description"]

                session.add(item)
                session.commit()

                flash("Item edited!")

                return redirect(url_for("viewCatItem", category_name=category.name, item_name=item.name))
            else:
                flash(
                    """A different item named {0} already exists in the
                    category called {1}.""".format(
                        itemName, category.name
                    )
                )
                return redirect(url_for("editItem", key=key))

        else:
            category = Category.query.filter_by(id=item.cat_id).one()

            return redirect(url_for("editCatItem", category_name=category.name, item_name=item.name))
コード例 #11
0
ファイル: views.py プロジェクト: frost-byte/catalog
def newItem():
    """This route is used behind the scenes to view an item.  It forwards
    the request on to viewCatItem.  Requires a user to be authenticated.

    Notes:
        This route could be changed to reflect which category it will be in.

    Returns:
        A GET request presents the user with a form for creating a new Item.

        A POST request processes the user's input from the form and adds the
        new item.

    """
    # A user session must exist to add an item.
    if isActiveSession() is False:
        return redirect(url_for("listItem"))

    if request.method == "POST":
        # Process the new Item from the submitted form.
        # Make sure that an item associated with this category doesn't already have
        # the name of the one submitted in the form.
        category = Category.query.filter_by(name=request.form["category"]).one()

        newItemName = request.form["name"]

        try:
            # We should find either zero or one item in a category with a given
            # name.
            items = Item.query.filter_by(cat_id=category.id, name=newItemName).one_or_none()
            print "newItem: items = {0}".format(items)

        except MultipleResultsFound as e:
            # We more than one item with the newItemName in it's category.
            print "Multiple " + e
            flash("{0} items named {1} in {2} already.".format(len(items), newItemName, category.name))
            return redirect(url_for("viewCategory", key=category.id))

        if items is None:
            # This is a new Item for this category and it's name is unique
            # in the category.

            # Handle uploaded image
            picture = request.files["picture"]
            pictureUrl = processImageUpload(picture)

            # Create the New Item and add it to the Database
            newItem = Item(
                name=request.form["name"],
                dateCreated=datetime.strptime(request.form["created"], "%Y-%m-%d"),
                cat_id=category.id,
                description=request.form["description"],
                user_id=getSessionUserInfo()["id"],
                picture=pictureUrl,
            )

            session.add(newItem)
            session.flush()
            session.commit()

            flash("New item created!")
            # Present the user with a view of the new item
            return redirect(url_for("viewItem", key=newItem.id))

        else:
            # Alert the user to an already exisiting item with the specified name.
            flash("An item with the name {0} already exists in {1}.".format(newItemName, category.name))
            # Send the user back to the newItem Form.
            return redirect(url_for("newItem"))
    else:
        # Present the User with the New Item Form
        return render_template(
            "generic.html", modelType="item", viewType=os.path.join("partials", "new.html"), traits=Item.defaultTraits()
        )