Esempio n. 1
0
    def test_save_sort_algo(self):
        client = self.create_dummy_client()

        dummy_form_data = {
            'title': 'Add Navbar',
            'description': 'We need to add a navbar',
            'target_date': datetime.date(datetime.today()),
            'client_priority': 1,
            'client': client,
            'product_areas': []
        }

        # create a feature with priority 1
        feature_1 = self.create_dummy_feature(client, priority=1)

        # create another feature with priority 1 using the algorithm

        Feature.save_sort_algo(dummy_form_data, db)

        # retrieve the feature created
        feature_2 = Feature.query.filter_by(title='Add Navbar').first()
        # confirm that the priority of the first feature is different from the the priority of the second feature
        assert (feature_1.client_priority != feature_2.client_priority)
        # confirm that the new feature takes the topmost priority
        assert (feature_2.client_priority == 1)
        # confirm that the old feature has it's priority increased by one
        assert (feature_1.client_priority == 2)
Esempio n. 2
0
def create_entities(project):
    #TODO: LEMBRAR DE CRIAR ROTINA PRA CALCULAR SPECTRUM E PROBABILIDADES E JÁ SALVAR
    feature = Feature()

    try:
        print(
            '------------------------- Reading New Feature -------------------------'
        )
        # print(project.data)
        loaded_json = json.loads(project.data)
        project = get_project(loaded_json['project'])
        feature.project = project

        feature.path_name = loaded_json['path_name']
        feature.feature_name = loaded_json['feature_name']
        feature.language = loaded_json['language']
        feature.user_story = loaded_json['user_story']
        feature.background = loaded_json['background']
        features_db = Feature.objects.filter(
            path_name=feature.path_name).filter(project=feature.project)
        if not features_db:
            feature.save()

        for each_scenario in loaded_json['scenarios']:
            scenario = SimpleScenario()
            scenario.feature = feature
            scenario.scenario_title = each_scenario['scenario_title']
            scenario.line = each_scenario['line']
            criterion1 = Q(scenario_title=scenario.scenario_title)
            criterion3 = Q(line=scenario.line)
            criterion2 = Q(feature=scenario.feature)
            base = SimpleScenario.objects.filter(criterion1 & criterion2
                                                 & criterion3)
            if len(base) > 0:
                print('Scenario Already exists!')
                scenario = base[0]
            else:
                print('Scenario: ', scenario.scenario_title)
                scenario.save()
            for method in each_scenario['executed_methods']:
                # if is_new_method(method):
                #     met = Method()
                #     met.method_name = method['method_name']
                #     met.class_name = method['class_name']
                #     met.class_path = method['class_path']
                #     met.save()
                #     scenario.executed_methods.add(met)
                # else:
                met = Method.objects.filter(method_id=method['method_id'])
                if len(met) < 1:
                    print('METHOD NOT FOUND! ', method['method_id'])
                scenario.executed_methods.add(met[0])

        print('------------------------- DONE! -------------------------')
        return True
    except ValueError as e:
        return False
Esempio n. 3
0
def process_row(row):

    key, value = row[0], row[1]
    if '/' in value:
        values = [val.strip() for val in value.split('/')]
        for v in values:
            f = Feature(key=key, value=v)
            db.session.add(f)
        db.session.commit()
    else:
        f = Feature(key=key, value=value)
        db.session.add(f)
        db.session.commit()
