Example #1
0
def search():
    form = SearchForm()
    if form.validate_on_submit():
        longitude, latitude, city = geosearch.get_geo_loc_twice(form.location.data)
        results = models.get_venues_by_bounding_box(latitude, longitude)
        return render_template('search.html', results=results, form=form)
    return render_template('search.html', form=form, results=None)
Example #2
0
def results():
    form = SearchForm(choice="museum")
    db = Database()
    result = request.args.getlist('res')
    fres = []
    if form.validate_on_submit():
        if (form.choice.data == "museum"):
            result = db.museum_search(form.choice_museum.data,
                                      form.search.data)
        elif (form.choice.data == "artist"):
            result = db.artist_search(form.choice_artist.data,
                                      form.search.data)
        elif (form.choice.data == "artpiece"):
            result = db.artpiece_search(form.choice_artpiece.data,
                                        form.search.data)
        else:
            result = db.user_search(form.choice_user.data, form.search.data)
        for r in result:
            fres.append(r[0])
        return redirect(url_for('results', res=fres))
    return render_template('results.html',
                           title='Results',
                           form=form,
                           user=session.get('username', None),
                           results=result)
Example #3
0
def search():
    try:
        form = SearchForm()
        session = db_session.create_session()
        if form.validate_on_submit():
            if form.search_type.data == '2':
                users = session.query(User).filter(
                    User.login.like(f'%{form.text.data}%')
                ).all()

            elif form.search_type.data == '1':
                users = session.query(User).filter(
                    User.id == int(form.text.data)
                ).all()

            else:
                users = session.query(User).all()
            return render_template(
                'search_page.html',
                form=form,
                search_results=users
            )

        return render_template('search_page.html', form=form)
    except Exception:
        return redirect('/search')
Example #4
0
def search():
    form = SearchForm()
    if form.validate_on_submit():
    	return redirect(url_for('search_results', query = form.search.data))	
    return render_template('searchform.html', 
        title = 'Search',
        form = form)
Example #5
0
def hello_world():
    form = SearchForm()
    if form.validate_on_submit():
        print(list(filter(lambda x: x is not None, [x if form.productName.data.lower() in x.name.lower() else None for x in list(Product.query.all())])))
        return render_template("searchResults.html", len=len, prods=list(filter(lambda x: x is not None, [x if form.productName.data.lower() in x.name.lower() else None for x in list(Product.query.all())])), Seller=Seller)
    else:
        return render_template("index.html", form=form)
Example #6
0
def index():
    # logic for the edit my profile page
    # pull text from input fields and rewrite JSON entry in the DB associated with that profile
    form = SearchForm()
    if form.validate_on_submit():
	# creating dictionary to store text from input text fields
        s = {}
	for i in ['Profname','about','age','email','phone','loc','empid','school','gradYear','involv', 'picture', 'groupd']:
	    if request.form[i] != "":
		s[i] = request.form[i]
	    else:
		s[i] = ''
	s['inter'] = {}
	s['username'] = current_user.username
	for i in ['exploring', 'nightlife', 'outdoors', 'sports', 'videogames']:
	    if i in request.form.getlist('interests'):
		s['inter'][i] = 1
	    else:	
		s['inter'][i] = 0
	#converting dictionary to JSON
	json_string = json.dumps(s)
	#checking if a profile with the username already exists in the db
	result = db_connection.execute("""SELECT p.comment_id, p.doc FROM user_profile p WHERE p.doc.username = :x""", x=current_user.username).fetchone()[0] 
	if result:
	    this_profile = UserProfile.get(result)
	    this_profile.doc = json_string
	    db.session.commit()
	else:
	    db.session.add(UserProfile(json_string))
	    db.session.commit()
	return redirect(url_for('viewprof', username = current_user.username))
    return render_template('index.html', form=form)
Example #7
0
def search():
    form = SearchForm()
    if form.validate_on_submit():
        results = wiki.search(form.term.data, form.ignore_case.data)
        return render_template('search.html', form=form,
                               results=results, search=form.term.data)
    return render_template('search.html', form=form, search=None)
Example #8
0
def search():
    form = SearchForm()
    if form.validate_on_submit():
        q = form.str.data
        print(q)
        q = spell_correct(q)
        body = {
            "_source": "title",
            "query": {
                "match": {
                    "storyline": {
                        "query": q
                    }
                }
            }
        }
        if q is not None:
            results = es.search(index='movies', doc_type='_doc', body=body)
            print(results)
            if len(results['hits']['hits']) == 0:
                return render_template('home.html',
                                       results=[],
                                       show='No movie:(')
            else:
                return render_template('home.html', results=results, show='')

    return render_template('search.html', form=form)
Example #9
0
def search():
    """Display search options"""

    # if "username" not in session:
    #     flash("You must be logged in or registered")
    #     return redirect("/")

    # create form
    form = SearchForm()

    # # check if valid  submitted, this check false if GET
    if form.validate_on_submit():

        # get form values
        pet_type = form.pettype.data
        gender = form.gender.data
        distance = form.distance.data
        location = form.location.data
        # params for api call
        params = (
            ("type", pet_type),
            ("gender", gender),
            ("distance", distance),
            ("location", location),
            ("limit", "36"),
        )
        # petfinder api search request
        url = "https://api.petfinder.com/v2/animals"
        resp = get_API_response(url, params)
        for pet in resp["animals"]:
            pet = fix_web_desc(pet)

        return render_template("displaypets.html", resp=resp)
    response = get_random_pet()
    return render_template("search.html", response=response, form=form)
