Esempio n. 1
0
    def test_component_crud(self):
        # Create
        component = Component(name='Foo', index=5, markup="<h1>Hello</h1>")
        db.session.add(component)
        db.session.commit()
        self.assertIn(component, Component.query.all())
        self.assertIsInstance(component.index, int)
        self.assertIsInstance(component.markup, unicode)
        self.assertIsInstance(component.created_at, DT.datetime)
        self.assertIsInstance(component.updated_at, DT.datetime)

        # Read
        component = Component.query.filter_by(name='Foo').first()
        self.assertEqual(component.name, 'Foo')
        self.assertEqual(component.index, 5)
        self.assertEqual(component.markup, "<h1>Hello</h1>")
        
        # Update
        old_created_at = component.created_at
        old_updated_at = component.updated_at
        component.name   = 'Bar'
        component.index  = 7
        component.markup = "<h2>Bye</h2>"
        component = Component.query.filter_by(name='Bar').first()
        self.assertIsInstance(component, Component)
        self.assertEqual(component.name, "Bar")
        self.assertEqual(component.index, 7)
        self.assertEqual(component.markup, "<h2>Bye</h2>")
        self.assertEqual(component.created_at, old_created_at)
        self.assertNotEqual(component.updated_at, old_updated_at)

        # Delete
        db.session.delete(component)
        count = Component.query.filter_by(name='Bar').count()
        self.assertEqual(0, count)
Esempio n. 2
0
def create_component():
    form = ComponentForm()
    if request.method == 'POST':
        if form.validate() == False:
            flash(
                'Не заполнены необходимые поля или введены некорректные данные'
            )
            return render_template('create_component.html', form=form)
        else:
            if Component.query.filter(
                    Component.component_name ==
                    form.name.data).first() or Component.query.filter(
                        Component.component_item == form.item.data).first():
                flash('Товар с таким именем или артикулом существует')
                return render_template('create_component.html', form=form)
            else:
                component = Component(form.name.data, form.unit.data,
                                      form.item.data)
                db.session.add(component)
                db.session.commit()
                return redirect(
                    url_for('create_modal_component',
                            modal_component=component.id,
                            det='hollow'))
    return render_template('create_component.html', form=form)
Esempio n. 3
0
 def import_components():
     app.logger.info('Importing components...')
     e = ElementTree.parse('data/const_2017-11-21.xml').getroot()
     for e_component in e.findall('CONST'):
         component = Component(
             id=int(e_component[0].text),
             name_fr=' '.join(e_component[1].text.split()),
             name_en=' '.join(e_component[2].text.split()),
         )
         db.session.add(component)
     db.session.commit()
Esempio n. 4
0
def create_component(project_id=None):
    if not session.get('username'):
        return redirect(url_for('index'))
    form = CreateComponentForm()
    form.project_id.data = project_id
    if form.validate_on_submit():
        Component(name=form.name.data, project_id=form.project_id.data).save()
        flash("Component is successfully created!", "success")
        return redirect(url_for('components', project_id=project_id))
    return render_template("create_component.html",
                           form=form,
                           title="Create Component",
                           create_component_flag=True)
Esempio n. 5
0
	def populateComponent(self, cluster_id, cluster,cluster_name, product_release_number, region_name, product_name,client_names):
		try:
			client = boto3.client("ecs", region_name=region_name)

			##fetch the services from AWS
			services = client.list_services(cluster = cluster)
			services = services["serviceArns"]
			cluster_task_list = []
			##iterate through each service in the cluster and store it in the database
			for service in services:
				#print(service)
				mysplit= service.split("/")
				service_name = mysplit[-1]

				##check if the component exists in the database
				exists_component = db.session.query(Component.component_name).filter_by(component_name=service_name).filter_by(cluster_id=cluster_id[0]).scalar() is not None
				if exists_component:
					print(" Component Already Exists")
				else:
					print(service_name)
					component = Component(component_name = service_name, cluster_id= cluster_id[0], is_active=True)
					db.session.add(component)
					print("Added component to database: " + service_name)

				##get the component_id of the corresponding component
				component_id = db.session.query(Component.component_id).filter_by(component_name=service_name).filter_by(cluster_id=cluster_id[0]).first()

				tasks = client.list_tasks(cluster=cluster, serviceName=service)
				tasks = tasks["taskArns"]
				task_component_dict = {}
				task_component_dict["component_id"] = component_id
				task_component_dict["task"] = tasks
				task_component_dict["service"] = service
				cluster_task_list.append(task_component_dict)


			#if self.checkRollback(cluster, cluster_name, product_release_number, region_name,cluster_task_list, product_name, client_names):
			#  	print("rollBACK")
			# else:
			self.compareTaskDefinition(cluster,cluster_name,product_release_number,region_name, cluster_task_list, product_name,client_names)

		except Exception as ex:
			date = datetime.utcnow()
			tb = sys.exc_info()[2]
			errorMsg = str(date) + " - File: AWSData.py - Function: populateComponent - " + str(ex.args) + " - on line " + str(tb.tb_lineno) + " \r\n"
			f.write(errorMsg)
			f.close()
