Esempio n. 1
0
def items_xml():
    session = connect_to_database()
    categories = session.query(Category).all()

    root = Element('catalog')

    for category in categories:
        cat_tag = SubElement(root, 'category', {
            'id': str(category.id),
            'name': category.name
        })

        items = session.query(Item).filter_by(category=category).all()

        for item in items:
            item_tag = SubElement(cat_tag, 'item', {'id': str(item.id)})
            name_tag = SubElement(item_tag, 'name')
            name_tag.text = item.name
            desc_tag = SubElement(item_tag, 'description')
            desc_tag.text = item.description

    session.close()

    # Return the XML with a 2 space indent to make it more human readable.
    return parseString(tostring(root, 'utf-8')).toprettyxml(indent='  ')
def items_xml():
    """Returns all the items as an XML file.

    Research for this function came from:
        https://pymotw.com/2/xml/etree/ElementTree/create.html
    """
    session = connect_to_database()
    categories = session.query(Category).all()

    root = Element('catalog')

    for category in categories:
        cat_tag = SubElement(root,
                             'category',
                             {'id':str(category.id), 'name':category.name})

        items = session.query(Item).filter_by(category=category).all()

        for item in items:
            item_tag = SubElement(cat_tag, 'item', {'id':str(item.id)})
            name_tag = SubElement(item_tag, 'name')
            name_tag.text = item.name
            desc_tag = SubElement(item_tag, 'description')
            desc_tag.text = item.description
            desc_tag = SubElement(item_tag, 'quantity')
            desc_tag.text = str(item.quantity)

    session.close()

    # Return the XML with a 2 space indent to make it more human readable.
    return parseString(tostring(root, 'utf-8')).toprettyxml(indent='  ')
Esempio n. 3
0
def show_items(category_name):
    """Show items belonging to a specified category.

    Args:
        category_name (str): The name of the category to which the item
            belongs.

    Returns:
        A web page showing all the items in the specified category.
    """
    session = connect_to_database()
    try:
        category = session.query(Category).filter_by(name=category_name).one()
    except NoResultFound:
        flash("The category '%s' does not exist." % category_name)
        return redirect(url_for('show_homepage'))

    categories = session.query(Category).all()
    items = (session.query(Item).filter_by(category=category).
             order_by(Item.name).all())
    session.close()
    if not items:
        flash("There are currently no pages in this category.")
    return render_template('items.html',
                           categories=categories,
                           category=category,
                           items=items)
def items_xml():
    """Returns all the items as an XML file.

    Research for this function came from:
        https://pymotw.com/2/xml/etree/ElementTree/create.html
    """
    session = connect_to_database()
    categories = session.query(Category).all()

    root = Element('catalog')

    for category in categories:
        cat_tag = SubElement(root, 'category', {
            'id': str(category.id),
            'name': category.name
        })

        items = session.query(Item).filter_by(category=category).all()

        for item in items:
            item_tag = SubElement(cat_tag, 'item', {'id': str(item.id)})
            name_tag = SubElement(item_tag, 'name')
            name_tag.text = item.name
            desc_tag = SubElement(item_tag, 'description')
            desc_tag.text = item.description
            desc_tag = SubElement(item_tag, 'quantity')
            desc_tag.text = str(item.quantity)

    session.close()

    # Return the XML with a 2 space indent to make it more human readable.
    return parseString(tostring(root, 'utf-8')).toprettyxml(indent='  ')
Esempio n. 5
0
def show_items(category_name):
    """Show items belonging to a specified category.

    Args:
        category_name (str): The name of the category to which the item
            belongs.

    Returns:
        A web page showing all the items in the specified category.
    """
    session = connect_to_database()
    try:
        category = session.query(Category).filter_by(name=category_name).one()
    except NoResultFound:
        flash("The category '%s' does not exist." % category_name)
        return redirect(url_for('show_homepage'))

    categories = session.query(Category).all()
    items = (session.query(Item).filter_by(category=category).order_by(
        Item.name).all())
    session.close()
    if not items:
        flash("There are currently no vehicles in this category.")
    return render_template('items.html',
                           categories=categories,
                           category=category,
                           items=items)
def create_user():
    """Create a new user in the database."""
    new_user = User(name=login_session['username'],
                    email=login_session['email'],
                    picture=login_session['picture'])
    session = connect_to_database()
    session.add(new_user)
    session.commit()
    user = session.query(User).filter_by(email=login_session['email']).one()
    session.close()
    return user.id
Esempio n. 7
0
def create_user():
    """Create a new user in the database."""
    new_user = User(name=login_session['username'],
                    email=login_session['email'],
                    picture=login_session['picture'])
    session = connect_to_database()
    session.add(new_user)
    session.commit()
    user = session.query(User).filter_by(email=login_session['email']).one()
    session.close()
    return user.id
Esempio n. 8
0
def item_json(item_name, category_name=None):
    session = connect_to_database()
    try:
        item = session.query(Item).filter_by(name=item_name).one()
    except NoResultFound:
        session.close()
        flash("JSON error: The item '%s' does not exist." % item_name)
        return redirect(url_for('show_homepage'))

    session.close()
    return jsonify(Item=item.serialise)
def show_login():
    """Show the login screen to the user."""
    # Create a state token to prevent request forgery.
    state = ''.join(random.choice(string.ascii_uppercase + string.digits)
                    for x in xrange(32))
    login_session['state'] = state

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

    return render_template('login.html', STATE=state, categories=categories)
Esempio n. 10
0
def items_json():
    """Returns all the items in the catalog as a JSON file.

    The for loop in the call to jsonify() goes through each category and,
    because the Category class has a reference to the items in it, for each
    item a call to its serialise function is made. So we end up with a JSON
    array of items for each category.
    """
    session = connect_to_database()
    categories = session.query(Category).all()
    serialised_catergories = [i.serialise for i in categories]
    session.close()
    return jsonify(Category=serialised_catergories)
Esempio n. 11
0
def show_login():
    """Show the login screen to the user."""
    # Create a state token to prevent request forgery.
    state = ''.join(
        random.choice(string.ascii_uppercase + string.digits)
        for x in xrange(32))
    login_session['state'] = state

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

    return render_template('login.html', STATE=state, categories=categories)