Example #10
0
def search(query=None):
    form = SearchForm()
    results_bugs, results_fish = {}, {}
    num_results, num_results_bugs, num_results_fish = 0, 0, 0

    if form.validate_on_submit():
        query = form.query.data
        db = DB()
        results_fish = db.findAll(
            'fish', lambda item: query.lower() in item[0].lower())
        results_bugs = db.findAll(
            'bugs', lambda item: query.lower() in item[0].lower())
        num_results_bugs = len(results_bugs)
        num_results_fish = len(results_fish)
        num_results = num_results_bugs + num_results_fish

        print('form valid... redirect to', url_for('search', query=query))
        """This doesn't work. Why?! expect /search/foo actual /search/?query=foo
        return redirect(url_for('search', query=query))"""
        # return redirect('/search/' + query)
    return render_template('search.html',
                           query=query,
                           fish=results_fish,
                           bugs=results_bugs,
                           num_results=num_results,
                           num_results_bugs=num_results_bugs,
                           num_results_fish=num_results_fish)
Example #11
0
def searchSeries():
    form = SearchForm()

    #Redirect to the same page after recieving request
    if form.validate_on_submit() and request.method == 'POST':
        #print request.method

        flash('Series requested is : ' + form.seriesName.data)

        message = form.seriesName.data
        message = helperFunctions.processSeriesString(message)

        message[1] = message[1] + ".json"

        showExists = os.path.isfile(os.getcwd() + "/app/static/" + message[1])

        #if show file exists, then use that file otherwise use scrapy to generate the json and then use that
        if showExists:
            return render_template("generateChart.html", showName=message[1])
        else:
            subprocess.check_call([
                'scrapy', 'crawl', 'imdb', '-a',
                'category=%s' % (message[0]), '-o',
                './app/static/%s' % (message[1]), '-t', 'json'
            ])
            return render_template("generateChart.html", showName=message[1])

    return render_template('inputs.html', title='Do Your Searches', form=form)
Example #12
0
 def search():
     form = SearchForm()
     if form.validate_on_submit():
         HKID = re.search("(^[A-Z])(\d{7})", form.search_form.data.strip().upper())
         mobile = re.search("(\d{8})", form.search_form.data.strip())
         name = re.search("(\w.+\s).+", form.search_form.data.strip().upper())
         if HKID is not None:
             if len(list(patients.find({'HKID': HKID.string}))) > 0:
                 results = patients.find({'HKID': HKID.string})
                 return render_template('searchmini.html', results=results, form=form)
             else:
                 pnot_found()
         elif mobile is not None:
             if len(list(patients.find({'mobile': mobile.string}))) > 0:
                 results = patients.find({'mobile': mobile.string})
                 return render_template('searchmini.html', results=results, form=form)
             else:
                 pnot_found()
         elif name is not None:
             if len(list(patients.find({'name': name.string}))) > 0:
                 results = patients.find({'name': name.string})
                 return render_template('searchmini.html', results=results, form=form)
             else:
                 pnot_found()
         else:
             pnot_found()
     return render_template('searchform.html', form=form)
def search():
    if app.config['TESTING'] != True:
        if ('credentials' not in flask.session):
            return flask.redirect(flask.url_for('oauth2callback'))
        credentials = client.OAuth2Credentials.from_json(
            flask.session['credentials'])
        if credentials.access_token_expired:
            return flask.redirect(flask.url_for('oauth2callback'))
    form = SearchForm()
    if form.validate_on_submit():
        email = form.data['finddelegate']
        if not re.match(r"^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]*$",
                        email):
            newform = SearchForm()
            searchform = SearchForm()
            return render_template('index.html',
                                   form=newform,
                                   searchform=searchform,
                                   error='Not a valid email address!')
        else:
            a = email.split('@')
            url = 'delegate/' + a[1] + '/' + a[0]
            return flask.redirect(
                flask.url_for('getdelegate', username=a[0], domain=a[1]))
    else:
        return render_template('index.html',
                               form=form,
                               searchform=form,
                               error='Is the field empty?')
Example #14
0
def index():
    form = SearchForm()
    if form.validate_on_submit():
        search_word = form.searchword.data
        books_to_search = find_books(search_word)

        # handling of no search results
        if not books_to_search:
            return render_template('sort_by_sentiment_app.html',
                                   no_results="no results",
                                   form=form)

        # handling of one match
        if len(books_to_search) == 1:
            books = find_similar(x, int(books_to_search[0][0]), 100)
            return render_template('sort_by_sentiment_app.html',
                                   books=books,
                                   form=form)
        # handling of multiple results
        else:
            return render_template('sort_by_sentiment_app.html',
                                   book_list=books_to_search,
                                   form=form)

    # handling the case of multiple results and selectin from the listing what to search
    if request.method == 'POST':
        if request.form.get('Search') == 'Search similar':
            book_index = request.form.get('index')
            books = find_similar(x, int(book_index), 100)
            return render_template('sort_by_sentiment_app.html',
                                   books=books,
                                   form=form)

    return render_template('sort_by_sentiment_app.html', form=form)
Example #15
0
def home():
    form = SearchForm()
    if form.validate_on_submit():
        return redirect(url_for('results',
                                postcode=form.postcode.data))
    return render_template('pages/home.html',
                           form=form)
def index():
    idform = GetIdForm(prefix="get")
    if idform.validate_on_submit():
        return redirect(
            url_for('component_page',
                    identifier=url_quote(idform.identifier.data, safe='')))

    sform = SearchForm(prefix="search")
    if sform.validate_on_submit():
        return redirect(
            url_for('component_search',
                    search_str=url_quote(sform.text.data, safe='')))

    itemform = SearchItemsForm(prefix="search-item")
    if itemform.validate_on_submit():
        return redirect(
            url_for('find_feature',
                    kind=itemform.kind.data,
                    value=url_quote(itemform.text.data, safe='')))

    return render_template('index.html',
                           title='Home',
                           idform=idform,
                           sform=sform,
                           itemform=itemform)