Esempio n. 4
0
def test_live(app, db):
    with app.test_client() as client:
        m = Map('foo', bbox=[1, 1, 1, 1])
        db.session.add(m)
        db.session.commit()
        uuid = m.uuid.hex

        from app.live import socketio
        socketio_client = socketio.test_client(app, flask_test_client=client)
        socketio_client.emit('join', uuid)
        assert socketio_client.is_connected()

        r = socketio_client.get_received()
        assert (len(r) == 1)
        assert (r[0]['name'] == 'message')
        assert (r[0]['args'] == 'user joined')

        m.name = 'bar'
        db.session.add(m)
        db.session.commit()

        r = socketio_client.get_received()
        assert (len(r) == 1)
        assert (r[0]['name'] == 'map-updated')

        point = GeoFeature(geometry=GeoPoint([1, 1]))
        f = Feature(point)
        db.session.add(m)
        m.features.append(f)
        db.session.commit()

        r = socketio_client.get_received()
        assert (len(r) == 1)
        assert (r[0]['name'] == 'feature-created')

        f.style = {'color': 'red'}
        db.session.add(f)
        db.session.commit()

        r = socketio_client.get_received()
        assert (len(r) == 1)
        assert (r[0]['name'] == 'feature-updated')

        db.session.delete(m)
        db.session.commit()

        r = socketio_client.get_received()
        assert (len(r) == 2)
        assert (r[0]['name'] == 'map-deleted')
        assert (r[1]['name'] == 'feature-deleted')
Esempio n. 5
0
def map_features_new(map_id):
    m = Map.get(map_id)
    if not m:
        abort(404)

    if not request.json or not Feature(request.json).is_valid:
        abort(400)

    # TODO: strip input data
    feature = MapFeature(request.json)
    m.features.append(feature)
    db.session.add(m)
    db.session.commit()

    return make_response(jsonify(feature.to_dict()), 201)
Esempio n. 6
0
def test_map_delete_private(app, db):
    m = Map('foo', bbox=[1, 1, 1, 1])
    db.session.add(m)
    db.session.commit()

    token = m.gen_token()
    resp = _get_map(app, m.uuid, token)
    assert (resp.status_code == 200)

    with app.test_client() as client:
        point = GeoFeature(geometry=GeoPoint([1, 1]))
        f = Feature(point)
        m.features.append(f)
        db.session.add(m)
        db.session.commit()

        url = '/api/maps/{}'.format(m.uuid)
        resp = client.delete(url)
        assert (resp.status_code == 401
                )  # TODO: should be 404 for private maps

        headers = {'X-MAP': m.uuid, 'X-TOKEN': token}
        resp = client.delete(url, headers=headers)
        assert (resp.status_code == 204)

    assert (not Map.get(m.uuid))
    resp = _get_map(app, m.uuid, token)
    assert (resp.status_code == 404)
Esempio n. 7
0
def map_feature_edit(map_id, feature_id):
    f = MapFeature.get(feature_id)
    if not f:
        abort(404)

    if not request.json or not Feature(request.json).is_valid:
        abort(400)

    if 'properties' in request.json:
        props = request.json['properties']
        if 'iconColor' in props:
            # ensure that we deal with hex values (not rgb(r,g,b))
            if props['iconColor'].startswith('rgb'):
                rgb = re.findall(r'\d+', props['iconColor'])
                iconColor = ''.join([('%02x' % int(x)) for x in rgb])
                props['iconColor'] = '#' + iconColor

        if 'weight' in props:
            props['weight'] = int(props['weight'])

        f.style = props

    if 'geometry' in request.json:
        f.geo = request.json['geometry']

    db.session.add(f)
    db.session.commit()

    return jsonify(f.to_dict())
Esempio n. 8
0
def map_feature_delete(map_id, feature_id):
    f = MapFeature.get(feature_id)
    if not f:
        abort(404)

    db.session.delete(f)
    db.session.commit()

    return ('', 200)
Esempio n. 9
0
    def create_dummy_feature(self, client, priority=1):

        date = datetime.date(datetime.today())
        feature = Feature('Add footer', 'We need nice footer', priority, date,
                          client)
        assert isinstance(feature, Feature)
        db.session.add(feature)
        db.session.commit()
        return Feature.query.filter_by(title='Add footer').first()
