Exemple #1
0
def create_tag():
    """ Creates a new tag.
    
    .. :quickref: Tag; Creates a new tag.

    **Example request**:

    .. sourcecode:: http

      POST /tags HTTP/1.1
      Host: 127.0.0.1
      Content-Type: application/json

      {
        "value": "phish"
      }

    **Example response**:

    .. sourcecode:: http

      HTTP/1.1 201 Created
      Content-Type: application/json

      {
        "id": 1,
        "value": "phish"
      }

    :reqheader Authorization: Optional Apikey value
    :resheader Content-Type: application/json
    :status 201: Tag created
    :status 400: JSON does not match the schema
    :status 401: Invalid role to perform this action
    :status 409: Tag already exists
    """

    data = request.get_json()

    # Verify this value does not already exist.
    existing = Tag.query.filter_by(value=data['value']).first()
    if existing:
        return error_response(409, 'Tag already exists')

    # Create and add the new value.
    tag = Tag(value=data['value'])
    db.session.add(tag)
    db.session.commit()

    response = jsonify(tag.to_dict())
    response.status_code = 201
    response.headers['Location'] = url_for('api.read_tag', tag_id=tag.id)
    return response
Exemple #2
0
def tag_stats(tagname):

    tag = Tag.get_tag_by_name(tagname, g.user)
    if tag is None:
        abort(400, "You don't have tag: ".format(tagname))
    else:
        tt, vv = get_tag_data(tag, duration='day')
        tt_w, vv_w = get_tag_data(tag, duration='week')
        tt_m, vv_m = get_tag_data(tag, duration='month')

        fig = Figure(figsize=(10, 7.5))
        fig.subplots_adjust(hspace=0.4)
        ax = fig.add_subplot(3, 1, 1)
        ax.step(tt, vv, where='post', label=tagname)
        ax.legend(loc='upper right', shadow=True)
        ax.set_xlabel('hour')
        ax.set_title('Work Time')

        ax = fig.add_subplot(3, 1, 2)
        ax.step(tt_w / 24, vv_w, where='post', label=tagname)
        ax.legend(loc='upper right', shadow=True)
        ax.set_xlabel('day')

        ax = fig.add_subplot(3, 1, 3)
        ax.step(tt_m / 24, vv_m, where='post', label=tagname)
        ax.legend(loc='upper right', shadow=True)
        ax.set_xlabel('day')

        html_text = mpld3.fig_to_html(fig)
        return html_text
Exemple #3
0
 def setUp(self):
     #self.create_app() # Create the app with TestConfig
     db.create_all()
     admin = User("admin", "*****@*****.**", "admin")
     admin.private_favorites = True
     db.session.add(admin)
     db.session.add(User("abd", "*****@*****.**", "abd"))
     db.session.add(User("tester", "*****@*****.**", "tester"))
     c = Category("testing")
     db.session.add(c)
     db.session.add(Category("testing_cat"))
     testing_post = BlogPost("Testing Post",
                             "This is just a test post",
                             author_id=1)
     testing_post.category = c
     db.session.add(testing_post)
     post1 = BlogPost("Testing Tag",
                      "This is just a test post to test tags",
                      author_id=2)
     post2 = BlogPost("From Abd",
                      "This is just a test post From Abd",
                      author_id=2)
     post1.category = c
     post2.category = c
     db.session.add(post1)
     db.session.add(post2)
     tag = Tag("tests")
     post1.tags.append(tag)
     db.session.add(Comment("Test comment", 1, 2))
     admin.fav_posts.append(testing_post)
     db.session.commit()
Exemple #4
0
def create_tag():
    class TagForm(Form):
        tag = StringField('Tag', validators=[DataRequired()])
        submit = SubmitField('Submit')

    form = TagForm()
    if form.validate_on_submit():
        #should not allow one user to have two identical tags
        if Tag.exist(form.tag.data, g.user):
            abort(400, 'You already have this tag: {}.'.format(form.tag.data))

        new_tag = Tag(form.tag.data, g.user)
        db.session.add(new_tag)
        db.session.commit()

        flash('1 tag added to the database.')
        return redirect(url_for('timer.showtags'))

    return render_template('addtag.html', form=form)
Exemple #5
0
def new_tag():
    form = TagForm(request.form)
    form.set_choices()
    if form.validate():
        tag = Tag(request.form["tag"])
        messages = [Message.query.get(m) for m in form.messages.data]
        tag.messages.extend(messages)
        db.session.add(tag)
        db.session.commit()
        return redirect(url_for("tags.index"))
    return render_template("tags/new.html", form=form)
