Exemple #1
0
 def test_color_validation(self):
     with self.app.app_context():
         f = SearchForm()
         f.select.data = "Color"
         f.search.data = "pink"
         f.validate()
         err_msg = [
             f"Please use one of {color_list} for your color selection"
         ]
         self.assertEqual(f.errors["select"], err_msg)
Exemple #2
0
 def test_orientation_validation(self):
     with self.app.app_context():
         f = SearchForm()
         f.select.data = "Orientation"
         f.search.data = "rounded"
         f.validate()
         err_msg = [
             f"Please use one of {orientation_list} for your orientation selection"
         ]
         self.assertEqual(f.errors["select"], err_msg)
Exemple #3
0
def search():
    form = SearchForm()
    if not form.validate():
        return redirect(url_for('index'))
    results, total = Oggetto.search(form.q.data)

    render_template('search.html', results=results)
def search():
    form = SearchForm()
    if request.method == 'POST':
        if form.validate() == False:
            flash('Search term is required.')
            return redirect(request.referrer)
        else:
            search_term = form.data['term']
            results = text_search(search_term)
            return render_template('searchresults.html', **locals())
Exemple #5
0
def search():
    form = SearchForm(request.form)
    blogs = UniqueList()
    if request.method == 'POST' and form.validate():
        key = request.form.get("keyboard")
        blogs.extend(Article.query.filter_by(select=key).all())
        blogs.extend(
            Article.query.filter(Article.title.like("%{}%".format(key))).all())
        blogs.extend(
            Article.query.filter(Article.body.like("%{}%".format(key))).all())
        return render_template('control/search.html', key=key, blogs=blogs)
    return render_template('control/search.html', blogs=blogs, form=form)
 def post(self):
     form = SearchForm(meta=dict(csrf=False))
     if form.validate():
         word = form.word.data
         query = PostModel.get_query()\
             .filter(or_(PostModel.content.like(f'%{word}%'),
                          PostModel.title.like(f'%{word}%')))
         data = defaultdict(list)
         for p in query.all():
             data[p.type].append(p.asdict())
         return dict(code=200, msg='success', data=data)
     else:
         return dict(code=400, msg='params error', data=form.errors)
def students():
    form = SearchForm()
    if request.method == 'POST' and form.validate():
        filteredStudents = Students.search(form.choice.data, form.search.data)
        students = filteredStudents
        if filteredStudents is False:
            flash('Search Error! "{}" does not exist on our list or you have the wrong category'.format(
                form.search.data), category='danger')
            return redirect(url_for('students'))
        return render_template('display_students.html', form=form, filtered=students, students="")
    else:
        students = Students.all()
        return render_template('display_students.html', form=form, students=students, filtered="")
def students():
    form = SearchForm()
    if request.method == 'POST' and form.validate():
        filteredStudents = Students.search(form.choice.data, form.search.data)
        students = filteredStudents
        return render_template('display_students.html',
                               form=form,
                               filtered=students,
                               students="")
    else:
        students = Students.all()
        return render_template('display_students.html',
                               form=form,
                               students=students,
                               filtered="")
Exemple #9
0
def search():		
	search_form = SearchForm(request.form)
	if not search_form.validate():
		return render_template('search_result.html', books = [], search_form = search_form)

	search_phrase = "%%%s%%" % search_form.text.data

	books_by_title = Book.query.filter(Book.title.ilike(search_phrase)).all() if search_form.by_title.data else []
	authors_by_name = Author.query.filter(Author.name.ilike(search_phrase)).all() if search_form.by_author.data else []

	books = set(books_by_title + [authorship.book for author in authors_by_name for authorship in author.authorships])
	
	#form = SearchForm().set_defaults()
	form = SearchForm()	
	return render_template('search_result.html', books = books, search_form = form)
Exemple #10
0
def search(pattern=None, page=1):
    form = SearchForm()
    if request.method == 'POST' and form.validate():
        pattern = form.search.data
        return redirect(url_for('search', pattern=pattern, page=page))

    if pattern is not None:
        results = Post.objects.search_text(pattern).paginate(
            page=page, per_page=items_per_page)
        if not results.items:  #results.items is a []
            return render_template('search_not_found.html.j2', pattern=pattern)
        return render_template('search.html.j2',
                               pattern=pattern,
                               posts=results)

    return render_template('search.html.j2', posts=None, form=form)