Esempio n. 12
0
def show_homepage():
    """Show the homepage displaying the categories and latest items.

    Returns:
        A web page with the 10 latest items that have added.
    """
    session = connect_to_database()
    categories = session.query(Category).all()
    latest_items = session.query(Item).order_by(desc(Item.id))[0:10]
    session.close()
    return render_template('homepage.html',
                           categories=categories,
                           latest_items=latest_items)
Esempio n. 13
0
def show_homepage():
    """Show the homepage displaying the categories and latest items.

    Returns:
        A web page with the 10 latest items that have added.
    """
    session = connect_to_database()
    categories = session.query(Category).all()
    latest_items = session.query(Item).order_by(desc(Item.id))[0:10]
    session.close()
    return render_template('homepage.html',
                           categories=categories,
                           latest_items=latest_items)
Esempio n. 14
0
def get_user_id(email):
    """Given an email address, return the user ID, if in the database.

    Args:
        email (str): The email address associated with the user account.

    Returns:
        The user id number stored in the database.
    """
    session = connect_to_database()
    try:
        user = session.query(User).filter_by(email=email).one()
        session.close()
        return user.id
    except NoResultFound:
        session.close()
        return None
Esempio n. 15
0
def delete_item(item_name):
    """Delete a specified item from the database.

    Args:
        item_name (str): Name of the item to be deleted.
    """
    if 'username' not in login_session:
        return redirect('/login')

    session = connect_to_database()

    try:
        item = session.query(Item).filter_by(name=item_name).one()
    except NoResultFound:
        flash("Error: The item '%s' does not exist." % item_name)
        session.close()
        return redirect(url_for('show_homepage'))

    if login_session['user_id'] != item.user_id:
        flash("You didn't add this Course, so you can't delete it. Sorry :-(")
        category = session.query(Category).filter_by(id=item.category_id).one()
        category_name = category.name
        item_name = item.name
        session.close()
        return redirect(
            url_for('show_item',
                    category_name=category_name,
                    item_name=item_name))

    if request.method == 'POST':
        if item.image_filename:
            delete_image(item.image_filename)
        session.delete(item)
        session.commit()
        category = session.query(Category).filter_by(id=item.category_id).one()

        flash("Course successfully deleted!")
        category_name = category.name
        session.close()
        return redirect(url_for('show_items', category_name=category_name))
    else:
        categories = session.query(Category).all()
        session.close()
        return render_template('delete_item.html',
                               categories=categories,
                               item=item)
Esempio n. 16
0
def show_login():
    """Show the login screen to the user."""
    # Create a state token to prevent request forgery.
    # You are trying to run a Python 2 codebase with Python 3. xrange() was renamed to range() in Python 3
    # https://stackoverflow.com/questions/17192158/nameerror-global-name-xrange-is-not-defined-in-python-3
    # state = ''.join(random.choice(string.ascii_uppercase + string.digits)
    #                for x in xrange(32))
    state = ''.join(
        random.choice(string.ascii_uppercase + string.digits)
        for x in range(32))
    login_session['state'] = state

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

    return render_template('login.html', STATE=state, categories=categories)
Esempio n. 17
0
def show_my_items():
    """If logged in, show the user the items they have added."""
    if 'username' not in login_session:
        return redirect('/login')

    user_id = get_user_id(login_session['email'])

    session = connect_to_database()
    categories = session.query(Category).all()
    items = session.query(Item).filter_by(user_id=user_id).all()
    session.close()

    if not items:
        flash("You haven't add any vehicles yet.")
        redirect(url_for('show_homepage'))

    return render_template('my_items.html', categories=categories, items=items)
Esempio n. 18
0
def get_user_id(email):
    """Given an email address, return the user ID, if in the database.

    Args:
        email (str): The email address associated with the user account.

    Returns:
        The user id number stored in the database.
    """
    session = connect_to_database()
    try:
        user = session.query(User).filter_by(email=email).one()
        session.close()
        return user.id
    except NoResultFound:
        session.close()
        return None
Esempio n. 19
0
def delete_item(item_name):
    """Delete a specified item from the database.

    Args:
        item_name (str): Name of the item to be deleted.
    """
    if 'username' not in login_session:
        return redirect('/login')

    session = connect_to_database()

    try:
        item = session.query(Item).filter_by(name=item_name).one()
    except NoResultFound:
        flash("Error: The item '%s' does not exist." % item_name)
        session.close()
        return redirect(url_for('show_homepage'))

    if login_session['user_id'] != item.user_id:
        flash("You didn't add this paper, so you can't delete it. Sorry :-(")
        category = session.query(Category).filter_by(id=item.category_id).one()
        category_name = category.name
        item_name = item.name
        session.close()
        return redirect(url_for('show_item',
                                category_name=category_name,
                                item_name=item_name))

    if request.method == 'POST':
        if item.image_filename:
            delete_image(item.image_filename)
        session.delete(item)
        session.commit()
        category = session.query(Category).filter_by(id=item.category_id).one()

        flash("Paper successfully deleted!")
        category_name = category.name
        session.close()
        return redirect(url_for('show_items', category_name=category_name))
    else:
        categories = session.query(Category).all()
        session.close()
        return render_template('delete_item.html',
                               categories=categories,
                               item=item)
Esempio n. 20
0
def item_json(item_name, category_name=None):
    """Returns a single item in a JSON file.

    Args:
        item_name (str): The name of the item to return in JSON format.
        category_name (str): A dummy variable used so that the path can
            optionally include the category name.
    """
    session = connect_to_database()
    try:
        item = session.query(Item).filter_by(name=item_name).one()
    except NoResultFound:
        session.close()
        flash("JSON error: The item '%s' does not exist." % item_name)
        return redirect(url_for('show_homepage'))

    session.close()
    return jsonify(Item=item.serialise)
Esempio n. 21
0
def show_my_items():
    """If logged in, show the user the items they have added."""
    if 'username' not in login_session:
        return redirect('/login')

    user_id = get_user_id(login_session['email'])

    session = connect_to_database()
    categories = session.query(Category).all()
    items = session.query(Item).filter_by(user_id=user_id).all()
    session.close()

    if not items:
        flash("You haven't added any papers  yet.")
        redirect(url_for('show_homepage'))

    return render_template('my_items.html',
                           categories=categories,
                           items=items)