Exemple #6
0
def index():
    if request.method == 'POST':
        form = TagForm(request.form)
        form.set_choices()
        if form.validate_on_submit():
            new_tag = Tag(form.text.data)
            for message in form.messages.data:
                new_tag.messages.append(Message.query.get(message))
            db.session.add(new_tag)
            db.session.commit()
        else:
            return render_template('tags/new.html', form=form)
    return render_template('tags/index.html', tags=Tag.query.all())
def index():
    if request.method == "POST":
        form = TagForm(request.form)
        form.set_choices()
        if form.validate():
            tag = Tag(form.text.data)
            for message in form.messages.data:
                tag.messages.append(Message.query.get(message))
            db.session.add(tag)
            db.session.commit()
            flash('Tag Created!')
        else:
            return redirect(url_for('tags.new.html', form=form))
    return render_template('tags/index.html', tags=Tag.query.all())
Exemple #8
0
 def fill_test_db(test_db):
     tag_names = [
         'one',
         'two',
         'three',
     ]
     db_tags = []
     for element in tag_names:
         tag = Tag(element)
         db_tags.append(tag)
         test_db.session.add(tag)
     for i in range(3):
         graph = Graph('G1{:05d}'.format(i))
         graph.tags.extend(db_tags[:i + 1])
         test_db.session.add(graph)
Exemple #9
0
 def fill_db(prod_db):
     random.seed(42)
     tag_names = [
         '{0}_{1}'.format(name, i) for i in range(tags_series)
         for name in ('tesla', 'mask', 'ev')
     ]
     db_tags = []
     for element in tag_names:
         tag = Tag(element)
         db_tags.append(tag)
         prod_db.session.add(tag)
     for i in range(graphics):
         graph = Graph('G1{:05d}'.format(i))
         graph.tags.extend(
             random.sample(db_tags, random.randint(1,
                                                   max_tags_per_graphic)))
         prod_db.session.add(graph)
Exemple #10
0
def add_tags(tags, post):
    # Remove all tags and then check if tag exists
    # If it is already added to the post (may need refactoring it)
    # Should be in `models.py`
    post.tags = []
    db.session.commit()
    for tag in tags:
        t = Tag(tag)
        tag_exists = Tag.query.filter_by(name=tag).first()
        if tag_exists:
            if tag_exists not in post.tags:
                post.tags.append(tag_exists)
            else:
                pass
        else:
            db.session.add(t)
            post.tags.append(t)
            db.session.commit()
Exemple #11
0
def tags_to_tag_ids(tags):
    """
    A generator that takes a list of string tag names
    and yields IDs of these tags if they exist
    or creates new tags and returns their IDs
    :param: tags: a list of string tag names
    """
    for tag_name in tags:
        # Query the tag
        tag = Tag.query.filter_by(name=tag_name).one_or_none()
        if not tag:
            # If the tag does not exist, create it and yield the new tag's ID
            new_tag = Tag(name=tag_name)
            db.session.add(new_tag)
            db.session.commit()
            yield new_tag.id
        else:
            # If the tag exists, return it's ID
            yield tag.id
Exemple #12
0
def add_session():
    start = request.args.get('start', None, type=int)
    end = request.args.get('end', None, type=int)

    #print(start)
    #print(end)
    start_datetime = unixtime_to_datetime(start)
    end_datetime = unixtime_to_datetime(end)

    tag = Tag.get_tag_by_name(session['tagname'], g.user)
    if tag is not None:
        new_work = Work(start_datetime, end_datetime, tag)
        db.session.add(new_work)
        db.session.commit()
    else:
        abort(400, "You don't have tag: ".format(session['tagname']))

    response = jsonify({'result': 'done'})
    response.status_code = 201
    return response