Example #17
0
def search():
    form = SearchForm()
    if form.validate_on_submit():
        location = request.form.get('location')
        term = request.form.get('search')
        return redirect('/results/{}/{}'.format(location, term))
    return render_template('search.html', form=form)
def search():
    searchForm = SearchForm(request.form)

    if request.method == 'POST':
        searchForm = SearchForm(request.form)
        searchedby = searchForm.search.data

        if searchForm.validate() == False:
            flash("Empty search.", 'warning')
            userNote = Note.objects.search_text(
                searchForm.search.data).as_pymongo()

        if searchForm.validate_on_submit():
            #noteResult = Note.objects.search_text(content=SearchForm.search.data).first()
            try:
                userNote = Note.objects.search_text(
                    searchForm.search.data).as_pymongo()
            except OperationFailure:
                flash("sometihng went wrong", "danger")
                render_template("search.html",
                                title=searchedby,
                                delete_quote=deleteQuoteForm(request.form),
                                search_form=searchForm,
                                result=userNote)
            #document = notes.objects(content=searchForm.search.data).first()
            #print userNote

    return render_template("search.html",
                           title=searchedby,
                           search_form=searchForm,
                           delete_quote=deleteQuoteForm(request.form),
                           result=userNote)
Example #19
0
def search():
    form = LoginForm()
    form_s = SearchForm()
    if form_s.validate_on_submit():
        q = form_s.search.data
        books = Book.query.all()
        authors = Author.query.all()
        result = []
        for book in books:
            if q in book.title:
                if not book in result:
                    result.append(book)
        for author in authors:
            if q in author.name:
                for b in author.books:
                    if not b in result:
                        result.append(b)
        return render_template(
            'index.html',
            books=result,
            form=form,
            user=current_user,
            is_authenticated=current_user.is_authenticated(),
            form_s=form_s,
        )

    return redirect(url_for('index'))
Example #20
0
def search():
    """ Search form """
    search = SearchForm()
    if search.validate_on_submit():
        return redirect(url_for('.search_results', query=search.search.data))
    else:
        return redirect(request.referrer)
Example #21
0
def search():
    form = SearchForm()
    if form.validate_on_submit():
        object = form.search.data
        session['searchterm'] = object
        return redirect(url_for('match'))
    return render_template('search.html', title='Search', form=form)
Example #22
0
def main(key_id=0, act=""):
    user_obj = User()
    tran_obj = Transaction()
    key_obj = Key()
    search_form = SearchForm()
    keys = user_obj.list_all_key(current_user.role, current_user.company_id)
    if request.method == "POST":
        if act == "take":
            selected_key = key_obj.query.get(key_id)
            selected_key.available = False
            db.session.add(selected_key)
            new_transaction = Transaction(user=current_user, key_id=key_id, time_stamp=datetime.datetime.now() + timedelta(hours=3))
            db.session.add(new_transaction)
            db.session.commit()
            flash("Key Taken")
            return redirect(url_for('main'))
        elif act == "release":
            selected_key = key_obj.query.get(key_id)
            selected_key.available = True
            db.session.add(selected_key)
            db.session.commit()
            flash("Key Release")
            return redirect(url_for('main'))
    if search_form.validate_on_submit():
        print search_form.key_input.data
        string_input = search_form.key_input.data
        if string_input == "":
            flash("Please enter something for searching")
            return redirect(url_for("main"))
        else:
            return redirect(url_for('search', input=string_input))
    elif request.method == "GET":
        return render_template("main.html", keys=keys, search_form=search_form)
Example #23
0
def search():
    form = SearchForm(csrf_enabled=False)
    if form.validate_on_submit():
        date_from = request.form.get("date_from")
        date_to = request.form.get("date_to")
        source = request.form.get("source")
        destination = request.form.get("destination")
        count = int(request.form.get("count"))

        conns = []
        d_from = parse(date_from)
        d_to = parse(date_to)
        delta = d_to - d_from
        for i in range(delta.days + 1):
            new_conns = connections.find_connections(
                source,
                destination,
                departure_date=(d_from +
                                timedelta(days=i)).strftime("%Y-%m-%d"),
            )
            conns += new_conns

        return render_template(
            "search_results.html",
            journeys=conns,
            form=form,
            source=source,
            destination=destination,
            count=count,
            date_from=date_from,
            date_to=date_to,
        )

    return render_template("search_vue.html", form=form)
Example #24
0
def raw_email(stype,docnumber):
	#Get the raw email from the database
	db_name = '01_database/hrc.sqlite'
	db = sqlite3.connect(db_name)
	cursor = db.cursor()

	#search = docnumber
	sql_cmd = 'SELECT RawText FROM emails\
		   WHERE DocNumber IS ?'
	cursor.execute(sql_cmd, (docnumber,))
	tmp = cursor.fetchone()
	raw_email = tmp[0]
	#Remove special characters and split into lines:
	evec = raw_email.split('\n')
	for line in evec:
		line.strip()
	#Take care of search form
	form = SearchForm()
	if form.validate_on_submit():# and request.method == 'POST':
		flash('Searching Hillary\'s emails for "%s"' % 
              	(form.search.data ))
		#stype as placeholder in case we want to add different seach schemes
		#'bs' = body/subject
		#'ps' = people search 
		#'es' = email search (to/from address)
        	return redirect(url_for('.search', stype = stype, search = form.search.data))

	return render_template('raw_email.html',
				raw_email = evec,
				docnumber = docnumber,
				form = form)