Esempio n. 10
0
def index():
    """ The main view function, serves the home page of the dashboard and handles 3 forms for
    adding Features, adding Clients and adding Product Areas"""
    clients = Client.query.limit(3).all()
    products = ProductArea.query.order_by('id').limit(5).all()
    features = Feature.query.order_by('client_priority').limit(5).all()
    feature_form = FeatureForm()
    feature_form.populate_choices()
    client_form = ClientForm()
    product_form = ProductAreaForm()

    if feature_form.submit_feature.data and feature_form.validate():
        # Get the form data
        form_data = feature_form.get_data()
        # process the form data and check for existing client priority and reorder the priorities of older features if there is a clash of priorities
        Feature.save_sort_algo(form_data, db)

        return redirect(url_for('main.index'))

    if client_form.submit_client.data and client_form.validate():
        data = dict()
        data["name"] = client_form.name.data
        data["email"] = client_form.email.data
        c = Client(**data)
        db.session.add(c)
        db.session.commit()
        return redirect(url_for('main.index'))

    if product_form.submit_product.data and product_form.validate():
        data = dict()
        data["name"] = product_form.name.data
        p = ProductArea(**data)
        db.session.add(p)
        db.session.commit()
        return redirect(url_for('main.index'))

    return render_template('index.html',
                           product_list=products,
                           clients=clients,
                           features=features,
                           feature_form=feature_form,
                           client_form=client_form,
                           product_form=product_form)
Esempio n. 11
0
def add_feature():
    form = FeatureForm()
    if form.validate_on_submit():
        data = Feature(title=form.title.data,
                       description=form.description.data,
                       icon=form.icon.data)
        db.session.add(data)
        db.session.commit()
        flash("Added Successfully.", "success")
        return redirect(url_for('admin.added_feature'))
    return render_template('admin/feature/add_feature.html', form=form)
Esempio n. 12
0
def submit_request():
    if request.method == 'POST':
        new_feature = Feature(title=request.form['title'],
                              description=request.form['desc'],
                              client=request.form['client'],
                              priority=request.form['priority'],
                              target_date=request.form['target'],
                              product_area=request.form['area'])
        message, failed = increment_priorities_to_make_room(new_feature)
        flash(message, 'error' if failed else 'message')
    return redirect(url_for('index'))
Esempio n. 13
0
 def test_feature_creation(self):
     ''' Test that a given feature is created '''
     client = Client('Client A', '*****@*****.**')
     assert isinstance(client, Client)
     date = datetime.date(datetime.today())
     db.session.add(client)
     db.session.commit()
     client = Client.query.filter_by(name='Client A').first()
     feature = Feature('Add footer', 'We neeed nice footer', 1, date,
                       client)
     assert isinstance(feature, Feature)
     db.session.add(feature)
     db.session.commit()
Esempio n. 14
0
def add_request(username):
    form = RequestForm()
    if form.validate_on_submit():
        feature = Feature(title=form.title.data,
                          description=form.description.data,
                          product_area=form.product_area.data,
                          clients=form.clients.data,
                          priority=form.priority.data,
                          target_date=form.target_date.data,
                          requestor=current_user)
        db.session.add(feature)
        db.session.commit()
        flash('Your feature request has been recorded.')
        return redirect(url_for('display_requests', user_id=current_user.id))
    return render_template('add_request.html', user=user, form=form)
Esempio n. 15
0
def index():
    form = EditingForm()
    d = []
    l = []
    for feature in Feature.query.all():
        if feature.geojson:
            s = json.loads(feature.geojson[40:len(feature.geojson) - 2])

            print(type(s))
            s['properties'] = {}
            s['properties']['class'] = feature.name_class
            s['properties']['name'] = feature.name
            print(type(s['properties']))
            print(s)

            #if s['geometry']['type']=='Point':
            l.append(s['id'])
            s = json.dumps(s)
            d.append(json.loads(s))
    #l = json.dumps(l)

    dd = json.dumps(d)
    #print(dd)

    if form.validate_on_submit():
        feature = Feature(
            geojson=form.new_coordinates.data,
            #geojson_2=form.new_coordinates.data,
            name_class=form.type.data,
            name=form.name.data,
        )
        db.session.add(feature)
        db.session.commit()
    return render_template("index.html",
                           title='Home Page',
                           form=form,
                           d=dd,
                           list=l)