Esempio n. 22
0
def show_item(category_name, item_name):
    """Show details of a particular item belonging to a specified category.

    Args:
        category_name (str): The name of the category to which the item
            belongs.
        item_name (str): The name of the item.

    Returns:
        A web page showing information of the requested item.
    """
    session = connect_to_database()
    try:
        category = session.query(Category).filter_by(name=category_name).one()
    except NoResultFound:
        flash("The category '%s' does not exist." % category_name)
        session.close()
        return redirect(url_for('show_homepage'))

    try:
        item = session.query(Item).filter_by(name=item_name).one()
    except NoResultFound:
        flash("The item '%s' does not exist." % item_name)
        session.close()
        return redirect(url_for('show_items', category_name=category_name))

    user = session.query(User).filter_by(id=item.user_id).one()
    owner_name = user.name

    categories = session.query(Category).all()
    session.close()
    return render_template('item.html',
                           categories=categories,
                           category=category,
                           item=item,
                           owner_name=owner_name)
Esempio n. 23
0
def show_item(category_name, item_name):
    """Show details of a particular item belonging to a specified category.

    Args:
        category_name (str): The name of the category to which the item
            belongs.
        item_name (str): The name of the item.

    Returns:
        A web page showing information of the requested item.
    """
    session = connect_to_database()
    try:
        category = session.query(Category).filter_by(name=category_name).one()
    except NoResultFound:
        flash("The category '%s' does not exist." % category_name)
        session.close()
        return redirect(url_for('show_homepage'))

    try:
        item = session.query(Item).filter_by(name=item_name).one()
    except NoResultFound:
        flash("The item '%s' does not exist." % item_name)
        session.close()
        return redirect(url_for('show_items', category_name=category_name))

    user = session.query(User).filter_by(id=item.user_id).one()
    ower_name = user.name

    categories = session.query(Category).all()
    session.close()
    return render_template('item.html',
                           categories=categories,
                           category=category,
                           item=item,
                           ower_name=ower_name)
Esempio n. 24
0
def items_json():
    session = connect_to_database()
    categories = session.query(Category).all()
    serialised_catergories = [i.serialise for i in categories]
    session.close()
    return jsonify(Category=serialised_catergories)
Esempio n. 25
0
def edit_item(item_name, category_name=None):
    """Edit the details of the specified item.

    Args:
        item_name (str): Name of item to be edited.
        category_name (str): Optionally, can also specify the category to
            which the item belongs to.
    """
    if 'username' not in login_session:
        flash("You need to login to edit any papers.")
        return redirect('/login')

    session = connect_to_database()

    try:
        item = session.query(Item).filter_by(name=item_name).one()
    except NoResultFound:
        flash("Error: The item '%s' does not exist." % item_name)
        return redirect(url_for('show_homepage'))

    if login_session['user_id'] != item.user_id:
        flash("You didn't add this paper, so you can't edit it. Sorry :-(")
        category = session.query(Category).filter_by(id=item.category_id).one()
        category_name = category.name
        item_name = item.name
        session.close()
        return redirect(url_for('show_item',
                                category_name=category_name,
                                item_name=item_name))

    if request.method == 'POST':
        if request.form['name'] != item.name:
            # Enforce rule that item names are unique
            qry = session.query(Item).filter(Item.name == request.form['name'])
            already_exists = (session.query(literal(True)).filter(qry.exists())
                              .scalar())
            if already_exists is True:
                original_category = (session.query(Category)
                                     .filter_by(id=item.category_id).one())
                flash("Error: There is already a paper with the name '%s'"
                      % request.form['name'])
                session.close()
                return redirect(url_for('show_items',
                                        category_name=original_category.name))
            item.name = request.form['name']

        form_category = (session.query(Category)
                         .filter_by(name=request.form['category']).one())
        if form_category != item.category:
            item.category = form_category

        item.description = request.form['description']
        item.quantity = request.form['quantity']

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

            item.image_filename = filename
            item.image_url = None

        elif ('delete_image' in request.form and
              request.form['delete_image'] == 'delete'):
            if item.image_filename:
                delete_image(item.image_filename)
                item.image_filename = None

        if not image_file and request.form['image_url']:
            item.image_url = request.form['image_url']
            if item.image_filename:
                delete_image(item.image_filename)
                item.image_filename = None

        session.add(item)
        session.commit()

        flash("Paper successfully edited!")
        category_name = form_category.name
        item_name = item.name
        session.close()
        return redirect(url_for('show_item',
                                category_name=category_name,
                                item_name=item_name))
    else:
        categories = session.query(Category).all()
        session.close()
        return render_template('edit_item.html',
                               categories=categories,
                               item=item)