Exemple #11
0
def search():
	form  = SearchForm()
	if form.validate(): 
		#current_milli_time = lambda: int(round(time.time() * 1000))
		#start_time = current_milli_time()
		start_time = time.time()
		#print(start_time)
		#query = form.q.data
		query = request.args.get('q')
		results = expertenservice(query)
		#q = query_index_multi('websites', query)
		#time_diff = current_milli_time() - start_time
		end_time = time.time()
		time_diff = round(end_time - start_time, 2)
		print(time_diff)
		return render_template('results.html', results = results, form = form, time_diff = time_diff)
	else: 
		return render_template('search.html', form = form)
Exemple #12
0
def search():
    """
    Blog Search View
    """
    form = SearchForm()
    if not form.validate():
        return redirect(url_for('index'))
    page = request.args.get('page', 1, type=int)
    posts, total = Posts.search(request.args['q'], page,
                                current_app.config['POSTS_PER_PAGE'])
    next_url = url_for('search', q=form.data, page=page + 1) \
        if total > page * current_app.config['POSTS_PER_PAGE'] else None
    prev_url = url_for('search', q=form.data, page=page - 1) \
        if page > 1 else None

    return render_template('search.html',
                           posts=posts,
                           next_url=next_url,
                           prev_url=prev_url)
Exemple #13
0
def search():
    '''
    Generic search page
    '''
    form = SearchForm(request.args, csrf_enabled=False)
    if not form.validate():
        return render_template('search.html', form=form)
    else:
        result_tabs = []
        active_result_tab = None
        query = User.query_in_deployment()  #pylint: disable=no-member

        if (form.questionnaire_area.data
                and form.questionnaire_area.data != 'ZZ'):
            questionnaire_id = form.questionnaire_area.data
            num_skills_column = func.count(UserSkill.id).label('num_skills')
            query = query.add_column(num_skills_column).\
                filter(UserSkill.user_id == User.id).\
                filter(UserSkill.name.like(questionnaire_id + "_%")).\
                filter(UserSkill.level == form.skill_level.data).\
                group_by(User).\
                order_by(num_skills_column.desc())

            base_args = request.args.copy()
            if 'skill_level' in base_args:
                del base_args['skill_level']

            tab_names = (
                ('LEVEL_I_CAN_DO_IT', gettext('Practitioners')),
                ('LEVEL_I_CAN_EXPLAIN', gettext('Explainers')),
                ('LEVEL_I_CAN_REFER', gettext('Connectors')),
                ('LEVEL_I_WANT_TO_LEARN', gettext('Peers')),
            )

            for level_id, tab_label in tab_names:
                tab_args = base_args.copy()
                tab_args['skill_level'] = str(LEVELS[level_id]['score'])
                tab_url = '%s?%s#results' % (url_for('views.search'),
                                             urlencode(tab_args))
                if form.skill_level.data == LEVELS[level_id]['score']:
                    active_result_tab = level_id
                result_tabs.append((level_id, tab_label, tab_url))
        else:
            # Add fake rank of 0 for now
            query = query.add_column('0')

        if form.country.data and form.country.data != 'ZZ':
            query = query.filter(User.country == form.country.data)

        if form.locale.data and form.locale.data != 'ZZ':
            query = query.join(User.languages).filter(
                UserLanguage.locale.in_([form.locale.data]))

        if (form.expertise_domain_name.data
                and form.expertise_domain_name.data != 'ZZ'):
            query = query.join(User.expertise_domains).filter(
                UserExpertiseDomain.name.in_([form.expertise_domain_name.data
                                              ]))

        if form.fulltext.data:
            ftquery = "%" + form.fulltext.data + "%"
            query = query.filter(
                or_(User.first_name.ilike(ftquery),
                    User.last_name.ilike(ftquery),
                    User.organization.ilike(ftquery),
                    User.position.ilike(ftquery), User.projects.ilike(ftquery),
                    (User.first_name + ' ' + User.last_name).ilike(ftquery)))

        return render_template('search.html',
                               result_tabs=result_tabs,
                               active_result_tab=active_result_tab,
                               form=form,
                               results=query.limit(20).all())