Exemple #13
0
def update_admin_networks_table():
    '''
    If the network exists in db, updates the network row with new values;
     clears and rebuilds:
    - tags table,
    - networks-tags relations,
    - group-networks relations
    else, adds new network to networks table.
    :return: 200
    '''
    t1 = time.time()
    log_msg = "User: {} - Started updating networks table".format(current_user.username)
    send_wr_log(log_msg)
    try:
        meraki_networks = get_networks()
        templates = get_templates()
    except ConnectionError:
        error = "Meraki Server Bad Response"
        log_msg = "User: {} - {} while updating networks table.".format(current_user.username, error)
        send_wr_log(log_msg)
        return error
    for key, value in templates.items():
        template = Template.query.filter_by(meraki_id=value).first()
        if template:
            template.update(key, value)
        else:
            template = Template(key, value)
        db.session.add(template)
    db.session.commit()  # update templates table

    db_networks = Network.query.all()
    # cleaning non-existent networks from db table
    for network in db_networks:
        network_exists = False
        for m_network in meraki_networks:
            if m_network['meraki_id'] == network.meraki_id:
                network_exists = True
                break
        if not network_exists:
            log_msg = "User: {} - Network: {} with {} id does not exist on cloud; " \
                      "being deleted from db.".format(current_user.username, network.name, network.meraki_id)
            send_wr_log(log_msg)
            network.tags.clear()
            network.groups.clear()
            for device in network.devices:
                log_msg = "User: {} - Deleting device: {} related with network: {} " \
                          "from DB".format(current_user.username, device.serial, network.name)
                send_wr_log(log_msg)
                db.session.delete(device)
            db.session.delete(network)

    # networks from meraki cloud
    for network in meraki_networks:
        db_network = Network.query.filter_by(meraki_id=network['meraki_id']).first()
        # update if the network exists
        if db_network:
            db_network.update(**network)  # update the existing network in db consistent with cloud
            # update tags table and build their relation with networks
            if network['net_tags']:
                db_network.tags.clear()
                for tag in network['net_tags'].split(" "):
                    db_tag = Tag.query.filter_by(name=tag).first()
                    if db_tag:
                        db_network.tags.append(db_tag)
                    else:
                        new_tag = Tag(tag)
                        db.session.add(new_tag)
                        db_network.tags.append(new_tag)

        else:
            db_network = Network(**network)  # there is a new network on cloud, and save it in db

        db.session.add(db_network)
        db_network.committed = True  # db is synced with cloud

    db.session.commit()
    # build group network relation according to tag bindings to both networks and groups
    db_groups = Group.query.all()
    for db_group in db_groups:
        db_grp_tags = db_group.tags
        if db_grp_tags:
            for db_network in db_networks:
                db_net_tags = db_network.tags
                for db_net_tag in db_net_tags:
                    if db_net_tag in db_group.tags:
                        db_group.networks.append(db_network)
                        break
                    else:
                        if db_network in db_group.networks:
                            db_group.networks.remove(db_network)
                db.session.add(db_group)
    db.session.commit()

    # cleaning duplicate networks if not existing in cloud
#    sq = Network.query.with_entities(Network.name).group_by(Network.name).having(func.count(Network.name) > 1).subquery()
#    duplicates = Network.query.filter(Network.name == sq.c.name).order_by(Network.name).all()
#    if duplicates:
#        for network in duplicates:
#            result = get_network(network.meraki_id)
#            if result == 404:
#                network.groups.clear()
#                network.tags.clear()
#                if network.devices:
#                    for device in network.devices:
#                        db.session.delete(device)
#                db.session.delete(network)
#        db.session.commit()

    t2 = time.time()
    log_msg = "User: {} - Updating networks table is completed in {} seconds.".format(current_user.username, t2 - t1)
    send_wr_log(log_msg)
    return "success"