Esempio n. 26
0
def populate_database():
    """Populate the item catalog database some initial content."""
    session = connect_to_database()

    # Make sure the database is empty before running this inital data dump.
    category_count = session.query(func.count(Category.id)).scalar()
    if category_count > 0:
        session.close()
        return

    # Create the six categories animals fall in to.
    category1 = Category(
        name="HTML&CSS",
        about=
        "HyperText Markup Language (HTML) is a markup language for creating webpages. Webpages are usually viewed in a web browser. They can include writing, links, pictures, and even sound and video. HTML is used to mark and describe each of these kinds of content so the web browser can show them correctly.",
        linkCat="https://www.w3.org/html/",
        linkCat2="https://www.w3.org/Style/CSS/",
        imageCat="fab fa-html5",
        imageCat2="fab fa-css3-alt")
    session.add(category1)
    session.commit()

    category2 = Category(
        name="JavaScript",
        about=
        "JavaScript (JS) is a lightweight interpreted or JIT-compiled programming language with first-class functions. While it is most well-known as the scripting language for Web pages, many non-browser environments also use it, such as Node.js, Apache CouchDB and Adobe Acrobat. JavaScript is a prototype-based, multi-paradigm, dynamic language, supporting object-oriented, imperative, and declarative (e.g. functional programming) styles",
        linkCat="https://developer.mozilla.org/en-US/docs/Web/JavaScript",
        imageCat="fab fa-js-square")
    session.add(category2)
    session.commit()

    category3 = Category(
        name="React.js",
        about=
        "React is a JavaScript library for building user interfaces. It is maintained by Facebook and a community of individual developers and corporations.",
        linkCat="https://reactjs.org/",
        imageCat="fab fa-react")
    session.add(category3)
    session.commit()

    category4 = Category(
        name="Node.js",
        about=
        "Node.js is an open-source, cross-platform JavaScript run-time environment that executes JavaScript code server-side.",
        linkCat="https://nodejs.org/",
        imageCat="fab fa-node")
    session.add(category4)
    session.commit()

    category5 = Category(
        name="Python",
        about=
        "Python is an interpreted high-level programming language for general-purpose programming. Created by Guido van Rossum and first released in 1991, Python has a design philosophy that emphasizes code readability, notably using significant whitespace.",
        linkCat="https://www.python.org/",
        imageCat="fab fa-python")
    session.add(category5)
    session.commit()

    category6 = Category(
        name="APIs",
        about=
        "API is a set of subroutine definitions, protocols, and tools for building application software."
    )
    session.add(category6)
    session.commit()

    category7 = Category(
        name="Databases",
        about=
        "A database is an organized collection of data. A relational database, more restrictively, is a collection of schemas, tables, queries, reports, views, and other elements.",
        imageCat="fas fa-database")
    session.add(category7)
    session.commit()

    category8 = Category(
        name="OAuth",
        about=
        "OAuth (Open Authorization) is an open standard for token-based authentication and authorization on the Internet. OAuth, which is pronounced oh-auth, allows an end user's account information to be used by third-party services, such as Facebook, without exposing the user's password.",
        linkCat="https://oauth.net")
    session.add(category8)
    session.commit()

    category9 = Category(
        name="Git",
        about=
        "Git is a version control system for tracking changes in computer files and coordinating work on those files among multiple people.",
        linkCat="https://git-scm.com/",
        imageCat="fab fa-git")
    session.add(category9)
    session.commit()

    # Create a  user for these initial items
    user1 = User(name="Irina Serova", email="*****@*****.**")
    session.add(user1)
    session.commit()

    # Create some items
    item1 = Item(
        user=user1,
        category=category1,
        name="Learn HTML",
        description=
        ("Learn the basics of HTML with this interactive Codecademy course. The introduction here gives an overview of the structure, purpose, and syntax of the language."
         ),
        duration="2 to 4 hours",
        level="BEGINNER",
        image_url=
        "https://production.cdmycdn.com/webpack/3d7c19cebe85b8d870e6d2c181dec922.svg",
        link="https://www.codecademy.com/learn/learn-html")
    session.add(item1)
    session.commit()

    item2 = Item(
        user=user1,
        category=category1,
        name="Learn CSS",
        description=(
            "Elephants are large mammals of the family Elephantidae and the "
            "order Proboscidea. Two species are traditionally recognised, the "
            "African elephant and the Asian elephant, although some evidence "
            "suggests that African bush elephants and African forest elephants "
            "are separate species."),
        duration="8 to 16 hours",
        level="INTERMEDIATE",
        image_url=
        "https://production.cdmycdn.com/webpack/9522085449ef048604ca3f5fa8d1bc27.svg",
        link="https://www.codecademy.com/learn/learn-css")
    session.add(item2)
    session.commit()

    item3 = Item(
        user=user1,
        category=category2,
        name="Learn JavaScript",
        description=
        ("Learn the fundamentals of JavaScript, the programming language of the web."
         ),
        duration="4 to 8 hours",
        level="INTERMEDIATE",
        image_url=
        "https://production.cdmycdn.com/webpack/fbac2e163a79bceb56b5dbabe6c74945.png",
        link="https://www.codecademy.com/learn/learn-javascript")
    session.add(item3)
    session.commit()

    item5 = Item(
        user=user1,
        category=category3,
        name="Learn ReactJS: Part I",
        description=
        ("Continue your learning by starting with Learn ReactJS: Part I Build powerful interactive applications with this popular JavaScript library."
         ),
        duration="8 to 16 hours",
        level="INTERMEDIATE",
        image_url=
        "https://production.cdmycdn.com/webpack/d38587f67ab102541186df1c157597d1.svg",
        link="https://www.codecademy.com/learn/react-101")
    item4 = Item(
        user=user1,
        category=category4,
        name="NODESCHOOL",
        description=
        ("Open source workshops that teach web software skills. Do them on your own or at a workshop nearby."
         ),
        duration="8 to 16 hours",
        level="INTERMEDIATE",
        image_url="https://nodeschool.io/images/schoolhouse.svg",
        link="https://nodeschool.io")
    session.add(item4)
    session.commit()

    session.add(item5)
    session.commit()

    item6 = Item(
        user=user1,
        category=category5,
        name="Python",
        description=
        ("Learn Python fundamentals that set you up to work in web development and machine learning."
         ),
        duration="8 to 16 hours",
        level="INTERMEDIATE",
        image_url=
        "https://production.cdmycdn.com/webpack/4bef5020e69a6464ebd9dabe087cb809.svg",
        link="https://www.codecademy.com/learn/learn-python")
    session.add(item6)
    session.commit()

    item7 = Item(
        user=user1,
        category=category6,
        name="Learn API!",
        description=("Learn how to use the YouTube API!"),
        duration="8 to 16 hours",
        level="BEGINNER",
        image_url=
        "https://s3.amazonaws.com/codecademy-production/original/50ecea3ba778dddcd50001d2_871712554.png",
        link="https://www.codecademy.com/en/tracks/youtube")
    session.add(item7)
    session.commit()

    item8 = Item(
        user=user1,
        category=category7,
        name="Getting Started with PostgreSQL on Mac OSX",
        description=
        ("This tutorial will teach you how to set up, configure, and use PostgreSQL on MacOSX 10.7 (Lion) and above. You will need at least a basic level of comfort using the command line using either the MacOSX built-in terminal, iTerm2, Zsh, or something similar."
         ),
        duration="to 1 hour",
        level="BEGINNER",
        image_url=
        "https://process.filestackapi.com/cache=expiry:max/resize=width:1050/compress/Vx31ILRQRSO5fBiMSvEg",
        link=
        "https://www.codementor.io/engineerapart/getting-started-with-postgresql-on-mac-osx-are8jcopb"
    )
    session.add(item8)
    session.commit()

    # Create some amphibians
    item9 = Item(
        user=user1,
        category=category8,
        name="OAuth2 with GitHub",
        description=("Learn OAuth2 with the GitHub API"),
        duration="2 to 4 hours",
        level="BEGINNER",
        image_url=
        "https://process.filestackapi.com/cache=expiry:max/resize=width:1050/compress/Vx31ILRQRSO5fBiMSvEg",
        link=
        "https://www.codementor.io/engineerapart/getting-started-with-postgresql-on-mac-osx-are8jcopb"
    )
    session.add(item9)
    session.commit()

    item10 = Item(
        user=user1,
        category=category9,
        name="Learn Version Control with Git",
        description=("A step-by-step course for the complete beginner"),
        duration="to 1 hour",
        level="BEGINNER",
        image_url=
        "https://tower-website-ftkdppxp1xaznovg.netdna-ssl.com/learn/assets/img/keyvisual/ebook_dark.1527173730.png",
        link=
        "https://www.git-tower.com/learn/git/ebook/en/command-line/appendix/best-practices"
    )
    session.add(item10)
    session.commit()

    item11 = Item(
        user=user1,
        category=category2,
        name="Javascript",
        description=
        ("Make your websites dynamic and interactive with JavaScript! You'll create features and stand-alone applications. This course will wrap everything you've learned at The Odin Project into one, final capstone project. 30 lessons"
         ),
        duration="16 to 32 hours",
        level="BEGINNER",
        image_url=
        "https://www.theodinproject.com/assets/home-isometric-60f02f572fa9ae583a22bf4d391e48f30cae707cbdb602e130bc3f12d73bac85.svg",
        link="https://www.theodinproject.com/courses/javascript")
    session.add(item11)
    session.commit()

    item12 = Item(
        user=user1,
        category=category3,
        name="Start Learning React",
        description=
        ("This series will explore the basic fundamentals of React to get you started."
         ),
        duration="2 to 4 hours",
        level="BEGINNER",
        image_url=
        "https://d2eip9sf3oo6c2.cloudfront.net/series/square_covers/000/000/003/full/course_image.png",
        link="https://egghead.io/courses/start-learning-react")
    session.add(item12)
    session.commit()

    item13 = Item(
        user=user1,
        category=category4,
        name="Node JS Training and Fundamentals",
        description=
        ("Node basics and fundamentals to make you ready to create any web app using express, jade and node modules."
         ),
        duration="4 to 8 hours",
        level="BEGINNER",
        image_url=
        "https://udemy-images.udemy.com/course/480x270/595294_bc81.jpg",
        link=
        "https://www.udemy.com/node-js-training-and-fundamentals/?siteID=Fh5UMknfYAU-TkergXOKdpODeZTt.miTZw&LSNPUBID=Fh5UMknfYAU"
    )
    session.add(item13)
    session.commit()

    item14 = Item(
        user=user1,
        category=category5,
        name="Python for Beginners with Examples",
        description=
        ("A practical Python course for beginners with examples and exercises."
         ),
        duration="4 to 8 hours",
        level="BEGINNER",
        image_url=
        "https://udemy-images.udemy.com/course/480x270/577248_3b6f_12.jpg",
        link=
        "https://www.udemy.com/ardit-sulce-python-for-beginners/?siteID=Fh5UMknfYAU-XQ5mHVXoiEA5LjPQW.xmAg&LSNPUBID=Fh5UMknfYAU"
    )
    session.add(item14)
    session.commit()

    item15 = Item(
        user=user1,
        category=category6,
        name="Laravel E-Commerce Restful API",
        description=
        ("Know what is Rest concept and how to create a RESTFUL API with Laravel Resource"
         ),
        duration="32 to 64 hours",
        level="INTERMEDIATE",
        image_url=
        "https://udemy-images.udemy.com/course/480x270/1470550_2d1e.jpg",
        link=
        "https://www.udemy.com/ardit-sulce-python-for-beginners/?siteID=Fh5UMknfYAU-XQ5mHVXoiEA5LjPQW.xmAg&LSNPUBID=Fh5UMknfYAU"
    )
    session.add(item15)
    session.commit()

    item16 = Item(
        user=user1,
        category=category7,
        name="Creating Programmatic SQL Database Objects",
        description=
        ("Learn how to add functionality to your database with programmatic database objects using the R programming language."
         ),
        duration="8 to 16 hours",
        level="INTERMEDIATE",
        image_url=
        "https://prod-discovery.edx-cdn.org/media/course/image/d471fec7-5d9d-45f1-b622-af86a31064be-6fe9a510bf23.small.jpg",
        link=
        "https://www.edx.org/course/creating-programmatic-sql-database-objects?source=aw&awc=6798_1528876589_9c64f89577cb3b4983eebd3c02c6f2e2"
    )
    session.add(item16)
    session.commit()

    item17 = Item(
        user=user1,
        category=category8,
        name="OAuth 2.0 Tutorial",
        description=
        ("This tutorial series explains how OAuth 2.0, the open authorization protocol, works."
         ),
        duration="4 to 8 hours",
        level="BEGINNER",
        image_url="http://tutorials.jenkov.com/images/oauth2/introduction.png",
        link="http://tutorials.jenkov.com/oauth2/index.html")
    session.add(item17)
    session.commit()

    item18 = Item(
        user=user1,
        category=category9,
        name="How to Use Git and GitHub",
        description=
        ("This course, built with input from GitHub, will introduce the basics of using version control by focusing on a particular version control system called Git and a collaboration platform called GitHub."
         ),
        duration="8 to 16 hours",
        level="BEGINNER",
        image_url=
        "https://res.cloudinary.com/db194k5td/image/upload/v1510723267/git_logo_tjnjxd.svg",
        link="https://in.udacity.com/course/how-to-use-git-and-github--ud775")
    session.add(item18)
    session.commit()

    session.close()

    print "Populated database..."