Esempio n. 6
0
    def insert_one(self, component):

        new_component = Component()

        if "name" in component:
            new_component.name = component["name"]

        if "description" in component:
            new_component.description = component["description"]

        if "uptime" in component:
            new_component.uptime = component["uptime"]

        if "group_id" in component:
            new_component.group = None if component["group_id"] is None else ComponentGroup.objects.get(pk=component["group_id"])

        new_component.save()
        return False if new_component.pk is None else new_component
Esempio n. 7
0
def component():
    if isinstance(current_user._get_current_object(), Admin):
        page = request.args.get('page', 1, type=int)
        items = Component.query.order_by(Component.id.desc()).paginate(
            page, app.config['DATA_PER_PAGE'], False)
        next_url = url_for('component',
                           page=items.next_num) if items.has_next else None
        prev_url = url_for('component',
                           page=items.prev_num) if items.has_prev else None
        add_form = AddComponentForm()
        if add_form.validate_on_submit():
            quantity = add_form.quantity.data
            unitPrice = add_form.unitPrice.data
            totalPrice = round(quantity * unitPrice, 2)
            department = dict(add_form.department.choices).get(
                add_form.department.data)
            if Component.query.filter_by(
                    name=add_form.name.data,
                    type=add_form.type.data,
                    department=department).first() is not None:
                flash("已存在这个元器件")
                return redirect(url_for('component'))
            component = Component(name=add_form.name.data,
                                  type=add_form.type.data,
                                  department=department,
                                  quantity=quantity,
                                  unitPrice=unitPrice,
                                  totalPrice=totalPrice,
                                  remark=add_form.remark.data)
            db.session.add(component)
            db.session.commit()
            flash("元器件添加成功")
            return redirect(url_for('component'))
        return render_template('admin/component.html',
                               items=items.items,
                               form=add_form,
                               next_url=next_url,
                               prev_url=prev_url)
    elif isinstance(current_user._get_current_object(), Student):
        items = Component.query.all()
        apply_form = ApplyComponentForm()
        return render_template('student/component.html',
                               items=items,
                               form=apply_form)
Esempio n. 8
0
def new_component():
    form = NewComponentForm()
    if form.validate_on_submit():
        component = form.component.data
        if Component.query.filter_by(component=component).first():
            flash(_('Component %(component)s already exist...', component=component))
        else:
            db_component = Component(component=component, search_date=form.search_date.data)
            db.session.add(db_component)
            current_user.last_component = component
            db.session.commit()
            session['component'] = component
            session['components'].append(component)
            # if session.get('new_case_id_list'):
            if 'new_case_id_list' in session:
                session.pop('new_case_id_list')
            flash(_('Congratulations, new component has been added!'))
            return redirect(url_for('index'))
    return render_template('component/new_component.html', title=_('New Component'),
                           form=form)
Esempio n. 9
0
def delete_component(id):
    Component.delete_component(id)
    return redirect(url_for('component_table'))
Esempio n. 10
0
vessels_file = open('inputs/vessels.csv')
vessels = csv.reader(vessels_file)

for vessel in vessels:
    v = Vessel(name=vessel[0],
               abbr=vessel[1],
               day_rate=vessel[2],
               mob_time=vessel[3],
               facility=f)
    db.session.add(v)

a = Area(name='DC1', equity_share=0.72, facility=f)
db.session.add(a)

c = Component(ident='P11', category='Tree', service_type='Production', area=a)
db.session.add(a)

consequences_file = open('inputs/consequences.csv')
consequences = csv.reader(consequences_file)