Example #25
0
def index():
    form = SearchForm()
    g.search_form = SearchForm()
    if form.validate_on_submit():
        ...
        return redirect('/result')
    return render_template('index_1.html', title='Home')
Example #26
0
def maker():
    pages = db.session.query(Data.ManufacturerSI, Data.Maker).distinct()
    form = SearchForm()
    if form.validate_on_submit():
        query = form.query.data.strip()
        list = [(DATA.rex_select_row(i[0], query), i[1], DATA.get_count(i[1]))
                for i in pages if query in i[0] or query.title() in i[0]]
        if list:
            flash("Результат поиска по запросу")
        else:
            flash("По вашему запросу ни чего не найденно!")
        return render_template('search/maker.html',
                               form=form,
                               list=list,
                               pages=None,
                               page_name='Фирмы изготовители СИ',
                               query=form.query.data)
    else:
        page = request.args.get('page', 1, type=int)
        list_pages = pages.paginate(page=page, per_page=30)
        list = [(i[0], i[1], DATA.get_count(i[1])) for i in list_pages.items]
        return render_template('search/maker.html',
                               form=form,
                               list=list,
                               pages=list_pages,
                               page_name='Фирмы изготовители СИ')
def search():
    form = SearchForm()
    result = None
    if form.validate_on_submit():
        #curs = db.connection.cursor()
        #notice = request.form.get('s')
        skills = request.form.get('e')
        jobId=request.form.get('jobid')
        rounds=request.form.get('rounds')
        stages=request.form.get('stages')
        if(skills!=None and jobId=="NULL" and stages=="NULL" and rounds=="NULL"):
            result=db.execute(f"SELECT c.id,c.name,c.email,c.phno,s.r1,s.r2,s.r3,s.r4,s.hr,s.os,s.joined FROM candid as c RIGHT JOIN candidStat as s ON c.id=s.id WHERE c.skills like :skills;",{"skills":'%'+skills+'%'})
            details=result.fetchall()
            return render_template('dashboard.html',details=details)
        elif(skills!=None and jobId=="NULL" and stages!="NULL" and rounds!="NULL"):
            result=db.execute(f"SELECT c.id,c.name,c.email,c.phno,s.r1,s.r2,s.r3,s.r4,s.hr,s.os,s.joined FROM candid as c RIGHT JOIN candidStat as s ON c.id=s.id WHERE c.skills like :skills AND s.{rounds}=:stages;",{"skills":'%'+skills+'%',"stages":stages})
            details=result.fetchall()
            return render_template('dashboard.html',details=details)
        elif(skills!=None and jobId!="NULL" and stages=="NULL" and rounds=="NULL"):
            result=db.execute(f"SELECT c.id,c.name,c.email,c.phno,s.r1,s.r2,s.r3,s.r4,s.hr,s.os,s.joined FROM candid as c RIGHT JOIN candidStat as s ON c.id=s.id WHERE c.skills like :skills AND c.jobId={jobId};",{"skills":'%'+skills+'%'})
            details=result.fetchall()
            return render_template('dashboard.html',details=details)
        elif(skills!=None and jobId!="NULL" and stages!="NULL" and rounds!="NULL"):
            result=db.execute(f"SELECT c.id,c.name,c.email,c.phno,s.r1,s.r2,s.r3,s.r4,s.hr,s.os,s.joined FROM candid as c RIGHT JOIN candidStat as s ON c.id=s.id WHERE c.skills like :skills AND s.{rounds}=:stages AND c.jobId={jobId};",{"skills":'%'+skills+'%',"stages":stages})
            details=result.fetchall()
            return render_template('dashboard.html',details=details)
        elif(skills==None and jobId!="NULL" and stages=="NULL" and rounds=="NULL"):
            result=db.execute(f"SELECT c.id,c.name,c.email,c.phno,s.r1,s.r2,s.r3,s.r4,s.hr,s.os,s.joined FROM candid as c RIGHT JOIN candidStat as s ON c.id=s.id WHERE c.jobId={jobId};")
            details=result.fetchall()
            return render_template('dashboard.html',details=details)
        elif(skills==None and jobId!="NULL" and stages!="NULL" and rounds!="NULL"):
            result=db.execute(f"SELECT c.id,c.name,c.email,c.phno,s.r1,s.r2,s.r3,s.r4,s.hr,s.os,s.joined FROM candid as c RIGHT JOIN candidStat as s ON c.id=s.id WHERE s.{rounds}=:stages AND c.jobId={jobId};",{"stages":stages})
            details=result.fetchall()
            return render_template('dashboard.html',details=details)
    return render_template('searchBar.html', form=form, result=result)
Example #28
0
File: iot.py Project: rlunding/iot
def search():
    """Search

    Search for the successor node responsible for a given key.

    :param key: the key of the node which should be found.
    :returns: html page with node information, possible also with errors if the input is invalid.
    """
    search_form = SearchForm()
    if search_form.validate_on_submit():
        result_node, msg, count = node.find_successor(
            int(request.form.get('key')), node.key)
        if result_node is not None:
            output = "{0}:{1}, key={2}, msg={3}, hop count = {4}".format(
                result_node.ip, result_node.port, result_node.key, msg, count)
        else:
            output = msg
        flash(output, 'success')
        return redirect(url_for('home'))
    join_form = JoinForm()
    add_form = AddForm()
    return render_template('home.html',
                           node=node,
                           join_form=join_form,
                           add_form=add_form,
                           search_form=search_form)