Esempio n. 27
0
def create_item():
    """Allow users to create a new item in the catalog."""
    if 'username' not in login_session:
        return redirect('/login')

    session = connect_to_database()

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

        if request.form['name'] == "items":
            # Can't have an item called "items" as this is a route.
            flash("Error: Can't have a paper called 'items'.")
            return redirect(url_for('show_homepage'))

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

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

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

        elif request.form['image_url']:
            new_item.image_url = request.form['image_url']

        session.add(new_item)
        session.commit()

        flash("New paper successfully added!")
        category_name = category.name
        item_name = new_item.name
        session.close()
        return redirect(url_for('show_item',
                                category_name=category_name,
                                item_name=item_name))
    else:
        categories = session.query(Category).all()

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

        session.close()
        return render_template('new_item.html',
                               categories=categories,
                               ref_category=ref_category)
Esempio n. 28
0
def populate_database():
    """Populate the item catalog database some initial content."""
    session = connect_to_database()

    # Make sure the database is empty before running this inital data dump.
    category_count = session.query(func.count(Category.id)).scalar()
    if category_count > 0:
        session.close()
        return

    # Create the six categories animals fall in to.
    category1 = Category(name="Mammals")
    session.add(category1)
    session.commit()

    category2 = Category(name="Birds")
    session.add(category2)
    session.commit()

    category3 = Category(name="Fish")
    session.add(category3)
    session.commit()

    category4 = Category(name="Reptiles")
    session.add(category4)
    session.commit()

    category5 = Category(name="Amphibians")
    session.add(category5)
    session.commit()

    category6 = Category(name="Arthropods")
    session.add(category6)
    session.commit()

    # Create a dummy user for these initial items
    user1 = User(name="Bob Fossil", email="*****@*****.**")
    session.add(user1)
    session.commit()

    # Create some mammals
    item1 = Item(
        user=user1,
        category=category1,
        name="Polar Bear",
        description=(
            "The polar bear is a carnivorous bear whose native range lies "
            "largely within the Arctic Circle, encompassing the Arctic Ocean, "
            "its surrounding seas and surrounding land masses. It is a large "
            "bear, approximately the same size as the omnivorous Kodiak bear."
        ),
        quantity=3,
        image_url="https://upload.wikimedia.org/wikipedia/commons/6/66/Polar_Bear_-_Alaska_(cropped).jpg"
    )
    session.add(item1)
    session.commit()

    item2 = Item(
        user=user1,
        category=category1,
        name="Elephant",
        description=(
            "Elephants are large mammals of the family Elephantidae and the "
            "order Proboscidea. Two species are traditionally recognised, the "
            "African elephant and the Asian elephant, although some evidence "
            "suggests that African bush elephants and African forest elephants "
            "are separate species."
        ),
        quantity=4,
        image_url="http://res.freestockphotos.biz/pictures/10/10004-an-elephant-in-the-wild-pv.jpg"

    )
    session.add(item2)
    session.commit()

    # Create some Birds
    item3 = Item(
        user=user1,
        category=category2,
        name="Kingfisher",
        description=(
            "Kingfishers are a group of small to medium-sized brightly colored "
            "birds in the order Coraciiformes. There are roughly 90 species of "
            "kingfisher. All have large heads, long, sharp, pointed bills, "
            "short legs, and stubby tails. Most species have bright plumage "
            "with little differences between the sexes."
        ),
        quantity=2,
        image_url="https://upload.wikimedia.org/wikipedia/commons/d/de/Common_Kingfisher_(Alcedo_atthis_taprobana)_-_Male_-_Flickr_-_Lip_Kee.jpg"
    )
    session.add(item3)
    session.commit()

    item4 = Item(
        user=user1,
        category=category2,
        name="Blue Tit",
        description=(
            "The Eurasian blue tit is a small passerine bird in the tit family "
            "Paridae. The bird is easily recognisable by its blue and yellow "
            "plumage, but various authorities dispute their scientific "
            "classification."
        ),
        quantity=7,
        image_url="https://upload.wikimedia.org/wikipedia/commons/6/65/Blue_Tit_-_flickr.jpg"
    )
    session.add(item4)
    session.commit()

    # Create some fish
    item5 = Item(
        user=user1,
        category=category3,
        name="Swordfish",
        description=(
            "Swordfish, also known as broadbills in some countries, are large, "
            "highly migratory, predatory fish characterized by a long, flat "
            "bill. They are a popular sport fish of the billfish category, "
            "though elusive. Swordfish are elongated, round-bodied, and lose "
            "all teeth and scales by adulthood."
        ),
        quantity=4,
        image_url="https://upload.wikimedia.org/wikipedia/commons/f/f6/Xiphias_gladius2.jpg"
    )
    session.add(item5)
    session.commit()

    item6 = Item(
        user=user1,
        category=category3,
        name="Whale Shark",
        description=(
            "The whale shark is a slow-moving filter feeding shark and the "
            "largest known extant fish species. The largest confirmed "
            "individual had a length of 12.65 m (41.50 ft) and a weight of "
            "about 21.5 metric tons (47,000 lb), and unconfirmed reports of "
            "considerably larger whale sharks exist. Claims of individuals "
            "over 14 m (46 ft) long and weighing at least 30 metric tons "
            "(66,000 lb) are not uncommon."
        ),
        quantity=1,
        image_url="https://upload.wikimedia.org/wikipedia/commons/thumb/5/57/Male_whale_shark_at_Georgia_Aquarium_crop.jpg/1024px-Male_whale_shark_at_Georgia_Aquarium_crop.jpg"
    )
    session.add(item6)
    session.commit()

    # Create some reptiles
    item7 = Item(
        user=user1,
        category=category4,
        name="Saltwater Crocodile",
        description=(
            "The saltwater crocodile  is the largest of all living reptiles, "
            "as well as the largest terrestrial and riparian predator in the "
            "world. The males of this species can reach sizes up to 6.3 m "
            "(20.7 ft) and weigh up to 1,360 kg (3,000 lb). However, an adult "
            "male saltwater crocodile is generally between 4.3 and 5.2 m (14 "
            "and 17 ft) in length and weighs 400 to 1,000 kg (880-2,200 lb), "
            "rarely growing larger."
        ),
        quantity=2,
        image_url="https://upload.wikimedia.org/wikipedia/commons/thumb/3/35/Saltwater_crocodile.jpg/640px-Saltwater_crocodile.jpg"
    )
    session.add(item7)
    session.commit()

    item8 = Item(
        user=user1,
        category=category4,
        name="Burmese Python",
        description=(
            "The Burmese python is one of the five largest species of snakes "
            "in the world (about the third-largest as measured either by "
            "length or weight). It is native to a large variation of tropic "
            "and subtropic areas of South and Southeast Asia. Until 2009, it "
            "was considered a subspecies of Python molurus, but now is "
            "recognized as belonging to a distinct species."
        ),
        quantity=2,
        image_url="https://upload.wikimedia.org/wikipedia/commons/thumb/6/62/Burmese_Python_02.jpg/640px-Burmese_Python_02.jpg"
    )
    session.add(item8)
    session.commit()

    # Create some amphibians
    item9 = Item(
        user=user1,
        category=category5,
        name="Golden Poison Frog",
        description=(
            "The golden poison frog, also known as the golden frog, golden "
            "poison arrow frog, or golden dart frog, is a poison dart frog "
            "endemic to the Pacific coast of Colombia. Its optimal habitat is "
            "the rainforest with high rain rates (5 m or more per year), "
            "altitudes between 100 and 200 m, temperatures of at least 26C, "
            "and relative humidity of 80-90%."
        ),
        quantity=2,
        image_url="https://upload.wikimedia.org/wikipedia/commons/9/9a/Phyllobates_terribilis_climbing_on_leaves.png"
    )
    session.add(item9)
    session.commit()

    item10 = Item(
        user=user1,
        category=category5,
        name="Glass Frog",
        description=(
            "The glass frogs (or glassfrogs) are frogs of the amphibian family "
            "Centrolenidae (order Anura). While the general background "
            "coloration of most glass frogs is primarily lime green, the "
            "abdominal skin of some members of this family is translucent. The "
            "internal viscera, including the heart, liver, and "
            "gastrointestinal tract, are visible through the skin, hence the "
            "common name."
        ),
        quantity=4,
        image_url="https://c1.staticflickr.com/7/6143/5991036083_b2a7f8d894_b.jpg"
    )
    session.add(item10)
    session.commit()

    # Create some arthropods
    item11 = Item(
        user=user1,
        category=category6,
        name="Fire Ant",
        description=(
            "Fire ant is the common name for several species of ants in the "
            "genus Solenopsis. They are however only a minority in the genus, "
            "which includes over 200 species of Solenopsis worldwide."
        ),
        quantity=200,
        image_url="https://c2.staticflickr.com/4/3614/3469703353_9020c24f36.jpg"
    )
    session.add(item11)
    session.commit()

    item12 = Item(
        user=user1,
        category=category6,
        name="Swallowtail Butterfly",
        description=(
            "Swallowtail butterflies are large, colorful butterflies in the "
            "family Papilionidae, and include over 550 species. Though the "
            "majority are tropical, members of the family inhabit every "
            "continent except Antarctica."
        ),
        quantity=5,
        image_url="https://upload.wikimedia.org/wikipedia/commons/f/fe/Swallowtail_Butterfly_(Papilio_machaon)_-_geograph.org.uk_-_854088.jpg"
    )
    session.add(item12)
    session.commit()

    session.close()

    print "Populated database with some animals..."