Esempio n. 16
0
def db_fill_data(import_values=True):
    from app.models import Subdomain, ModelType, Feature, User

    Subdomain(domain=Subdomain.Domain.general, name="Type 1").save(False)
    Subdomain(domain=Subdomain.Domain.general, name="Type 2").save(False)
    Subdomain(domain=Subdomain.Domain.general, name="Type 3").save(False)
    Subdomain(domain=Subdomain.Domain.general, name="Type 4").save(False)
    Subdomain(domain=Subdomain.Domain.general, name="Type 5").save(False)
    Subdomain(domain=Subdomain.Domain.healthcare, name="Cancer").save(False)
    Subdomain(domain=Subdomain.Domain.healthcare, name="Diabetic").save(False)
    Subdomain(domain=Subdomain.Domain.healthcare,
              name="Dermatology").save(False)
    Subdomain(domain=Subdomain.Domain.healthcare, name="Radiology").save(False)
    Subdomain(domain=Subdomain.Domain.healthcare, name="Pharma").save(False)
    Subdomain(domain=Subdomain.Domain.healthcare, name="Genomics").save(False)
    Subdomain(domain=Subdomain.Domain.healthcare, name="Cardiac").save(False)
    Subdomain(domain=Subdomain.Domain.financial,
              name="Credit Application").save(False)
    Subdomain(domain=Subdomain.Domain.financial,
              name="Insurance Claims").save(False)
    Subdomain(domain=Subdomain.Domain.financial,
              name="Investment Portfolios").save(False)
    Subdomain(domain=Subdomain.Domain.financial,
              name="Financial Instruments").save(False)

    ModelType(name="Model1").save(False)
    ModelType(name="Model2").save(False)
    ModelType(name="Model3").save(False)
    ModelType(name="Model4").save(False)
    ModelType(name="Model5").save(False)
    Feature(name="Age", short_name="age").save()
    Feature(name="Number of Pregnancies", short_name="preg").save(False)
    Feature(name="Blood Pressure", short_name="pres").save(False)
    Feature(name="Skin Thickness", short_name="skin").save(False)
    Feature(name="Body Mass Index", short_name="mass").save(False)
    Feature(name="Diabetes Family Pedigree", short_name="pedi").save(False)
    Feature(name="Glucose", short_name="plas").save(False)
    Feature(name="Insulin", short_name="test").save()

    Feature(name="SeriousDlqin2yrs", short_name="SeriousDlqin2yrs").save()
    Feature(
        name="Revolving Utilization of Unsecured Lines",
        short_name="RevolvingUtilizationOfUnsecuredLines",
    ).save()
    Feature(
        name="Number of times 30-59 days past due not worse",
        short_name="NumberOfTime30-59DaysPastDueNotWorse",
    ).save()
    Feature(name="Debt Ratio", short_name="DebtRatio").save()
    Feature(name="Monthly Income", short_name="MonthlyIncome").save()
    Feature(
        name="Number of Open Credit Lines And Loans",
        short_name="NumberOfOpenCreditLinesAndLoans",
    ).save()
    Feature(name="Number of times 90 days late",
            short_name="NumberOfTimes90DaysLate").save()
    Feature(name="Number Real Estate Loans or Lines",
            short_name="NumberRealEstateLoansOrLines").save()
    Feature(
        name="Number of times 60-89 days past due not worse",
        short_name="NumberOfTime60-89DaysPastDueNotWorse",
    ).save()
    Feature(name="Number of Dependents",
            short_name="NumberOfDependents").save()

    user = User(username=ADMIN_USERNAME, email=ADMIN_EMAIL)
    user.password = ADMIN_PASSWORD
    user.save()