Example #29
0
def manageProfile():
    form = bankProfileForm()
    search_form = SearchForm()
    username = session.get('username')
    if session.get('username') == None:
        return redirect(url_for('home'))


    if form.profile_submit.data and form.validate_on_submit():
        cursor.execute("SELECT * FROM AMLOfficer WHERE email = '" + form.email.data + "'")
        data2 = cursor.fetchone()
        if not (data2 is None):
            flash('This Email is already exists please try another email', 'danger')
            return render_template('ManageProfile.html', form=form , form2 = search_form )
        else:
            cur, db , engine = connection2()
            cur.execute("UPDATE SMI_DB.AMLOfficer SET fullname = '" + form.fullName.data + "' , email = '" + form.email.data + "' , password = '******' WHERE userName = '******'" )
            db.commit()

    # bring info from database
    cur1, db1, engine1 = connection2()
    cur1.execute("SELECT * FROM SMI_DB.AMLOfficer WHERE userName = '******'")
    data = cur1.fetchall()


    for each in data:
        form.fullName.data = each[2]
        form.email.data = each[1]


    if search_form.search_submit.data and search_form.validate_on_submit():
        return redirect((url_for('searchResult', id= search_form.search.data , form2 = search_form )))

    return render_template("ManageProfile.html", form=form , form2 = search_form )
Example #30
0
def search():
    form1 = SearchForm()
    m = []
    entries = {}
    message = None
    if form1.validate_on_submit():
    	keywords = form1.query.data
    	  #parse the HTTP response
        m = searchWord(keywords)

    elif request.form.get("like") != None:
        smallURL = request.form.get("small")
        bigURL = request.form.get("big")
        message = LikeImage(smallURL, bigURL)
        return message

    elif request.form.get("review") != None:
        entries = reviewLiked()
        
    elif request.form.get("dislike") != None:
        smallURL = request.form.get("small")
        bigURL = request.form.get("big")
        dislikeImage(smallURL, bigURL)
        entries = reviewLiked()
    return render_template('search.html',
        title = 'Flickr Search',
        form1 = form1,
        liked = entries,
        imgs = m,
        message = message)
Example #31
0
def show_areas():
    '''Route to show a user's areas '''
    if not g.user:
        return redirect("/")

    user_areas = Area.query.filter(UserAreas.user_id == g.user.id).all()
    user = User.query.get_or_404(g.user.id)
    form = SearchForm()
    user_cities = [area.serialize() for area in user_areas]

    if form.validate_on_submit():
        city = form.city.data
        state = form.state.data
        formatted_city = city.title()

        for area in user_cities:
            if area['city'] == formatted_city and area['state'] == state:
                area_id = area['id']
                flash('You already added this area!', 'success')
                return redirect(f'/discover/restaurants/{area_id}')

        area = Area(city=formatted_city, state=state)
        g.user.areas.append(area)
        db.session.commit()
        return redirect(f'/discover/restaurants/{area.id}')
    return render_template('/areas/areas.html', form=form)
Example #32
0
def book(book_id):
    form = SearchForm()
    book = Book.query.filter_by(id = book_id).first()
    pics = Picture.query.filter_by(book_id = book_id).order_by(Picture.order)
    if book == None:
        flash('Book not found')
        return redirect(url_for('index'))

    if form.validate_on_submit():
        api = InstagramAPI(client_id=app.config['INSTAGRAM_ID'], client_secret = app.config['INSTAGRAM_SECRET'])
        # if max_tag_id > 0:
        #     if request.args['query']:
        #         tag_name = request.args['query']
        #     tag_media, next = api.tag_recent_media(count = 20, max_id = max_tag_id, tag_name = request.args['query'])
        # else:
        tag_media, next = api.tag_recent_media(count = 20, tag_name = form.query.data)
        instagram_results = []
        for media in tag_media:
            instagram_results.append(media.images['thumbnail'].url)
        try:
            max_tag_id = next.split('&')[2].split('max_tag_id=')[1]
        except: 
            max_tag_id = None
        return render_template('book.html',
            query = form.query.data,
            instagram_results = tag_media,
            pics = pics,
            form = form,
            next = max_tag_id,
            book = book)

    return render_template('book.html',
        book = book,
        pics = pics,
        form = form)
Example #33
0
def search():
    form = SearchForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is not None:
            return redirect(url_for('add', username=user.username))
        flash('The user does not exist!')
    return render_template('search.html', form=form)
Example #34
0
def search_user():
    global user_details
    form = SearchForm()
    if form.validate_on_submit():
        query = form.username.data
        return redirect(url_for('search_results', query=query))
    
    return render_template('search_user.html', title='Search User', form=form, user_details=user_details)
Example #35
0
def search():
    form = SearchForm(csrf_enabled=False)
    if form.validate_on_submit():
        journeys = scraper.get_parsed_journeys(
            form.source.data, form.destination.data, form.date.data)
        template = render_template('search.html', journeys=journeys, form=form)
        return make_response(template)
    return render_template('search.html', form=form)