Exemple #14
0
def new_network():
    error = None
    # beginning of "on page load"
    #####
    templates_names = []
    try:
        templates_db = Template.query.all()
    except (ProgrammingError, OperationalError) as e:
        error_log = str(e)
        log_msg = "Database error on (Get) New Network: {}".format(error_log)
        send_wr_log(log_msg)
        return jsonify("Database error!")
    for template in templates_db:
        templates_names.append(template.name)

    form = NewNetworkForm(request.form)
    form.net_template.choices = list(templates_names)
    form.set_choices()
    #####
    # end of "on page load" block

    if request.method == 'POST':
        net_will_be_copied = False
        error = None
        net_name = form.net_name.data
        net_name = net_name.strip()
        # validation on serverside
        if net_name == "":
            return jsonify("Enter a unique network name!")

        net_type = form.net_type.data
        user_id = current_user.id

        # ensure that network name does not already exist in db
        try:
            network = Network.query.filter_by(name=net_name).first()
        except (ProgrammingError, OperationalError) as e:
            error_log = str(e)
            log_msg = "Database error on (Post) New Network: {}".format(
                error_log)
            send_wr_log(log_msg)
            return jsonify("Database error!")
        if network:
            error = "Network already exists, try another unique name"
            # return render_template('home.html', form=form, error=error)
            log_msg = "User: {} - Network Name: {} - {}".format(
                current_user.username, network.name, error)
            send_wr_log(log_msg)
            return jsonify(error)

        if net_type == 'appliance':
            template = Template.query.filter_by(
                name=form.net_template.data).first()
            bound_template = template.meraki_id
            network = Network(net_name,
                              net_type,
                              user_id,
                              bound_template=bound_template)
            log_msg = "User: {} - Network {} is being saved in DB" \
                      " with binding to template: {}".format(current_user.username, network.name, template.name)
            send_wr_log(log_msg)
        else:
            network_copy_source = Network.query.get(int(form.net_to_copy.data))
            source_network = network_copy_source.id  # it is not bound template, actually.
            network = Network(net_name,
                              net_type,
                              user_id,
                              source_network=source_network)
            log_msg = "User: {} - Network {} is being saved in DB" \
                      " being copied from the Network: {}".format(current_user.username, network.name, network_copy_source.name)
            send_wr_log(log_msg)

        network.net_tags = ""
        for tag_id in form.net_tag_mselect.data:
            tag = Tag.query.get(int(tag_id))
            network.tags.append(tag)
            network.net_tags += tag.name + " "
            # build network group relation according to selected tags
            for group in tag.groups:
                network.groups.append(group)
        # location specific tag for name seperated with dash;
        # eg. for network name AB11-Firewall, then new tag will be AB11
        if "-" in net_name:
            specific_tag_name = net_name.split("-")[0]
            specific_tag = Tag.query.filter_by(name=specific_tag_name).first()
            if not specific_tag:
                new_network_tag = Tag(specific_tag_name)
                db.session.add(new_network_tag)
                db.session.commit()
                network.tags.append(new_network_tag)
            else:
                network.tags.append(specific_tag)
        db.session.add(network)
        db.session.commit()
        log_msg = "User: {} - Network: {} is saved in DB with success".format(
            current_user.username, network.name)
        send_wr_log(log_msg)

        return jsonify(error)

    return render_template('new_network.html',
                           current_user=current_user,
                           form=form,
                           error=error)
Exemple #15
0
    def post(self):
        api_key = ''
        try:
            api_key = request.headers['X-API-KEY']
            if api_key != 'food' and api_key != 'textile':
                return 'X-API-KEY not recognised', HTTPStatus.BAD_REQUEST
        except KeyError:
            return 'No X-API-KEY supplied', HTTPStatus.BAD_REQUEST
        json_data = dict(request.get_json(force=True))
        if not json_data:
            return 'No JSON body supplied', HTTPStatus.BAD_REQUEST
        try:
            product = Product(name=json_data["name"], product_type=api_key)
            db.session.add(product)
            db.session.flush()
            product_id = product.id
            materials = json_data.get(
                "billOfMaterials")  # Returns None if no materials provided
            tags = json_data.get("tags")
            if api_key == 'food':
                family = json_data["family"]
                customer = json_data["customer"]
                food_entry = Food(product_id=product_id,
                                  family=family,
                                  customer=customer)
                db.session.add(food_entry)
                allergens = json_data.get("allergens")
                if allergens:
                    for allergen in allergens:
                        allergen_data = Allergen(name=allergen)
                        db.session.add(allergen_data)
                        db.session.flush()
                        allergen_id = allergen_data.id
                        db.session.add(
                            ProductAllergen(allergen_id=allergen_id,
                                            product_id=product_id))
            elif api_key == 'textile':
                colour = json_data["colour"]
                product_range = json_data["range"]
                textile_data = Textile(product_id=product_id,
                                       colour=colour,
                                       range=product_range)
                db.session.add(textile_data)
            if tags:
                for tag in tags:
                    tag_id = Tag.query.with_entities(
                        Tag.id).filter_by(tag_name=tag).first(
                        )  # Check if tag already exists, create new if not
                    if not tag_id:
                        tag_data = Tag(tag_name=tag)
                        db.session.add(tag_data)
                        db.session.flush()
                        tag_id = tag_data.id
                    else:
                        tag_id = tag_id[0]
                    db.session.add(
                        ProductTag(tag_id=tag_id, product_id=product_id))
            if materials:
                for material, data in materials.items():
                    material_data = Material(product_id=product_id,
                                             material_name=material,
                                             quantity=data["quantity"],
                                             units=data["units"])
                    db.session.add(material_data)
            db.session.commit()
        except KeyError:
            db.session.rollback()
            return 'Invalid JSON body supplied', HTTPStatus.BAD_REQUEST
        except:
            db.session.rollback()
            raise

        return 'Product created', HTTPStatus.CREATED
Exemple #16
0
def get_new_tag(new_tag):
    if new_tag:
        tag = Tag(new_tag)
        db.session.add(tag)
        db.session.commit()
        return tag