Esempio n. 17
0
def create_app(config, blog_config):
    """This initiates the Flask app and starts your app engine instance.
    Startup Steps:
    1. Instantiate the Flask app with the config settings.
    2. Register bluprints.
    3. Create the Contact and About Pages in the datastore if they don't exist yet.
    4. Load the blog_config settings from the datatstore. Or add them if they don't exist yet.
    """

    logging.info('STARTUP: Getting ready to launch the Flask App')

    app = Flask(__name__)
    app.config.update(config)

    # Register blueprints

    logging.info('STARTUP: Register Blueprints')

    from .main import app as main_blueprint
    app.register_blueprint(main_blueprint, url_prefix='/')

    from .editor import app as editor_blueprint
    app.register_blueprint(editor_blueprint, url_prefix='/editor')

    # Add Contact and About pages to the datastore when first launching the blog

    logging.info('STARTUP: Set up Contact and About pages')

    # Contact page creation
    query = Article.query(Article.slug == 'contact-page')
    result = query.fetch(1)

    if result:
        logging.info('STARTUP: Contact page exists')
    else:
        logging.info('STARTUP: Creating a contact page')
        contact_page = Article()
        contact_page.title1 = 'Contact Me'
        contact_page.title2 = 'Have questions? I have answers (maybe).'
        contact_page.slug = 'contact-page'
        contact_page.author = ''
        contact_page.content = 'Want to get in touch with me? Fill out the form below to send me a message and I ' \
                               'will try to get back to you within 24 hours! '
        contact_page.published = False
        contact_page.put()

    # About page creation
    query = Article.query(Article.slug == 'about-page')
    result = query.fetch(1)

    if result:
        logging.info('STARTUP: About page exists')
    else:
        logging.info('STARTUP: Creating an about page')
        about_page = Article()
        about_page.title1 = 'About Me'
        about_page.title2 = 'This is what I do.'
        about_page.slug = 'about-page'
        about_page.author = ''
        about_page.content = ''
        about_page.published = False
        about_page.put()

    # Register blog configurations
    # The Blog is initially configured with blog_conf settings
    # The settings are added to the datastore and will take precedence from now on
    # You can change the settings in the datastore.
    # The settings are only updated on Startup, so you need to restart the instances to apply changes.

    logging.info('STARTUP: Register Blog Configurations')

    query = Feature.query()

    for feature in blog_config:

        # TODO: Add the accesslist to the datastore. The access list is still read only from the config file.
        if feature == 'EDITOR_ACCESS_LIST':
            pass

        # TODO: The posts limit is an int and needs to be converted. Find a better way of doing this.
        elif feature == 'POSTS_LIST_LIMIT':
            result = query.filter(Feature.title == feature).fetch()
            if result:

                logging.info('STARTUP: Loading {}'.format(result[0].title))

                blog_config['POSTS_LIST_LIMIT'] = int(result[0].value)

            else:

                logging.info('STARTUP: Adding to datastore: {}'.format(feature))

                f = Feature()
                f.title = feature
                f.value = str(blog_config[feature])
                f.put()

        # Load the configs or add them to the datastore if they don't exist yet
        else:
            result = query.filter(Feature.title == feature).fetch()
            if result:

                logging.info('STARTUP: Loading {}'.format(result[0].title))

                blog_config[result[0].title] = result[0].value

            else:

                logging.info('STARTUP: Adding to datastore: {}'.format(feature))

                f = Feature()
                f.title = feature
                f.value = blog_config[feature]
                f.put()

    # Startup complete
    logging.info('STARTUP: READY TO ROCK!!!')

    return app
    def test_admin_list_features(self):
        """
        Test that the features module is functional
        """
        # create admin
        admin = User(username="******",
                     email="*****@*****.**",
                     password="******",
                     is_admin=True)
        db.session.add(admin)
        db.session.commit()

        # create product area
        product_area = ProductArea(product_area="product_area A")
        db.session.add(product_area)

        # create project
        project = Project(project_name="Project A")
        db.session.add(project)

        # create client
        client = Client(client_name="Client A")
        db.session.add(client)
        db.session.commit()

        # create feature
        feature1 = Feature(title="update feature",
                           description="update description ",
                           client_priority=1,
                           target_date=datetime.now(),
                           product_area_id=product_area.id,
                           client_id=client.id,
                           project_id=project.id,
                           user_id=admin.id)
        db.session.add(feature1)
        db.session.commit()

        # login admin
        # login with the new account
        response = self.client.post(url_for('auth.login'),
                                    data={
                                        'email': '*****@*****.**',
                                        'password': '******'
                                    },
                                    follow_redirects=True)
        self.assertTrue(re.search('admin', response.data))

        # check users list
        response = self.client.get(url_for('hrequests.index'))
        self.assertTrue(response.status_code == 200)

        #confirm the list of users in the page
        self.assertTrue(feature1.title in response.data)

        # post a new feature
        response = self.client.post(url_for('hrequests.create'),
                                    data={
                                        'title': 'Feature A',
                                        'description': 'Desctiption A',
                                        'product_area_id': product_area.id,
                                        'client_priority': 1,
                                        'target_date': datetime.now(),
                                        'client': client.id,
                                        'project': project.id,
                                        'user': admin.id,
                                    },
                                    follow_redirects=True)
        self.assertTrue(re.search('Feature A', response.data))

        # test that the edit feature page is accessible
        response = self.client.get(url_for('hrequests.edit', id=feature1.id))
        self.assertTrue(re.search('update feature', response.data))

        # test the edit feature is functional
        response = self.client.post(url_for('hrequests.edit', id=feature1.id),
                                    data={
                                        'title': 'Feature X',
                                        'description': feature1.description,
                                        'client_priority':
                                        feature1.client_priority,
                                        'target_date': "03/03/2018",
                                        'product_area':
                                        feature1.product_area_id,
                                        'client': feature1.client_id,
                                        'project': feature1.project_id,
                                        'user': admin.id
                                    })
        self.assertTrue(302 == response.status_code)

        # delete requests page
        response = self.client.post(url_for('hrequests.delete'),
                                    data={
                                        'request_id': feature1.id,
                                    },
                                    follow_redirects=True)
        self.assertTrue(
            re.search('You have successfully deleted the Feature Request',
                      response.data))
