def search(request): form = myforms.SearchForm() results = None if request.method == 'POST': form = myforms.SearchForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] name = form.cleaned_data['name'] if email: results = User.objects.filter(email=email) elif name: try: name_l = name.split(' ') first_name = name_l[0] last_name = name_l[1] except IndexError: first_name = '' last_name = '' results = User.objects.filter(first_name__iexact=first_name, last_name__iexact=last_name) return render_to_response('search.html', { 'form': form, 'results': results }, context_instance=RequestContext(request))
def search_form(request, object_type): """Display a form so that the user can perform search actions.""" if request.method == 'POST': form = forms.SearchForm(request.POST) if form.is_valid(): keyword = form.cleaned_data['keyword'] return http.HttpResponseRedirect( urlresolvers.reverse('search', args=[object_type, keyword])) else: form = forms.SearchForm() return shortcuts.render_to_response('search_form.html', {'form': form, 'root_url' : CONFIG['ROOT']}, context_instance=template.RequestContext(request))
def my_games(): """ shows all games downloaded by the user :return: my games page html or redirect to home page """ page = request.args.get('page', 1, type=int) prev_search = request.args.get('prev_search', "", type=str) if current_user.is_authenticated: search = forms.SearchForm() if request.method == 'POST': return redirect( url_for('my_games', page=page, prev_search=search.search_bar.data)) if prev_search: search.search_bar.data = prev_search games = search_games_downloaded(prev_search, user=current_user, page=page) else: games = search_games_downloaded("", user=current_user, page=page) return render_template("my_games.html", form=search, games=games, utcnow=datetime.utcnow()) else: flash("you have to login", "is-danger") return redirect(url_for("home"))
def base_options(): # a function for the options required by every page return { 'pages': Page.query.all(), 'current_user': current_user, 'search_form': forms.SearchForm() }
def process_search(): form = forms.SearchForm(request.form) if form.validate() == False: flash("You didn't search for anything silly.") return render_template('search.html', user=current_user) else: posts = [] ids_no_posts = [] search_terms = form.search_term.data.split() for search_term in search_terms: user_ids = model.search_user(search_term) if user_ids == []: flash("Oh no! That person doesn't exist.") return render_template('search.html', user=current_user) for user_id in user_ids: post = model.get_last_post(user_id) if post: posts.append(post) else: ids_no_posts.append(user_id) users_no_posts = [] for user_id in ids_no_posts: user = model.get_user_by_id(user_id) users_no_posts.append(user) posts = list(set(posts)) users_no_posts = list(set(users_no_posts)) return render_template('searchresults.html', user=current_user, posts=posts, no_posts=users_no_posts)
def root(): form = forms.SearchForm() searchterm = form.searchterm.data shopname = form.shopname.data minPrice = form.minPrice.data maxPrice = form.maxPrice.data return searchshoppage(searchterm, shopname, minPrice, maxPrice)
def search(): form = forms.SearchForm() if form.validate_on_submit(): username = form.search.data allUsernames = metallic.getAccounts() # list of tuples # filter the search results matchingAccounts = [] for account in allUsernames: if username in account[0]: matchingAccounts.append(account) if len(matchingAccounts) == 0: flash("No matching usernames were found.", 'danger') # render the page again, but this time with the search results return render_template('search.html', title="Search", form=form, matchingAccounts=matchingAccounts) return render_template('search.html', title="Search", form=form, matchingAccounts=None)
def render_nave(num): search_form = forms.SearchForm(request.form) if request.method == "POST": peliculas = requests.get("https://swapi.co/api/films/?search={}".format(search_form.criteria.data)) json_pelis = peliculas.json() peliculas = json_pelis["results"] peliculas_2 = list() for peli in peliculas: peliculas_2.append(parse(peli)) personajes = requests.get("https://swapi.co/api/people/?search={}".format(search_form.criteria.data)) json_pers = personajes.json() personajes = json_pers["results"] personajes_2 = list() for per in personajes: personajes_2.append(perparse(per)) naves = requests.get("https://swapi.co/api/starships/?search={}".format(search_form.criteria.data)) json_naves = naves.json() naves = json_naves["results"] naves_2 = list() for na in naves: naves_2.append(navparse(na)) planetas = requests.get("https://swapi.co/api/planets/?search={}".format(search_form.criteria.data)) json_plans = planetas.json() planetas = json_plans["results"] planetas_2 = list() for pl in planetas: planetas_2.append(planparse(pl)) return render_template("search.html", peliculas = peliculas_2, personajes = personajes_2 , naves= naves_2, planetas= planetas_2, form = search_form) nave = requests.get("https://swapi.co/api/starships/{}".format(num)) json_nav = navparse(nave.json()) return render_template("ships.html", n=json_nav, form = search_form)
def search(request): num_pages = 0 limit = None nonvouched_only = False picture_only = False people = [] show_pagination = False form = forms.SearchForm(request.GET) groups = None curated_groups = None if form.is_valid(): query = form.cleaned_data.get('q', u'') limit = form.cleaned_data['limit'] vouched = False if form.cleaned_data['nonvouched_only'] else None profilepic = True if form.cleaned_data['picture_only'] else None page = request.GET.get('page', 1) curated_groups = Group.get_curated() # If nothing has been entered don't load any searches. if not (not query and vouched is None and profilepic is None): profiles = UserProfile.search(query, vouched=vouched, photo=profilepic) groups = Group.search(query) paginator = Paginator(profiles, limit) try: people = paginator.page(page) except PageNotAnInteger: people = paginator.page(1) except EmptyPage: people = paginator.page(paginator.num_pages) if len(profiles) == 1 and not groups: return redirect(reverse('profile', args=[people[0].user.username])) if paginator.count > forms.PAGINATION_LIMIT: show_pagination = True num_pages = len(people.paginator.page_range) d = dict(people=people, form=form, limit=limit, nonvouched_only=nonvouched_only, picture_only=picture_only, show_pagination=show_pagination, num_pages=num_pages, groups=groups, curated_groups=curated_groups) if request.is_ajax(): return render(request, 'search_ajax.html', d) return render(request, 'phonebook/search.html', d)
def searchshoppage(searchterm, shopname=None, minPrice=None, maxPrice=None): form = forms.SearchForm() shopresult = shop.get_shop_results(searchterm, shopname, minPrice, maxPrice) return render_template("index.html", shoplist=shop.shoplist, shopresult=shopresult, searchterm=searchterm, form=form)
def GLOBALS() -> dict: """ Returns all the global variables passed to every template. """ user = cube.load_file("users").get(flask.session.get("account", None), {}) vars = { "vote_active": cube.load_file("vote")["vote_active"], "user": user, "btnform": forms.FlaskForm(), "searchForm": forms.SearchForm(), } return cube.add_dict(GLOBAL, vars)
def index(): form = forms.SearchForm() data = None if form.validate_on_submit(): name_city = form.city.data if name_city is None: data = [] else: data = api.dbpedia.search_theatres(name_city, api.dbpedia.theatres_city, 'en') return render_template('index.html', form=form, data=data)
def index(): form = forms.SearchForm() data = None countries = collections.Counter([]) if form.validate_on_submit(): try: user = vk.users.get(user_ids=[form.vk_id.data], fields='city,universities,sex,bdate') except vk_api.exceptions.ApiError: user = None if user is None: data = [] else: if RU_REGEXP.match(user[0]['first_name']): first_name = transliterate.translit(user[0]['first_name'], reversed=True).replace( "'", '') else: first_name = user[0]['first_name'] birthdate_raw = user[0].get('bdate') birthdate = birthdate_raw.split('.') if birthdate_raw else (0, 0, 0) use_date = birthdate_raw is not None and form.date.data use_age = birthdate_raw is not None and form.age.data if form.api.data == 'wikidata': data = api.wikidata.search_people(first_name, birthdate, form.name.data, use_date, use_age, 'en') elif form.api.data == 'dbpedia': data = api.dbpedia.search_people(first_name, birthdate, form.name.data, use_date, use_age, 'en') else: data = None if data is not None: countries = collections.Counter([ item['country_name']['value'] for item in data if 'country_name' in item ]) else: countries = collections.Counter() return render_template('index.html', form=form, data=data, countries=countries)
def search(request): num_pages = 0 limit = None people = [] show_pagination = False form = forms.SearchForm(request.GET) groups = None curated_groups = None if form.is_valid(): query = form.cleaned_data.get('q', u'') limit = form.cleaned_data['limit'] include_non_vouched = form.cleaned_data['include_non_vouched'] page = request.GET.get('page', 1) curated_groups = Group.get_curated() public = not (request.user.is_authenticated() and request.user.userprofile.is_vouched) profiles = UserProfile.search(query, public=public, include_non_vouched=include_non_vouched) if not public: groups = Group.search(query) paginator = Paginator(profiles, limit) try: people = paginator.page(page) except PageNotAnInteger: people = paginator.page(1) except EmptyPage: people = paginator.page(paginator.num_pages) if profiles.count() == 1 and not groups: return redirect(reverse('profile', args=[people[0].user.username])) if paginator.count > forms.PAGINATION_LIMIT: show_pagination = True num_pages = len(people.paginator.page_range) d = dict(people=people, form=form, limit=limit, show_pagination=show_pagination, num_pages=num_pages, groups=groups, curated_groups=curated_groups) if request.is_ajax(): return render(request, 'search_ajax.html', d) return render(request, 'phonebook/search.html', d)
def search() -> dict: """ Parses the user's search. Can be POST or GET method. """ form = forms.SearchForm() if form.validate_on_submit(): query = form.query.data elif flask.request.args.get("query", None) is not None: query = flask.request.args["query"] else: return {} return { "entries": [(time, NAMES[html], html, preview) for time, html, preview in cube.parse_search(query)] }
def admin(): search_form = forms.SearchForm() admin_form = forms.AdminForm() movement_stream = models.Movement.select().order_by( models.Movement.timestamp.desc()).limit(10) if admin_form.validate_on_submit(): return redirect(url_for('main', crew=admin_form.crew.data)) return render_template('admin.html', admin_form=admin_form, search_form=search_form, movement_stream=movement_stream)
def search(): form = forms.SearchForm() if form.validate_on_submit(): # save form data date = form.date.data origin = form.origin.data destination = form.destination.data redirect(url_for( 'flights', date=date, origin=origin, destination=destination )) return render_template('search.html', form=form)
def add(): """validate add equipment form. renders add equipment page with form.""" form = forms.AddForm() search_form = forms.SearchForm() if form.validate_on_submit(): models.Equipment.add_equipment(unitnumber=form.unitnumber.data, etype=form.type.data, crew=form.crew.data) flash('{} {} added.'.format(form.type.data, form.unitnumber.data)) redirect('home') return render_template('add.html', form=form, user=current_user, search_form=search_form)
def search(): # ajax request handling if g.sijax.is_sijax_request: g.sijax.register_callback('update_notifications', update_notifications) g.sijax.register_callback('set_all_notifications_seen', set_all_notifications_seen) return g.sijax.process_request() # non-ajax handling: # posts = Post.query.search(interrogation).all() form = forms.SearchForm() options = { 'title': 'Search', 'search_form': form, } if form.validate_on_submit(): selection = form.filter.data interrogation = form.interrogation.data if not selection or selection == 'all': options.update({ 'users': User.query.search(interrogation, sort=True)[:5], 'topics': Topic.query.search(interrogation, sort=True)[:5], 'posts': Post.query.search(interrogation, sort=True)[:5], 's_pages': Page.query.search(interrogation, sort=True)[:5], 'proposals': Proposal.query.search(interrogation, sort=True)[:5], 'laws': Law.query.search(interrogation, sort=True)[:5] }) elif selection == 'users': options['users'] = User.query.search(interrogation, sort=True)[:20] elif selection == 'topics': options['topics'] = Topic.query.search(interrogation, sort=True)[:20] elif selection == 'posts': options['posts'] = Post.query.search(interrogation, sort=True)[:20] elif selection == 'pages': options['s_pages'] = Page.query.search(interrogation, sort=True)[:20] elif selection == 'proposals': options['proposals'] = Proposal.query.search(interrogation, sort=True)[:20] elif selection == 'laws': options['laws'] = Law.query.search(interrogation, sort=True)[:20] options.update(base_options()) return render_template("search.html", **options)
def avanzado(): form = forms.SearchForm() data = [] cities = [] if request.method == 'POST': q = form.text.data url = "http://192.168.1.112:5000/brute?query=" + q url = url.replace(" ", "%20") response = urllib.urlopen(url) my_data = json.loads(response.read()) cities = my_data["entities"] data = my_data["results"] return render_template('avanzado.html', form=form, data=data, cities=cities)
def search_view(request): # TODO choose the actual set of possible reviewers possible_reviewers = list(User.objects.all()) possible_authors = list(User.objects.all()) form = forms.SearchForm(request.GET, reviewers=possible_reviewers, authors=possible_authors) if form.is_valid(): results = form.get_results() else: results = [] return render_to_response("search.html", RequestContext(request, { 'form' : form, 'results' : results, 'which_page' : "search" }))
def index(): form = forms.SearchForm() data = [] if request.method == 'POST': q = form.text.data url = "http://192.168.1.112:5000/brute?query=" + q url = url.replace(" ", "%20") response = urllib.urlopen(url) my_data = json.loads(response.read()) data = my_data["results"] # my_data = my_data["results"] # for d in my_data: # print d["similarity"], d["document"]["NOMBRE"] # for value in data: # print value return render_template('index.html', form=form, data=data)
def home(): """ show home page. :return: home page html """ page = request.args.get('page', 1, type=int) prev_search = request.args.get('prev_search', "", type=str) search = forms.SearchForm() if request.method == 'POST': return redirect(url_for('home', page=page, prev_search=search.search_bar.data)) if prev_search: search.search_bar.data = prev_search games = search_games(prev_search, page) else: games = search_games("", page) return render_template("home.html", form=search, games=games)
def my_uploads(): """ page with all of the users uploaded games. :return: uploads page html """ if current_user.is_authenticated: page = request.args.get('page', 1, type=int) prev_search = request.args.get('prev_search', "", type=str) search = forms.SearchForm() if request.method == 'POST': return redirect(url_for('my_uploads', page=page, prev_search=search.search_bar.data)) if prev_search: search.search_bar.data = prev_search games = search_uploaded_games(prev_search, current_user, page) else: games = search_uploaded_games("", current_user, page) return render_template("my_uploads.html", form=search, games=games) return "you must login"
def maintenance(pump=None): """Logs maintenance into database""" maintenance_form = forms.MaintenanceForm() hole_form = forms.HoleForm() search_form = forms.SearchForm() parts_form_vs = forms.PartsFormVS() parts_form_packing = forms.PartsFormPacking() grease_form = forms.GreaseForm() maintenance_stream = models.Maintenance.select().where( models.Maintenance.equipment == pump).order_by( models.Maintenance.timestamp.desc()).limit(10) messages = [] for maint_log in maintenance_stream: message = '{} did {} on {} Hole {} on {} at {}'.format( maint_log.user, maint_log.maintenance_type, maint_log.equipment.unitnumber, maint_log.hole, maint_log.timestamp.strftime('%b %d'), maint_log.timestamp.strftime('%H:%M')) messages.append(message) if grease_form.validate_on_submit(): models.Maintenance.add_maintenance( maintenance_form.maintenance_type.data, hole_form.Hole.data, pump, parts_form_vs.suction_valves.data, parts_form_vs.suction_seats.data, parts_form_vs.discharge_valves.data, parts_form_vs.discharge_seats.data, parts_form_packing.five_packing.data, parts_form_packing.four_point_five_packing.data, grease_form.grease_psi.data, current_user.username) flash('Maintenance logged for {}'.format(pump)) return redirect(url_for('main')) return render_template('maintenance.html', maintenance_form=maintenance_form, hole_form=hole_form, search_form=search_form, parts_form_vs=parts_form_vs, parts_form_packing=parts_form_packing, grease_form=grease_form, pump=pump, maintenance_stream=messages)
def login(): form = forms.LoginForm() search_form = forms.SearchForm() if form.validate_on_submit(): try: user = models.User.get(models.User.username == form.username.data) except models.DoesNotExist: flash('Your username or password does not match', 'error') if check_password_hash(user.password, form.password.data): login_user(user) flash("You've been logged in.", 'success') if current_user.is_admin: return redirect(url_for('admin')) else: return redirect(url_for('main')) else: flash('Your username or password is incorrect', 'error') redirect(url_for('home')) return render_template('login.html', form=form, search_form=search_form)
def form(): form = forms.SearchForm(request.form) links = list() if form.validate_on_submit(): query = form.search.data.split() n_score = dict() start_time = time.time() counter = 0 unique_query = list() #Only get the unique tokens (Note: we still give extra weighting to duplicate words in the scoring during retrieval) for i in query: if i in retriever.stop_words: counter+=1 if counter/len(query) < 0.60: #If stop words comprise less than 60% of the query, ignore them for i in query: if i not in retriever.stop_words and i in pos_dict.keys(): unique_query.append(i) else: unique_query = [i for i in set(query) if i in pos_dict.keys()] if len(unique_query) > 6: #If the query is longer than 6 words, shorten the query new_length = int(len(unique_query)//2) terms = sorted([i for i in unique_query if i in pos_dict.keys()],key = lambda x:tfidf_dict[x][1])[0:new_length] #Get the top-half of the query words else: terms = unique_query doc_vector = dict() for i in terms: doc_len = 0 query_weight = (1+ math.log(query.count(i),10) * (1 + math.log(num_docs/tfidf_dict[i][1]))) t_pos = pos_dict[i] mi.seek(t_pos) #Read the line that contains the token's dictionary t_dict = eval(mi.readline()) #Calculate tf-idf score for each document that has at least 1 word in the query for k,v in t_dict.items(): for doc,freq in v.items(): if doc not in doc_vector.keys(): doc_vector[doc] = 0 term_weight = (1 + math.log(freq,10)) * (1 + math.log(num_docs/tfidf_dict[i][1])) doc_vector[doc]+=(term_weight*query_weight) url_list = sorted([(k,v) for k,v in doc_vector.items()],key = lambda x:x[1],reverse = True)[0:10] #Get top 10 results and sort by score links = [urls_dict[link_num[0]] for link_num in url_list] #Get the url links print("--- %s ms ---" % (time.time()*1000 - start_time*1000)) #Used for timing the program, units are in milliseconds mi.seek(0) #Reset file pointer return render_template('search.html',form = form,links = links) return render_template('search.html',form = form)
def search(): """Action for clicking search button in top right. Looks for crew of a piece of equipment and flashes to page. """ search_form = forms.SearchForm() if current_user.is_admin: response = make_response(redirect(url_for('admin'))) else: response = make_response(redirect(url_for('main'))) if search_form.validate_on_submit(): try: query = models.Equipment.select().where( models.Equipment.unitnumber == search_form.search.data).get() flash('{} is on {} crew'.format(search_form.search.data, query.crew)) except: flash( '{} is not in the system. If this is a mistake please inform admin.' .format(search_form.search.data)) return response else: return response
def search(): geneName = name_load.get_gene_name() form = forms.SearchForm() if form.validate_on_submit(): gene_db_creater() geneDicts = search_region.get_geneDicts(form.GeneName.data) gene_data_creater(geneDicts[0]) db = get_db() cur = db.execute('select * from genedata;') genes = cur.fetchall() geneData = {} for gene in genes: geneData[gene['id']] = json.loads(gene['json']) ids = [gene['id'] for gene in genes] print(ids) return render_template('gene_resource_list.html', ids=ids) return render_template('search.html', form=form, geneName=geneName)
def search_route(): if request.MOBILE: return redirect(url_for("mobile_search_route")) form = forms.SearchForm() if not session["search_query"] or ["search_query"] == "": return render_template("search.html", form=form) if form.validate_on_submit(): session["search_query"] = form.query.data allart = Articles.query.all() artlist = [] for art in allart: # name1 = Users.query.all().name # name = fuzz.token_set_ratio(session["search_query"], name1) title = fuzz.token_set_ratio(session["search_query"], art.title) desc = fuzz.token_set_ratio(session["search_query"], art.desc) print(session["search_query"]) print(title) print(desc) if title >= 70 or desc >= 50: newtext = "" thisart = Articles.query.filter_by(id=art.id).first() text = thisart.content text = text.split(" ") if len(text) >= 30: text = text[:31] newtext = listToString(text) else: newtext = listToString(text) newtext = Markup(newtext).striptags() artlist.append([thisart.img, thisart.title, newtext, thisart.slug]) artlist = artlist[::-1] return render_template("search.html", form=form, artlist=artlist, valabc=session["search_query"])