Example #36
0
def search():
    form = SearchForm()
    if request.method == 'POST' and form.validate_on_submit():
        # call helper function to check if the user put ISBN into search
        user_provides_isbn = is_isbn_code(form.search.data)

        if user_provides_isbn:
            return redirect(url_for('book', book_isbn=user_provides_isbn))

        # search for authors, and books
        else:
            s_q_authors = db.execute(
                'SELECT *, '
                'public.author_gr_map.author_id_gr, '
                'public.author_gr_map.author_ph_gr '
                'FROM public.author '
                'LEFT JOIN public.author_gr_map '
                'ON public.author.id = public.author_gr_map.author_id '
                'WHERE LOWER(name) LIKE LOWER(:search_like) ',
                {'search_like': '%'+form.search.data+'%'}
            ).fetchall()

            s_q_books = db.execute(
                'SELECT public.book.*, '
                'array_agg(public.author.name) '
                'FROM public.book '
                'JOIN public.book_author '
                'ON public.book.id = public.book_author.book_id '
                'JOIN public.author '
                'ON public.book_author.author_id = public.author.id '
                'WHERE isbn LIKE :search_like '
                'OR to_tsvector(title) @@ to_tsquery(:search) '
                'GROUP BY public.book.id',
                {'search': form.search.data.strip().replace(' ', ' & '),
                 'search_like': '%'+form.search.data+'%'}
            ).fetchall()

            results = (s_q_books, s_q_authors)
            return render_template('search.html', form=form, results=results)

    if not form.validate_on_submit():
        for field in form.errors:
            for err in form.errors[field]:
                flash(f'{field}: {err}', 'alert')

    return render_template('search.html', form=form, results=None)
Example #37
0
def searchdoctor(pid):
    form=SearchForm()
    doctor=None
    i=-1
    if form.validate_on_submit():
          doctor = DoctorDetails.query.filter_by(city=(form.city.data).upper()).all()
          i=len(doctor) 
    return render_template('searchdoctor.html',doctor=doctor,form=form,pid=pid,i=i)
Example #38
0
def social():
    friends = dq.find(User, ['nickname'], [g.user.nickname]).first().valid_friends()
    form = SearchForm(request.form)
    if form.validate_on_submit():
        nickname = form.search.data
        results = dq.find(User, ['nickname'], [nickname])
        count=results.count()
        return render_template('social.html', friends=friends, form=form, results=results, results_count=count)
    return render_template('social.html', friends=friends, form=form, results=None, results_count=-1)
Example #39
0
File: views.py Project: adlnet/xci
def compsearch():
    comps = []
    if request.method == 'GET':
        return render_template('compsearch.html', comps=comps, search_form=SearchForm())
    else:
        sf = SearchForm(request.form)
        if sf.validate_on_submit():
            key = sf.search.data
            comps = models.searchComps(key)
        return render_template('compsearch.html', comps=comps, search_form=sf)        
Example #40
0
def search():
    form = SearchForm()
    if form.validate_on_submit():
        # input some search here
        search_string = form.search.data
        flash(search_string)
        app.logger.info(form.search.data)
        return redirect(url_for('search_result', query=search_string))
        # redirect(url_for('search'))
    return render_template('search.html', form=form)
Example #41
0
def search_books():
    form = SearchForm()
    results = None
    if request.method == 'POST' and form.validate_on_submit():
        book = request.form['book']
        author = request.form['author']
        results = Book.get_byTitleAuthor(book, author, g.dbs)

        # flash('book: %s author: %s' % (books, author))
    return render_template('search_books.html', form=form, results=results)
Example #42
0
def index():
    form = SearchForm()
    cordinates = None
    if form.validate_on_submit():
        query = form.query.data
        cordinates = decode_address_to_coordinates(query)
        zone_id = find_in_zone(cordinates['lat'], cordinates['lng'])
        zone_info = ZoneAssignment.query.filter_by(zone_id=zone_id).all()
        return render_template('index.html', form=form, zone_info=zone_info, cordinates=cordinates)

    return render_template('index.html', form=form)
Example #43
0
def search_results(query):
    form = SearchForm(request.form)
    if request.method == 'POST' and form.validate_on_submit():
        return redirect(url_for('search_results', query = form.search.data))
    results = Locator.query.whoosh_search(query).\
                            filter_by(email=current_user.email)
    for r in results.order_by(desc(Locator.id)):
        print r.id, r.date
    return render_template('urls.jade', form=form,
                                        urls=results,
                                        groupnames=get_groupnames())
Example #44
0
    def post(self):
        form = SearchForm()
        if form.validate_on_submit():
            search_by, search_text = form.search_by.data, form.search_text.data
            search_pattern = "%{0}%".format(search_text)
            if search_by == 'name':
                books = Book.query.filter(Book.title.like(search_pattern)).all()
            else:
                books = Book.query.join(Author.books).filter(Author.name.like(search_pattern)).all()
            return jsonify(result=[book.as_dict() for book in books])

        return render_template('index.html', form=form)
Example #45
0
def main():
    if current_user.is_authenticated:
        if session['url']:
            save_url(session['url'], session['groupname'])
        form = SearchForm(request.form)
        if request.method == 'POST' and form.validate_on_submit():
            return redirect(url_for('search_results',
                                    query = form.search.data))
        return render_template('urls.jade', form=form,
                                            urls=get_urls(),
                                            groupnames=get_groupnames())
    return render_template('home.jade')
Example #46
0
def search(term=""):
    searchform = SearchForm(prefix='search')

    posts = []

    if (request.method == 'GET' and term != "") or (request.method == 'POST' and searchform.validate_on_submit()):
        if request.method == 'POST':
            term = searchform.term.data

        term = '%' + term + '%'
        posts = Post.query.filter(and_(Post.draft == False, or_(Post.title.like(term), Post.text.like(term)))).order_by(db.desc(Post.timestamp))

    return render_custom_template('search.html', searchform=searchform, posts=posts)
Example #47
0
def hello(stype):
	form = SearchForm()