Esempio n. 29
0
def create_item():
    """Allow users to create a new item in the catalog."""
    if 'username' not in login_session:
        return redirect('/login')

    session = connect_to_database()

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

        if request.form['name'] == "items":
            # Can't have an item called "items" as this is a route.
            flash("Error: Can't have an vehicle called 'items'.")
            return redirect(url_for('show_homepage'))

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

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

        if request.form['image_url']:
            new_item.image_url = request.form['image_url']

        session.add(new_item)
        session.commit()

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

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

        session.close()
        return render_template('new_item.html',
                               categories=categories,
                               ref_category=ref_category)
Esempio n. 30
0
def populate():
    session = connect_to_database()

    # Make sure the database is empty before running this inital data dump.
    category_count = session.query(func.count(Category.id)).scalar()
    if category_count > 0:
        session.close()
        return

    # Create the categories for Vehicles

    categoryBicycles = Category(name="Bicycles")
    session.add(categoryBicycles)
    session.commit()

    categoryMotor = Category(name="Motor Vehicles")
    session.add(categoryMotor)
    session.commit()

    categoryRailed = Category(name="Railed Vehicles")
    session.add(categoryRailed)
    session.commit()

    categoryWatercraft = Category(name="Watercraft")
    session.add(categoryWatercraft)
    session.commit()

    categoryAircraft = Category(name="Aircraft")
    session.add(categoryAircraft)
    session.commit()

    categorySpacecraft = Category(name="Spacecraft")
    session.add(categorySpacecraft)
    session.commit()

    # Create a user
    user1 = User(name="Rui Bot", email="*****@*****.**")
    session.add(user1)
    session.commit()

    item1 = Item(
        user=user1,
        category=categoryBicycles,
        name="Chinese Flying Pigeon",
        description=
        ("The most popular bicycle model-and most popular vehicle of any kind in"
         "the world-is the Chinese Flying Pigeon, with about 500 million produced"
         ),
        image_url=
        "https://upload.wikimedia.org/wikipedia/commons/thumb/4/41/Left_side_of_Flying_Pigeon.jpg/1280px-Left_side_of_Flying_Pigeon.jpg"
    )
    session.add(item1)
    session.commit()

    item2 = Item(
        user=user1,
        category=categoryBicycles,
        name=" Trek Y-Foil",
        description=("A carbon fiber Trek Y-Foil from the late 1990s"),
        image_url=
        "https://upload.wikimedia.org/wikipedia/commons/thumb/6/6d/Trek_Y_Foil.jpg/1280px-Trek_Y_Foil.jpg"
    )
    session.add(item2)
    session.commit()

    item3 = Item(
        user=user1,
        category=categoryMotor,
        name="1927 Ford Model T",
        description=("1927 Ford Model T"),
        image_url=
        "https://upload.wikimedia.org/wikipedia/commons/1/15/Late_model_Ford_Model_T.jpg"
    )
    session.add(item3)
    session.commit()

    item4 = Item(
        user=user1,
        category=categoryMotor,
        name="Nissan Leaf",
        description=(
            "The Nissan Leaf is an all-electric car launched in December 2010"
        ),
        image_url=
        "https://upload.wikimedia.org/wikipedia/commons/thumb/5/5b/2018_Nissan_Leaf_Tekna_Front.jpg/280px-2018_Nissan_Leaf_Tekna_Front.jpg"
    )
    session.add(item4)
    session.commit()

    item5 = Item(
        user=user1,
        category=categoryMotor,
        name="Freightliner M2 dump truck",
        description=("Big truck: Freightliner M2 dump truck"),
        image_url=
        "https://upload.wikimedia.org/wikipedia/commons/thumb/1/11/Freightliner_M2_106_6x4_2014_%2814240376744%29.jpg/1280px-Freightliner_M2_106_6x4_2014_%2814240376744%29.jpg"
    )
    session.add(item5)
    session.commit()

    item6 = Item(
        user=user1,
        category=categoryMotor,
        name="Doble Decker Bus",
        description=
        ("A New Routemaster double-decker bus, operating for Arriva London on"
         "London Buses route 73"),
        image_url=
        "https://upload.wikimedia.org/wikipedia/commons/thumb/6/63/LT_471_%28LTZ_1471%29_Arriva_London_New_Routemaster_%2819522859218%29.jpg/1280px-LT_471_%28LTZ_1471%29_Arriva_London_New_Routemaster_%2819522859218%29.jpg"
    )
    session.add(item6)
    session.commit()

    item7 = Item(
        user=user1,
        category=categoryMotor,
        name="Old bus",
        description=(
            "A Toronto Transit Commission bus system trolleybus in Toronto"),
        image_url=
        "https://upload.wikimedia.org/wikipedia/commons/thumb/1/19/Toronto_Flyer_E700A_trolleybus_in_1987.jpg/1280px-Toronto_Flyer_E700A_trolleybus_in_1987.jpg"
    )
    session.add(item7)
    session.commit()

    item8 = Item(
        user=user1,
        category=categoryMotor,
        name="Norton motorcycle",
        description=("A classic Norton motorcycle"),
        image_url=
        "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/Norton_Motorcycle.jpg/800px-Norton_Motorcycle.jpg"
    )
    session.add(item8)
    session.commit()

    item9 = Item(
        user=user1,
        category=categoryMotor,
        name="Suzuki GS500",
        description=(
            "A Suzuki GS500 with a clearly visible frame, painted silver"),
        image_url=
        "https://upload.wikimedia.org/wikipedia/commons/thumb/3/36/1997SuzukiGS500E-001.jpg/1280px-1997SuzukiGS500E-001.jpg"
    )
    session.add(item9)
    session.commit()

    item10 = Item(
        user=user1,
        category=categoryRailed,
        name="Glass Frog",
        description=(
            "Japanese Shinkansen 500 Series train, Shinkansen 500 series"
            " at Kyoto Station taken by Nick Coutts on 2005-03-19."),
        image_url=
        "https://upload.wikimedia.org/wikipedia/commons/3/31/Shinkansen_500_Kyoto_2005-03-19.jpg"
    )
    session.add(item10)
    session.commit()

    item11 = Item(
        user=user1,
        category=categoryRailed,
        name="ETT 303 and 304 Sunshine.",
        description=("ETT 303 and 304 Sunshine."),
        image_url=
        "https://upload.wikimedia.org/wikipedia/commons/thumb/5/5a/City_of_Rockhampton_train_%28Sunshine_railway_station%2C_Brisbane%29.jpg/800px-City_of_Rockhampton_train_%28Sunshine_railway_station%2C_Brisbane%29.jpg"
    )
    session.add(item11)
    session.commit()

    item12 = Item(
        user=user1,
        category=categoryWatercraft,
        name="RMS Titanic 3",
        description=("Titanic!!!"),
        image_url=
        "https://upload.wikimedia.org/wikipedia/commons/thumb/f/fd/RMS_Titanic_3.jpg/800px-RMS_Titanic_3.jpg"
    )
    session.add(item12)
    session.commit()

    item13 = Item(
        user=user1,
        category=categoryWatercraft,
        name="Colombo Express",
        description=
        ("The Colombo Express, one of the largest container ships in the world,"
         "owned and operated by Hapag-Lloyd of Germany on its maiden voyage into Hamburg,"
         "with the Kohlbrand bridge in the background"),
        image_url=
        "https://upload.wikimedia.org/wikipedia/commons/thumb/7/7e/Colombo.Express.wmt.jpg/800px-Colombo.Express.wmt.jpg"
    )
    session.add(item13)
    session.commit()

    item14 = Item(
        user=user1,
        category=categoryAircraft,
        name="Cessna 172",
        description=(
            "The Cessna 172 Skyhawk is the most produced aircraft in history."
        ),
        image_url=
        "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c8/Cessna172-CatalinaTakeOff.JPG/800px-Cessna172-CatalinaTakeOff.JPG"
    )
    session.add(item14)
    session.commit()

    item15 = Item(
        user=user1,
        category=categoryAircraft,
        name="Mil Mi-8",
        description=(
            "The Mil Mi-8 is the most-produced helicopter in history."),
        image_url=
        "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8d/Mi-8_%28RA-24477%29_Helicopter_in_SPB.jpg/800px-Mi-8_%28RA-24477%29_Helicopter_in_SPB.jpg"
    )
    session.add(item15)
    session.commit()

    session.close()

    print("Populated database with some rows...")