Esempio n. 19
0
def img_feat(img_ids,
             net,
             transformer,
             save_path,
             type_name,
             is_patch=False,
             normalize=True):

    img_arrays = []
    savenames = {}
    savenames['fc7'] = []
    # savenames['fc6'] = []
    # good_img_ids = []
    feat = {}
    feat['fc7'] = []
    # feat['fc6'] = []
    normsavenames = []
    for cnt, idx in enumerate(img_ids):
        print cnt
        check = Feature.query.filter(Feature.patch_id == idx).filter(
            Feature.type == type_name + '_fc7').first()
        if check != None:
            print 'skipping'
            continue
        subdir = str(idx)[:2]
        if not os.path.exists(os.path.join(save_path, subdir)):
            os.makedirs(os.path.join(save_path, subdir))
            os.makedirs(os.path.join(save_path, subdir, 'norm'))
        sname = os.path.join(save_path, subdir, 'img_%d' % idx)
        if not os.path.exists(sname):
            savenames['fc7'].append(sname + '_fc7.jbl')
            # savenames['fc6'].append(sname+'_fc6.jbl')
            # good_img_ids.append(idx)
        else:
            continue

        if is_patch:
            img = Patch.query.get(idx).crop(savename=None, make_square=True)
        else:
            img = Image.query.get(idx).to_array()
        if len(img.shape) == 2:
            img = img.reshape(img.shape[0], img.shape[1], 1).repeat(3, 2)

        net.blobs['data'].data[...] = transformer.preprocess('data', img)
        out = net.forward(blobs=['fc6'])
        feat['fc7'].append(out['fc7'])
        # feat['fc6'].append(out['fc6'])

        try:
            joblib.dump(feat['fc7'][-1], savenames['fc7'][-1])
            if is_patch:
                f = Feature(type=type_name + '_fc7',
                            location=savenames['fc7'][-1],
                            patch_id=idx)
            else:
                f = Feature(type=type_name + '_fc7',
                            location=savenames['fc7'][-1],
                            image_id=idx)
            db.session.add(f)
            # joblib.dump(feat['fc6'][-1], savenames['fc6'][-1])
            # if is_patch:
            #     f6 = Feature(type = type_name+'_fc6', location = savenames['fc6'][-1], patch_id = idx)
            # else:
            #     f6 = Feature(type = type_name+'_fc6', location = savenames['fc6'][-1], image_id = idx)
            # db.session.add(f6)
            db.session.commit()

            print 'idx %d' % idx
            sname = os.path.join(save_path, subdir, 'norm', 'img_%d' % idx)
            if not os.path.exists(sname):
                normsavenames.append(sname)
            else:
                continue

            print normsavenames[-1] + '_fc7.jbl'
            joblib.dump(norm_convnet_feat(feat['fc7'][-1]),
                        normsavenames[-1] + '_fc7.jbl')
            if is_patch:
                f2 = Feature(type=type_name + '_fc7_norm',
                             location=normsavenames[-1] + '_fc7.jbl',
                             patch_id=idx)
            else:
                f2 = Feature(type=type_name + '_fc7_norm',
                             location=normsavenames[-1] + '_fc7.jbl',
                             image_id=idx)
            db.session.add(f2)
            # joblib.dump(norm_convnet_feat(feat['fc6'][-1]), normsavenames[-1]+'_fc6.jbl')
            # if is_patch:
            #     f3 = Feature(type = type_name+'_fc6_norm', location = normsavenames[-1]+'_fc6.jbl', patch_id = idx)
            # else:
            #     f3 = Feature(type = type_name+'_fc6_norm', location = normsavenames[-1]+'_fc6.jbl', image_id = idx)
            # db.session.add(f3)
            db.session.commit()
        except:
            print "Unexpected error:", sys.exc_info()
            print 'something broke with this pid/img_id', idx