def get_search_results():
    data = MultiDict(mapping=request.json)
    form = SearchForm(data)
    if form.validate():
        data = request.json
        user = User.query.get(data["userId"])
        user_dict = user.to_dict()

        user_lat = user_dict["lat"]
        user_lng = user_dict["lng"]
        coords_dict = reverse_haversine(target_distance=data["radius"],
                                        lat=user_lat,
                                        lng=user_lng)

        min_lat = coords_dict["min_lat"]
        max_lat = coords_dict["max_lat"]
        min_lng = coords_dict["min_lng"]
        max_lng = coords_dict["max_lng"]

        if data["firstName"] and data["lastName"]:
            users = [
                user.to_dict()["id"] for user in User.query.filter(
                    and_(
                        between(User.lat, min_lat, max_lat),
                        between(User.lng, min_lng, max_lng),
                        User.id != data["userId"],
                        func.soundex(User.first_name) == func.soundex(
                            data["firstName"]),
                        func.soundex(User.last_name) == func.soundex(
                            data["lastName"]))).all()
            ]
        elif data["firstName"]:
            users = [
                user.to_dict()["id"] for user in User.query.filter(
                    and_(
                        between(User.lat, min_lat, max_lat),
                        between(User.lng, min_lng, max_lng),
                        User.id != data["userId"],
                        func.soundex(User.first_name) == func.soundex(
                            data["firstName"]))).all()
            ]
        else:
            users = [
                user.to_dict()["id"] for user in User.query.filter(
                    and_(between(User.lat, min_lat, max_lat),
                         between(User.lng, min_lng, max_lng),
                         User.id != data["userId"])).all()
            ]

        profile_insts = db.session.query(
            profile_instruments.c.profile_id).filter(
                and_(
                    profile_instruments.c.profile_id.in_(users),
                    profile_instruments.c.instrument_id.in_(
                        data["instruments"])))
        profile_stls = db.session.query(profile_styles.c.profile_id).filter(
            and_(profile_styles.c.profile_id.in_(users),
                 profile_styles.c.style_id.in_(data["styles"])))
        profiles = profile_insts.intersect(profile_stls).all()

        return {
            "searchResults": list(set([profile[0] for profile in profiles]))
        }

    else:
        res = make_response({"errors": format_errors(form.errors)}, 401)
        return res
Exemple #15
0
def search():
    '''
    Generic search page
    '''
    form = SearchForm(request.args, csrf_enabled=False)
    if not form.validate():
        return render_template('search.html', form=form)
    else:
        result_tabs = []
        active_result_tab = None
        query = User.query_in_deployment() #pylint: disable=no-member

        if (form.questionnaire_area.data and
            form.questionnaire_area.data != 'ZZ'):
            questionnaire_id = form.questionnaire_area.data
            num_skills_column = func.count(UserSkill.id).label('num_skills')
            query = query.add_column(num_skills_column).\
                filter(UserSkill.user_id == User.id).\
                filter(UserSkill.name.like(questionnaire_id + "_%")).\
                filter(UserSkill.level == form.skill_level.data).\
                group_by(User).\
                order_by(num_skills_column.desc())

            base_args = request.args.copy()
            if 'skill_level' in base_args:
                del base_args['skill_level']

            tab_names = (
                ('LEVEL_I_CAN_DO_IT', gettext('Practitioners')),
                ('LEVEL_I_CAN_EXPLAIN', gettext('Explainers')),
                ('LEVEL_I_CAN_REFER', gettext('Connectors')),
                ('LEVEL_I_WANT_TO_LEARN', gettext('Peers')),
            )

            for level_id, tab_label in tab_names:
                tab_args = base_args.copy()
                tab_args['skill_level'] = str(LEVELS[level_id]['score'])
                tab_url = '%s?%s#results' % (
                    url_for('views.search'),
                    urlencode(tab_args)
                )
                if form.skill_level.data == LEVELS[level_id]['score']:
                    active_result_tab = level_id
                result_tabs.append((level_id, tab_label, tab_url))
        else:
            # Add fake rank of 0 for now
            query = query.add_column('0')

        if form.country.data and form.country.data != 'ZZ':
            query = query.filter(User.country == form.country.data)

        if form.locale.data and form.locale.data != 'ZZ':
            query = query.join(User.languages).filter(UserLanguage.locale.in_(
                [form.locale.data]))

        if (form.expertise_domain_name.data and
            form.expertise_domain_name.data != 'ZZ'):
            query = query.join(User.expertise_domains).filter(
                UserExpertiseDomain.name.in_(
                    [form.expertise_domain_name.data]
                )
            )

        if form.fulltext.data:
            ftquery = "%" + form.fulltext.data + "%"
            query = query.filter(or_(
                User.first_name.ilike(ftquery),
                User.last_name.ilike(ftquery),
                User.organization.ilike(ftquery),
                User.position.ilike(ftquery),
                User.projects.ilike(ftquery),
                (User.first_name + ' ' + User.last_name).ilike(ftquery)
            ))

        return render_template('search.html',
                               result_tabs=result_tabs,
                               active_result_tab=active_result_tab,
                               form=form,
                               results=query.limit(20).all())