#	print "past form"
	#return "heyo"
	if form.validate_on_submit():
		flash('Searching Hillary\'s emails for "%s"' % 
              	(form.search.data ))
		#stype as placeholder in case we want to add different seach schemes
		#'bs' = body/subject
		#'ps' = people search 
		#'es' = email search (to/from address)
        	return redirect(url_for('.search',stype = stype, search = form.search.data))
	#form = 'skdfjl'
	return render_template('index.html', stype = stype, form = form, search_types = app.config['SEARCH_TYPES'])
Example #48
0
def home():
    form = SearchForm()
    db = get_db()
    cur = db.cursor()

    # validate_on_submit = true if post + validation
    if form.validate_on_submit():
        search = request.form['search']

        # Validate input syntax
        if not ':' in search:
            flash('Syntax error: Search format is field:pattern')
            return render_template('index.html', form=form)

        # Unpack input + validate pattern
        column_name, search_term = search.lower().split(':', 2)
        if not search_term:
            flash('No pattern entered')
            return render_template('index.html', form=form)

        # Find the correct select query
        if column_name:
            if column_name == 'ip':
                cur.execute('SELECT * FROM suspect_ips WHERE ip LIKE ? ORDER BY Date DESC ', ('%'+search_term+'%',))
            elif column_name == 'hostname':
                cur.execute('SELECT * FROM suspect_ips WHERE hostname LIKE ? ORDER BY Date DESC', ('%'+search_term+'%',))
            elif column_name == 'latitude':
                cur.execute('SELECT * FROM suspect_ips WHERE latitude LIKE ? ORDER BY Date DESC', ('%'+search_term+'%',))
            elif column_name == 'longitude':
                cur.execute('SELECT * FROM suspect_ips WHERE longitude LIKE ? ORDER BY Date DESC', ('%'+search_term+'%',))
            elif column_name == 'country':
                cur.execute('SELECT * FROM suspect_ips WHERE country LIKE ? ORDER BY Date DESC', ('%'+search_term+'%',))
            elif column_name == 'date':
                cur.execute('SELECT * FROM suspect_ips WHERE date LIKE ? ORDER BY Date DESC', ('%'+search_term+'%',))
        else:
            flash('Field %s not found' % column_name)
            return render_template('index.html', form=form)

        entries = cur.fetchall()
        if len(entries) == 0:
            flash('No records found matching %s' % search_term)
            return render_template('index.html', form=form)
        else:
            total = len(entries)
            return render_template('index.html', entries=entries, form=form, total=total)
    else:
        cur.execute('SELECT * FROM suspect_ips ORDER BY Date DESC')
        entries = cur.fetchall()
        return render_template('index.html', entries=entries[0:2500], form=form)
Example #49
0
def search(stype, search):
	body_rows = search_bs(search)	
	form = SearchForm()
#	print "past form"
	#return "heyo"
	if form.validate_on_submit():# and request.method == 'POST':
		flash('Searching Hillary\'s emails for "%s"' % 
              	(form.search.data ))
		#stype as placeholder in case we want to add different seach schemes
		#'bs' = body/subject
		#'ps' = people search 
		#'es' = email search (to/from address)
        	return redirect(url_for('.search', stype = stype, search = form.search.data))
	
	return render_template('search.html', results = body_rows, stype = stype, form = form)
Example #50
0
def search_results(query, index=1):
    user = g.user
    form = LoginForm()
    form_busca = SearchForm()
    result_doacao = Doacao.query.filter(Doacao.tags.like('%' + query + '%')).paginate(index, POST_PER_PAGE, False)
    result_ong = Ong.query.filter(Ong.nome.like('%' + query + '%'))
    if form_busca.validate_on_submit():
        return redirect(url_for('search_results', query=form_busca.search.data))
    return render_template('search.html',
                           query=query,
                           result_doacao=result_doacao,
                           result_ong=result_ong,
                           form_busca=form_busca,
                           form=form,
                           user=user)
Example #51
0
def show_stocks(searchterm = '', page = None):
	search = SearchForm()
	db = Db()
	SQL = "SELECT ticker, company_name FROM stocks WHERE ticker LIKE %s OR company_name LIKE %s ORDER BY ticker;"
	data =  ('%', '%')	
	if search.validate_on_submit():
		search_data = search.search.data
		data = (search_data + '%', search_data + '%')
		db.execute(SQL, data)
		entries = [dict(ticker = row[0], company = row[1]) for row in db.fetchall()]
		return render_template('index.html', search = SearchForm(),  entries = entries)

	else:
		db.execute(SQL, data)
		entries = [dict(ticker = row[0], company = row[1]) for row in db.fetchall()]
		return render_template('index.html',search = search, entries=entries)
Example #52
0
def search(query=None):
    form = SearchForm()
    if form.validate_on_submit():
        query = form.search.data
        results = []
        if form.by_title.data:
            results += Book.query.filter(Book.name.like('%' + query + '%')).all()
        if form.by_author.data:
            from models import authors
            results += Book.query.join(authors).join(Author).filter(
                Author.name.like('%' + query + '%')).all()
        results = set(results)
        num = len(results)
        return render_template('search.html', query=query, form=form,
                                results=results, num=num)
    return render_template('search.html', form=form, query=query)
Example #53
0
def search():
    if "s" not in session:
        return redirect(url_for("login"))
    form = SearchForm()
    if form.validate_on_submit():
        session["bookname_r"] = form.bookname_s.data
        session["author_r"] = form.author_s.data
        if session.get("bookname_r") or session.get("author_r"):
            return redirect(url_for("result"))
        else:
            flash(u"请输入书名或作者名")
    form.bookname_s.data = ""
    form.author_s.data = ""
    return render_template(
        "search.html", form=form, bookname_s=session.get("bookname_r"), author_s=session.get("author_r")
    )