Esempio n. 31
0
def edit_item(item_name, category_name=None):
    """Edit the details of the specified item.

    Args:
        item_name (str): Name of item to be edited.
        category_name (str): Optionally, can also specify the category to
            which the item belongs to.
    """
    if 'username' not in login_session:
        flash("You need to login to edit any vehicles.")
        return redirect('/login')

    session = connect_to_database()

    try:
        item = session.query(Item).filter_by(name=item_name).one()
    except NoResultFound:
        flash("Error: The item '%s' does not exist." % item_name)
        return redirect(url_for('show_homepage'))

    if login_session['user_id'] != item.user_id:
        flash("You didn't add this vehicle, so you can't edit it. Sorry :-(")
        category = session.query(Category).filter_by(id=item.category_id).one()
        category_name = category.name
        item_name = item.name
        session.close()
        return redirect(
            url_for('show_item',
                    category_name=category_name,
                    item_name=item_name))

    if request.method == 'POST':
        if request.form['name'] != item.name:
            # Enforce rule that item names are unique
            qry = session.query(Item).filter(Item.name == request.form['name'])
            already_exists = (session.query(literal(True)).filter(
                qry.exists()).scalar())
            if already_exists is True:
                original_category = (session.query(Category).filter_by(
                    id=item.category_id).one())
                flash("Error: There is already an vehicle with the name '%s'" %
                      request.form['name'])
                session.close()
                return redirect(
                    url_for('show_items',
                            category_name=original_category.name))
            item.name = request.form['name']

        form_category = (session.query(Category).filter_by(
            name=request.form['category']).one())
        if form_category != item.category:
            item.category = form_category

        item.description = request.form['description']

        if ('delete_image' in request.form
                and request.form['delete_image'] == 'delete'):

            item.image_url = request.form['image_url']

        session.add(item)
        session.commit()

        flash("Vehicle successfully edited!")
        category_name = form_category.name
        item_name = item.name
        session.close()
        return redirect(
            url_for('show_item',
                    category_name=category_name,
                    item_name=item_name))
    else:
        categories = session.query(Category).all()
        session.close()
        return render_template('edit_item.html',
                               categories=categories,
                               item=item)