Esempio n. 20
0
def index():
    form1 = BannerForm()
    form2 = PromotionForm()
    form3 = FeatureForm()
    productform = ProductForm()
    productform.catid.choices = [
        (c.id, c.subcategories) for c in db.session.query(SubCategories).all()
    ]
    productform.pdbid.choices = [(p.id, p.productbrand)
                                 for p in db.session.query(ProductBrand).all()]
    if productform.validate_on_submit():
        product = Product(product=productform.product.data,
                          volumn=productform.volumn.data,
                          price=productform.price.data,
                          details=productform.details.data,
                          origin=productform.origin.data,
                          productimage=productform.url.data,
                          categories_id=productform.catid.data,
                          productbrand_id=productform.pdbid.data,
                          pricedown=productform.pricedown.data)
        db.session.add(product)
        db.session.commit()
        flash(_('New Product added'))
        return redirect(url_for('main.index'))
    elif form3.validate_on_submit():
        feature = Feature(title=form3.title.data,
                          description=form3.description.data,
                          url=form3.url.data)
        db.session.add(feature)
        db.session.commit()
        flash(_('New Promotion added'))
        return redirect(url_for('main.index'))
    elif form2.validate_on_submit():
        promotion = Promotion(name=form2.name.data, url=form2.url.data)
        db.session.add(promotion)
        db.session.commit()
        flash(_('New Promotion added'))
        return redirect(url_for('main.index'))
    elif form1.validate_on_submit():
        banneritem = Banner(banner=form1.banner.data)
        db.session.add(banneritem)
        db.session.commit()
        flash(_('New Banner added'))
        return redirect(url_for('main.index'))
    banners = Banner.query.order_by(Banner.id)
    categoriess = Categories.query.order_by(Categories.categories)
    subcats = SubCategories.query.order_by(SubCategories.subcategories)
    promotions = Promotion.query.order_by(Promotion.id)
    features = Feature.query.all()
    page = request.args.get('page', 1, type=int)
    pdbrands = ProductBrand.query.order_by(func.random()).paginate(
        page, current_app.config['PRODUCTBRAND_PER_PAGE'], False)
    newproducts = Product.query.order_by(Product.id.desc()).paginate(
        page, current_app.config['NEWPRODUCT_PER_PAGE'], False)
    reviews = Review.query.all()
    return render_template('index.html',
                           title=_('Home'),
                           form1=form1,
                           form2=form2,
                           form3=form3,
                           banners=banners,
                           categoriess=categoriess,
                           subcats=subcats,
                           newproducts=newproducts.items,
                           promotions=promotions,
                           features=features,
                           pdbrands=pdbrands.items,
                           page=page,
                           productform=productform,
                           reviews=reviews)