for consequence in consequences:
    cons = Consequence(name=consequence[0],
                       mean_time_to_repair=consequence[10],
                       replacement_cost=consequence[11],
                       deferred_prod_rate=consequence[14],
                       component=c,
                       facility=f)
    v1 = Vessel.query.filter_by(name=consequence[2]).first()
    vt1 = VesselTrip(vessel=v1,
                     active_repair_time=consequence[5],
import json
from app import app, db
from app.models import Component, Maintenance
from datetime import datetime, timedelta

#read a components json file
with open('components_data.json','r') as cp:
    array = json.load(cp)

for cpt in array['components'] :
    c = Component(position=cpt['position'],weight=cpt['weight'])
    db.session.add(c)
db.session.commit()

#read a maintenances json file
with open('maintenances_data.json','r') as ms:
    array = json.load(ms)
index = 20
for mt in array['maintenances'] :
    d = datetime.today() - timedelta(days=index)
    m = Maintenance(body=mt['body'],date=d,component_id=mt['component_id'])
    db.session.add(m)
    index -= 2
db.session.commit()   
Esempio n. 12
0
    def test_relationships(self):

        # Create account with no relationships
        account = Account(name="Account Foo")
        db.session.add(account)
        db.session.commit()
        self.assertEqual(account.users, [])

        # Add user to account (many-to-many relationship)
        user = User(name="User 1", email="*****@*****.**", password="******")
        account.users.append(user)
        db.session.add(user)
        db.session.commit()
        self.assertIn(user, account.users)
        self.assertIn(account, user.accounts)

        # Add visitor to account
        visitor = Visitor()
        account.visitors.append(visitor)
        db.session.add(visitor)
        db.session.commit()
        self.assertIn(visitor, account.visitors)
        self.assertEqual(visitor.account, account)

        # Add placeholder to account
        placeholder = Placeholder(name="Placeholder Foo")
        account.placeholders.append(placeholder)
        db.session.add(placeholder)
        db.session.commit()
        self.assertIn(placeholder, account.placeholders)
        self.assertEqual(placeholder.account, account)

        # Add components to placeholder
        component_0 = Component(name="Component Foo", index=0)
        component_1 = Component(name="Component Foo", index=1)
        component_2 = Component(name="Component Foo", index=2)
        placeholder.components.append(component_2)
        placeholder.components.append(component_1)
        placeholder.components.append(component_0)
        db.session.commit()
        self.assertIn(component_0, placeholder.components)
        self.assertEqual(component_0.placeholder, placeholder)
        self.assertEqual(component_0, placeholder.components[0])
        self.assertEqual(component_1, placeholder.components[1])
        self.assertEqual(component_2, placeholder.components[2])

        # Add segment to account
        segment = Segment(name="Segment Foo")
        account.segments.append(segment)
        db.session.add(segment)
        db.session.commit()
        self.assertIn(segment, account.segments)
        self.assertEqual(segment.account, account)
        self.assertEqual(segment.rules, [])

        # Add rule to segment
        rule = Rule()
        segment.rules.append(rule)
        db.session.add(rule)
        db.session.commit()
        self.assertIn(rule, segment.rules)
        self.assertEqual(rule.segment, segment)

        # Add segment to component
        component_0.segment = segment
        db.session.commit()
        self.assertEqual(component_0.segment, segment)
        self.assertIn(component_0, segment.components)
Esempio n. 13
0
def make_dummy_seed():
    from app.models import Creation, Page, Component, Design

    with app.app_context():

        design = Design.query.filter_by(name='design1').first() or Design(
            name='design1')

        creation = Creation.query.filter_by(
            domain='creator').first() or Creation()
        creation.name = 'Dummy'
        creation.domain = 'creator'
        creation.active = True
        creation.design = design
        creation.menu = {
            'position':
            'top',
            'links': [
                {
                    'href': '/page1',
                    'name': 'Media'
                },
                {
                    'href': '/page2',
                    'name': 'Poll'
                },
                {
                    'href': '/page3',
                    'name': 'My Page'
                },
            ]
        }

        db.session.add(creation)

        pages = (('page1', (
            {
                'name': 'TOP',
                'type': 'media',
                'config': {
                    'length': 5
                }
            },
            {
                'name': 'Twitter',
                'type': 'twitter',
                'config': {
                    'account_id': 403614288
                }
            },
        )), ('page2', ({
            'name': 'POLL Z',
            'type': 'poll',
            'config': {
                'id_poll': 123
            }
        }, )), ('page3', ({
            'name': 'History',
            'type': 'html',
            'config': {
                'file': 'custom_html_27.html'
            }
        }, )))

        for p, components in pages:
            page = Page.query.filter_by(
                creation=creation, name=p).first() or Page(name=p,
                                                           creation=creation)
            db.session.add(page)

            for component in components:
                c = Component.query.filter_by(
                    name=component['name'], page=page,
                    type=component['type']).first() or Component()
                c.page = page
                c.name = component['name']
                c.type = component['type']
                c.config = component['config']
                db.session.add(c)

        db.session.commit()