Example #54
0
def index():
	"""index/search page, will get data from the templates then pass it to 
	bestroute to validate if the searched data is registered in the database 
	return errors if textfields are not supplied care of the form object"""
	form = SearchForm()

	if 'username' in session:
		username = session['username']
	else:
		username = ''

	if form.validate_on_submit():
		session['start'] = form.departure_place.data
		session['end'] = form.destination_place.data		
		return redirect('/bestroute')
	return render_template('index.html', form=form, username = username)
Example #55
0
def search():
    form = SearchForm()

    if form.validate_on_submit():
        match_id = form.query.data
        error = False

        search_log = Search(current_user.get_id(), match_id, request.access_route[0])

        # Trim whitespace chars
        match_id = match_id.strip()

        # Normalize input (in case of unicode variants of chars; can break at urllib.urlencode level later on without this)
        match_id = unicodedata.normalize('NFKC', match_id)

        # If not a decimal input, let's try pull match id from inputs we recognise
        if not unicode.isdecimal(match_id):
            # Pull out any numbers in the search query and interpret as a match id.
            search = re.search(r'([0-9]+)', match_id)
            if search is not None:
                match_id = search.group(1)

        if unicode.isdecimal(match_id):
            _replay = Replay.query.filter(Replay.id == match_id).first()

            # If we don't have match_id in database, check if it's a valid match via the WebAPI and if so add it to DB.
            if not _replay:
                flash('Sorry, we do not have any replay stored for match ID {}'.format(match_id), 'danger')
                return redirect(request.referrer or url_for("index"))

            if _replay:
                search_log.replay_id = _replay.id
                search_log.success = True
                db.session.add(search_log)
                db.session.commit()
                return redirect(url_for("replays.replay", _id=match_id))

        # We only get this far if there was an error or the matchid is invalid.
        if error:
            flash("Replay {} was not on our database, and we encountered errors trying to add it.  Please try again later.".format(match_id), "warning")
        else:
            flash("Invalid match id.  If this match id corresponds to a practice match it is also interpreted as invalid - Dotabank is unable to access practice lobby replays.", "danger")

        search_log.success = False
        db.session.add(search_log)
        db.session.commit()
    return redirect(request.referrer or url_for("index"))
Example #56
0
def home():
    form = SearchForm()
    if form.validate_on_submit():
        try:
            media = Media.query.filter(func.lower(Media.title) ==
                                       func.lower(form.search_string.data)).first()
            if media is None:  # does not already exist in db
                info = get_all_data(form.search_string.data)  # api call
                new_title = info['show_title']
                new_category = info['category']
                new_rating = info['rating']
                new_show_id = info['show_id']
                new_release_year = info['release_year']
                new_show_cast = info['show_cast']
                new_media_type = info['mediatype']
                new_summary = info['summary']
                new_director = info['director']
                new_runtime = info['runtime']
                new_unit = info['unit']
                new_poster = info['poster']
                new_media = Media(title=new_title,
                                  category=new_category,
                                  rating=new_rating,
                                  show_id=new_show_id,
                                  release_year=new_release_year,
                                  show_cast=new_show_cast,
                                  media_type=new_media_type,
                                  summary=new_summary,
                                  director=new_director,
                                  runtime=new_runtime,
                                  unit=new_unit,
                                  poster=new_poster)
                db.session.add(new_media)
                db.session.commit()
                return render_template('show.html',
                                       media=new_media,
                                       isrc=new_poster)
            else:
                isrc = media.poster
                return render_template('show.html',
                                       media=media,
                                       isrc=isrc)
        except:
            flash("""Sorry, that show / movie doesn't seem to be
                  in the Netflix database.""")
    return render_template('home.html',
                           form=form)
Example #57
0
def index():

  form = SearchForm(name='nam')
  if form.validate_on_submit():
    print request.form
    query = form.query.data
    count = form.count.data
    print('Search for="%s", #times=%s' % (query, str(count)))
    if 'nyt' in request.form:
      platypus.play_nyt_articles(query, count)
    if 'twitter' in request.form:
      platypus.play_tweets(query, count)
    return redirect('/')

  return render_template('index.html', 
                         title='Search Tweets',
                         form=form)
Example #58
0
def index():
    form = SearchForm()

    if form.validate_on_submit():
        room = Room()
        form.populate_obj(room)

        # Change room_pref and room_type if they are None
        if not room.room_pref:
            room.room_pref = 0 if room.is_available else 1
        if not room.room_type:
            room.room_type = 1 if room.is_available else 0

        # Search for matching rooms
        rooms_distance = Room.search_rooms(room)
        return render_template("found.html", rooms_distance=rooms_distance)
    return render_template("autoform.html", form=form, title="Search Acco.", submit="Search ad")
Example #59
0
def search():
    form = SearchForm()
    articles = None
    if form.validate_on_submit():
        conditions = []
        if form.title.data != '':
            conditions.append(Article.title.ilike('%' + form.title.data + '%'))
        if form.keyword.data != '':
            conditions.append(or_(Article.title.ilike('%' + form.keyword.data + '%'),
                                  Article.abstract.ilike('%' + form.keyword.data + '%')))
        if form.author.data != '':
            conditions.append(Article.authors.any(Author.lastname.ilike(form.author.data + "%")))
        if form.category.data != '':
            for cname in form.category.data:
                conditions.append(Category.name.ilike(cname + '%'))
        if conditions:
            articles = Article.query.filter(and_(*conditions))
    return render_template('search.html', form=form, articles=articles, navsearch=SimpleSearchForm())