def sports(new_country): field = request.args.get('field') sort = request.args.get('sort') country = Country.query.filter_by(name=new_country).first() if field == 'name': order = Sport.name elif field == 'percent': order = Sport.percent else: order = Sport.count if sort == 'asc': sports = Sport.query.filter_by(country_id=country.id).order_by( order.asc()).all() else: sports = Sport.query.filter_by(country_id=country.id).order_by( order.desc()).all() results = SearchResults() form = SearchForm() if form.validate_on_submit(): name = form.name.data.lower().title() country = Country.query.filter_by(name=name).first() if country is None: flash('Check your spelling') return redirect(url_for('index')) elif country.medals == 0: next_page = request.args.get('next') if not next_page or url_parse(next_page).netloc != '': next_page = url_for('index', field='solo', sort='solo', name=name) return redirect(next_page) else: next_page = request.args.get('next') if not next_page or url_parse(next_page).netloc != '': next_page = url_for('sports', new_country=name) return redirect(next_page) return render_template('sports.html', country=country, sports=sports, form=form, results=results)
def show_book_detail(book_id, sort_id): book = Book() sql_book_id_data = book.get_book_infos_by_book_id(book_id) if len(sql_book_id_data) == 0: abort(404) # print("图书信息:------",sql_book_id_data) book_name = sql_book_id_data[0]['book_name'] sql_detail_data = book.get_book_detail_by_book_id_sort_id(book_id, sort_id) if len(sql_detail_data) == 0: abort(404) next_data = book.get_next_cap_id(book_id, sort_id) if next_data == None: next_sort_id = '' else: next_sort_id = next_data['sort_id'] before_data = book.get_before_cap_id(book_id, sort_id) if before_data == None: before_sort_id = '' else: before_sort_id = before_data['sort_id'] seo = { "title": sql_detail_data[0]['detail_title'] + '_' + book_name + TITLES['bookdetail'][0], # 第二十七章来了_大道朝天 - 笔趣阁 "keywords": book_name + ',' + sql_book_id_data[0]['book_author'] + ',' + sql_detail_data[0]['detail_title'], # 大道朝天,猫腻,第二十七章来了 "description": book_name + "无弹窗,是作者" + sql_book_id_data[0]['book_author'] + "所著的好看的小说" + TITLES['bookdetail'][2] # 大道朝天无弹窗,是作者猫腻所著的玄幻小说类小说,本站提供无弹窗阅读环境 } return render_template("book_detail.html", seo=seo, books_cates=BOOK_CATES, sql_detail_data=sql_detail_data, next_sort_id=next_sort_id, before_sort_id=before_sort_id, book_name=book_name, form=SearchForm())
def check(request): """ Manages the /check/ function, which simply returns True or False for whether or not a hash exists in the database. POST data should be hash=[HASH] OR plaintext=[PLAINTEXT] """ if request.method == 'POST': val = None if 'hash' in request.POST: val = request.POST.get("hash") elif 'val' in request.POST: val = request.POST.get('val') return HttpResponse(str(HashModel.objects.filter(Q(hashval=val) | \ Q(plaintext=val)).exists())) return render_to_response("home.html", {'form' : SearchForm()}, context_instance=RequestContext(request))
def search(): form = SearchForm() if request.method == "POST": if form.validate() == False: return render_template("requestSearch.html", form=form) else: request_ID = form.request_ID.data service = serviceRequest.query.filter_by( service_request_id=request_ID).first() if service is not None: service_info = "Address: " + service.address + " " + service.zipcode + "\n" + "Service Code: " + service.service_code + "\n" + "Service Name: " + service.service_name + "\n" + "Service Description " + service.description + "\n" + "Status: " + service.status + "\n" + "Notes: " + service.status_notes + "\n" + "Date Requested: " + service.request_date + "\n" + "Date Updated: " + service.update_date + "\n" + "Expected Date of Completion: " + service.expected_date + "\n" + "Agency to Respond: " + service.agency_responsible return service_info else: return redirect(url_for('search')) elif request.method == "GET": return render_template('requestSearch.html', form=form)
def post(self, request): form = SearchForm(request.POST) if form.is_valid(): # Little bit of cheating, ideally the html would handle this # but, I felt like building the webapp in django... # alternatively, I could just reach over and build this. start = form.cleaned_data['start'].isoformat() end = form.cleaned_data['end'].isoformat() # POST the query and return the pk, so we can look it up later r = requests.post('http://localhost:9000/api/query/', data={ 'start_date': start, 'end_date': end }) result = Result.objects.create(key=r.json()["pk"]) result.save() # To the results! return HttpResponseRedirect("/{0}/".format(r.json()["pk"])) else: return render(request, 'index.html', {'form': form})
def home(): form = SearchForm() if form.validate_on_submit(): RecipeApiParams = { "ingredients": form.Ingredients.data, "apiKey": RECIPE_API_KEY, } Recipe_Response = requests.get(url=RECIPE_ENDPOINT, params=RecipeApiParams) Recipe_Response.raise_for_status() recipe_data = Recipe_Response.json() if recipe_data != []: RandomRecipe = random.choice(Recipe_Response.json()) return render_template('RecipeInfo.html', recipeData=RandomRecipe) else: flash( "There are no recipes found with this list of ingredients. Please try again!" ) return render_template('home.html', form=form) return render_template('home.html', form=form)
def home(): # Fill out the search form. It's either empty or contains search string. form = SearchForm(request.form) # The use either did a search or interacted with a tweet. if request.method == 'POST': if dispatch_tweet_actions(request.form) == NO_DISPATCH: if form.validate(): return redirect(url_for('tweets', search=form.search.data)) if session.get('logged_in'): user = User(*session['user']) tweet_posts = get_followers_tweets(user.user_id) followers = get_user_followers(user.user_id) message = choice(logged_in_messages) return render_template('home.html', form=form, tweets=chunks(tweet_posts, 3), message=message, followers=followers) else: tweet_posts = get_newest_tweets(18) message = non_logged_in_message return render_template('home.html', form=form, tweets=chunks(tweet_posts, 3), message=message, followers=[])
def search(): keyword = request.args.get('q', default='') page = request.args.get('page', default=1, type=int) if keyword == '': return redirect(url_for('main')) form = SearchForm() res, more = search_(keyword, page) next_url = url_for('search', q=keyword, page=page + 1) if more else None prev_url = url_for('search', q=keyword, page=page - 1) if page > 1 else None return render_template('results.html', results=res, page=page, next_url=next_url, prev_url=prev_url, form=form)
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)
def searchResult(id): # Only logged in users can access bank profile if session.get('username') == None: return redirect(url_for('home')) else: cur, db , engine = connection2() query = "SELECT * FROM SMI_DB.Client WHERE clientID = '" + id + "'" cur.execute(query) data = cur.fetchall() form = ViewProfileForm() search_form = SearchForm() if form.view_submit.data and form.validate_on_submit(): return redirect((url_for('clientProfile', id = id , form = form ))) 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("searchResult.html", data=data, form=form , form2 = search_form)
def search(): form = SearchForm() ''' gets an object of form from search page along with values entered by user in the form ''' ''' condition checked when search button is ''' if form.validate_on_submit(): global searched global area global city global state area = form.area.data city = form.city.data state = form.state.data searched = Post.query.filter((Post.area == form.area.data) & (Post.city == form.city.data) & (Post.state == form.state.data)).all() ''' returns posts which satisfy the searched condition ''' ''' redirects to 'show_post' ''' return redirect(url_for('show_post')) return render_template('search.html', form=form)
def query_yelp(): """ interface with Yelp API search """ form = SearchForm(obj=request.form) if form.validate(): q_string = urlencode(form.data)+"&"+urlencode({"latitude":g.user.latitude,"longitude":g.user.longitude}) req = json.loads(requests.get(api_url+"search?"+q_string,headers={"Authorization": f"Bearer {API_KEY}"}).text) bus_obj_list=remove_discoveries(g.user,parse_resp(req)) shuffle(bus_obj_list) json_list=[] for bus in bus_obj_list: json_list.append(BusEncoder().encode(bus)) return (jsonify(json_list), 201) return (jsonify(data=form.errors),500)
def newfarm(): searchform = SearchForm() if searchform.validate_on_submit(): return redirect('/farms/' + searchform.search.data) form = NewFarmForm() if form.validate_on_submit(): farm = User( farmname=form.farmname.data, address=form.address.data, farmtype=form.farmtype.data, about=form.about.data, username=form.username.data, password=form.password.data, ) db.session.add(farm) db.session.commit() return render_template('newfarm.html', form=form, searchform=searchform)
def product_view(): this_route = url_for('.product_view') if 'email' not in session: app.logger.info("Must have session key to view {}".format(this_route)) return redirect(url_for('login')) form = SearchForm() c = Categories() categories = c.return_categories() p = Product_details() id = request.args.get('id', '') product_details = p.return_product(id) return render_template('product.html', product_info=product_details, form=form, categories=categories)
def search(): form = SearchForm() if form.validate_on_submit(): # print 'aaa' x = {} y = {} query = form.query.data # print query for key in di: for row in di[key]: # print row if query == row['name']: y[query] = row['price'] # print row['name'] for row2 in di[key]: if query != row2['name']: if int(row2['price']) < int(y[query]): x[row2['name']] = row2['price'] # print x return render_template("search.html", form=form, x=x, y=y) return render_template("search_main.html", form=form)
def venues(): # TODO: replace with real venues data. [done] # num_shows should be aggregated based on number of upcoming shows per venue. form = SearchForm() data = [] citys = (Venue.query.distinct(Venue.city, Venue.state).with_entities( Venue.city, Venue.state).order_by(Venue.state, Venue.city).all()) for city in citys: city_data = {} city_data["city"] = city.city city_data["state"] = city.state venues = Venue.query.filter( and_(Venue.city == city.city, Venue.state == city.state)).all() city_data["venues"] = [] for venue in venues: venue_data = {} venue_data["id"] = venue.id venue_data["name"] = venue.name city_data["venues"].append(venue_data) data.append(city_data) return render_template("pages/venues.html", areas=data, form=form)
def buscadorPais(): if 'username' in session: listado = dictCsv("clientes.csv") formulario = SearchForm( enviar="enviar") #instancia objeto en formulario para poder usarlo pais = formulario.search.data #Argentina if formulario.validate_on_submit(): #si llena el buscador paises = [] #lista de diccionarios x cada fila for i in listado: if pais in i['País'] and i[ "País"] not in paises: #si Argentina se encuentra en columna Pais paises.append(i['País']) #agerga el pais encontrado if paises: #si tiene contenido flash("Búsqueda exitosa") else: flash('No se encontraron paises') return render_template( 'buscador.html', paises=paises, formulario=formulario ) #me guardo pais buscado para hipervinculo y lista para imprimir return render_template('buscador.html', formulario=formulario) return redirect(url_for('ingresar'))
def index(): field = request.args.get('field') sort = request.args.get('sort') name = request.args.get('name') country = Country.query.filter_by(name=name).first() if field == 'gdp': order = Country.gdp elif field == 'population': order = Country.population elif field == 'medals': order = Country.medals else: order = Country.name if sort == 'desc': countries = Country.query.order_by(order.desc()).all() elif sort == 'solo': countries = [] else: countries = Country.query.order_by(order.asc()).all() form = SearchForm() if form.validate_on_submit(): name = form.name.data.lower().title() country = Country.query.filter_by(name=name).first() if country is None: flash('Check your spelling') return redirect(url_for('index')) elif country.medals == 0: next_page = request.args.get('next') if not next_page or url_parse(next_page).netloc != '': next_page = url_for('index', sort='solo', name=name) return redirect(next_page) else: next_page = request.args.get('next') if not next_page or url_parse(next_page).netloc != '': next_page = url_for('metrics', new_country=name) return redirect(next_page) return render_template('landing_page.html', country=country, countries=countries, form=form)
def search(): form = SearchForm() if session["logged_in"] == True: if form.validate_on_submit(): isbn = request.form.get("isbn") res = db.execute("SELECT * FROM books WHERE isbn LIKE :isbn", { "isbn": isbn }).fetchone() if res: if res['isbn']: # review = requests.get("https://www.goodreads.com/book/review_counts.json", # params={"key": "UnJEUENuYcvAB9ZAWrD7Q", "isbns": isbn}, proxies=proxies) #review = review.json() resp = requests.get( 'https://www.goodreads.com/review/list.xml', params={ 'key': 'UnJEUENuYcvAB9ZAWrD7Q', 'v': 2, 'id': myuserid }) book = '' if resp.status_code == 200: data_dict = xmltodict.parse( resp.content)['GoodreadsResponse'] review = data_dict['reviews']['review'] for item in review: if (item['book']['isbn']) == isbn: book = item['book'] #description = book['description'] return render_template('search.html', title='search', form=form, res=res, book=book) return render_template('search.html', title='search', form=form) flash('not found') return render_template('search.html', title='search', form=form) return render_template('home.html')
def searchReferee(): form = SearchForm() if form.is_submitted(): refID = request.form['refID'] refFirstName = request.form['refFirstName'] refLastName = request.form['refLastName'] age = request.form['age'] salary = request.form['salary'] workingYears = request.form['workingYears'] mydb = mysql.connector.connect(host="localhost", user="******", passwd="123456", database="NBA") mycursor = mydb.cursor() if mycursor: query = "SELECT * FROM Referee WHERE TRUE " if refID: query += "AND RefID = '" + refID + "' " if refFirstName: query += "AND FirstName = '" + refFirstName + "' " if refLastName: query += "AND LastName = '" + refLastName + "' " if age: query += "AND Age = '" + age + "' " if salary: query += "AND Salary = '" + salary + "' " if workingYears: query += "AND WorkingYears = '" + workingYears + "' " print(query) mycursor.execute(query) myresult = mycursor.fetchall() titles = [ "RefereeID", "Referee First Name", "Referee Last Name", "Age", "Salary", "Working Years" ] return render_template('home.html', form=form, myresult=myresult, titles=titles) return render_template('searchReferee.html', form=form)
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)
def search(): form = SearchForm() res = [] if(form.validate_on_submit()): author = request.form['index'] query = request.form['query'] numResults = 10 es = elasticsearch.Elasticsearch() results = es.search( index=author, body={ "size": numResults, "query": {"match": {"text": {"query": query}}}}) print(results) hitCount = results['hits']['total']['value'] print(hitCount) if hitCount > 0: if hitCount is 1: print(str(hitCount) + ' result') else: print(str(hitCount) + ' results') for hit in results['hits']['hits']: text = hit['_source']['text'] lineNum = hit['_source']['lineNum'] score = hit['_score'] title = hit['_type'] if lineNum > 1: previousLine = es.get(index=author,E id=lineNum-1) nextLine = es.get(index=author, id=lineNum+1) res.append(title + ': ' + str(lineNum) + ' (' + str(score) + '): ') res.append(previousLine['_source']['text'] + text + nextLine['_source']['text']) else: print('No results') print(form) return render_template('search.html', form=form, res=res)
def adduser_page(): searchform = SearchForm() if searchform.validate_on_submit(): flash('Search requested for item {}'.format(searchform.search.data)) return redirect('/searchuser/' + searchform.search.data) form = NewUserForm() if form.validate_on_submit(): flash( 'New user instance requested for\nfname:{}\nlname:{}\nfootsize:{}'. format(form.fname.data, form.lname.data, form.footsize.data)) user = User(fname=form.fname.data, lname=form.lname.data, footsize=form.footsize.data) db.session.add(user) db.session.commit() return redirect('/searchuser/' + str(user.id)) return render_template('newuser.html', title='NewUser', searchform=searchform, form=form)
def zipcode_post(request): #return HttpResponse("Hello Weather") if (request.method == "POST"): form = SearchForm(request.POST) if form.is_valid(): url=weather_url.format(request.POST['ciudad']) response = requests.get(url) json_response = json.loads(response.text) w= Weather(temperature=k_to_c(json_response["main"]["temp"]),zipcode=zipcode, description=json_response["weather"][0]["description"], sunrise= json_response["sys"]["sunrise"], sunset= json_response["sys"]["sunset"],wind= json_response["wind"]["speed"]) w.save() #html="<html><body>%s y %s</body></html>"% (w.temperature, w.zipcode) context_dict = {} context_dict['temperature'] = k_to_c(json_response["main"]["temp"]) context_dict['zipcode'] = zipcode context_dict['description'] = json_response["weather"][0]["description"] context_dict['sunrise']= datetime.utcfromtimestamp(json_response["sys"]["sunrise"]) context_dict['sunset']= datetime.utcfromtimestamp(json_response["sys"]["sunset"]) context_dict['wind']= json_response["wind"]["speed"] return render(request, 'weather/weather.html', context_dict)
def search_func(): global matrix, dictionary form = SearchForm() if request.method == 'POST': if 'prepare data' in request.form: matrix, dictionary = preprocess() flash(f'Data loaded!', 'success') return redirect('/search') else: text = request.form['text'] k = int(request.form['k']) results = search(dictionary, matrix, text, k, return_res=True) return render_template('search.html', title='Search', form=form, results=results) return render_template('search.html', title='Search', form=form, results=[])
def about(): if 'email' not in session: return redirect(url_for('login')) form = SearchForm() cid = session['id'] email = session['email'] user = User.query.filter_by(email=email).first() keys = Info.query results = [] if request.method == "POST": if form.validate() == False: return render_template('signup.html', form=form) else: if form.search.data is not None: results = db_session.query(Info).filter( Info.key.like('%' + form.search.data + '%'), Info.user_id == cid) return render_template('results.html', results=results) elif request.method == "GET": return render_template('about.html', form=form)
def search_email_in_mysql(): """ This function shows emails that match a keyword, including their classification """ form = SearchForm() if form.validate_on_submit(): # Create a cursor object for the database cursor = g.db_instance.getCursor() # Execute a query to retrieve the shared activity. cursor.execute( """SELECT * FROM emails_with_classification WHERE email_subject LIKE %s """, ("%" + form.query.data + "%", )) # Fetch the results result = cursor.fetchall() data = [] for row in result: data.append({ "id": str(row['id']), "relevance": "n/a", "metadata": row['email_metadata'][:200], "subject": row['email_subject'], "body": row['email_body'][:200], "isSpam": ("yes" if row['is_spam'] is 1 else "no") }.copy()) return render_template('search_results.html', data=data) return render_template('search_email_in_mysql.html', title='Search in MySQL:', form=form)
def index(): form = SearchForm() if request.args.get("book"): text = request.args.get("book") # Take input and add a wildcard query = f"%{text}%".lower() rows = db.execute("SELECT book_id, isbn, title, author, year FROM books WHERE isbn LIKE :search OR title LIKE :search OR author LIKE :search", {"search": query}) # Books not founded if rows.rowcount == 0: flash( f'No Book Found "{request.args.get("book")}" Try Again !!', 'danger') return redirect(url_for('index')) # Fetch all the results books = rows.fetchall() return render_template("dashboard.html", title="Home", form=form, books=books) return render_template("dashboard.html", title="Home", form=form)
def index(request, mlist_fqdn, message_id_hash): ''' Displays a single message identified by its message_id_hash (derived from message_id) ''' search_form = SearchForm(auto_id=False) store = get_store(request) message = store.get_message_by_hash_from_list(mlist_fqdn, message_id_hash) if message is None: raise Http404 message.sender_email = message.sender_email.strip() set_message_votes(message, request.user) mlist = store.get_list(mlist_fqdn) context = { 'mlist': mlist, 'message': message, 'message_id_hash': message_id_hash, 'months_list': get_months(store, mlist.name), 'reply_form': ReplyForm(), } return render(request, "message.html", context)
def search(): form = SearchForm() if form.validate_on_submit(): if form.search_radio.data == 'book': books = Book.query.filter( Book.bookname.contains(form.search_attr.data)).all() if not books: flash(u"Нет такой книги") return render_template('search.html', form=form, user=current_user, books=books) else: authors = Author.query.filter( Author.authorname.contains(form.search_attr.data)).all() if not authors: flash(u"Нет такого автора") return render_template('search.html', form=form, user=current_user, authors=authors) return render_template('search.html', form=form, user=current_user)