Exemple #16
0
def index():
    # receive parameters from url query string
    params = get_parameters()

    # initialize forms:
    addform = PostBookmarkForm()
    editform = EditBookmarkForm()
    deleteform = DeleteBookmarkForm()
    deletetagform = DeleteTagForm()
    searchform = SearchForm()

    # Add entry:
    if addform.validate() and "add" in request.form:
        new_bookmark_data = {}
        new_bookmark_data['url'] = addform.url.data
        new_bookmark_data['title'] = addform.title.data
        new_bookmark_data['description'] = addform.description.data
        new_bookmark_data['date'] = datetime.datetime.utcnow()
        new_bookmark_data['tags'] = [
            t.strip() for t in (addform.tags.data.split(',') or [])
        ]
        add_bookmark_from_dict(new_bookmark_data)
        flash(f"Add: {new_bookmark_data['url']}", 'success')
        return redirect(request.url)

    # Edit entry:
    if editform.validate() and "edit" in request.form:
        my_bookmark = Bookmark.query.filter_by(id=editform.myid.data).first()
        my_bookmark.url = editform.url.data
        my_bookmark.title = editform.title.data
        my_bookmark.description = editform.description.data
        my_bookmark.tags.clear()
        new_tags = [t.strip() for t in (addform.tags.data.split(',') or [])]
        for t in new_tags:
            db_tag = fetch_or_add_tag(t)
            my_bookmark.tags.append(db_tag)
        db.session.commit()
        flash(f"Edited: {my_bookmark.url}", 'success')
        return redirect(request.url)

    # Delete entry:
    if deleteform.validate() and "delete" in request.form:
        my_bookmark = Bookmark.query.filter_by(id=deleteform.myid.data).first()
        db.session.delete(my_bookmark)
        db.session.commit()
        flash(f"Deleted: {my_bookmark.url}", 'danger')
        return redirect(request.url)

    # Delete tag:
    if deletetagform.validate() and "delete_tag" in request.form:
        my_tag = Tag.query.filter_by(name=deletetagform.tagname.data).first()
        db.session.delete(my_tag)
        db.session.commit()
        flash(f"Deleted tag: {my_tag.name}", 'danger')
        params['tag'] = None
        return redirect(
            url_for(
                'index',
                search=params['search'],
                page=params['page'],
                order=params['order'],
                tag=params['tag'],
                tags_order=params['tags_order'],
            ))

    # Perform Search:
    # if 'search' in params and params['search'] is not None:
    #     return f"{params['search']}"
    if searchform.validate() and "submit_search" in request.form:
        params['search'] = searchform.search.data
        return redirect(
            url_for(
                'index',
                search=params['search'],
                page=params['page'],
                order=params['order'],
                tag=params['tag'],
                tags_order=params['tags_order'],
            ))

    # Build sql query:
    query = build_query(params)
    page = request.args.get('page', 1, type=int)
    paginate_query = query.paginate(page, app.config['ITEM_PER_PAGE'], False)

    # Build pagedata
    pagedata = create_pagedata(query, params)

    return render_template("index.html",
                           data=paginate_query.items,
                           addform=addform,
                           editform=editform,
                           deleteform=deleteform,
                           searchform=searchform,
                           deletetagform=deletetagform,
                           pagedata=pagedata)