def inputform(): form = QueryForm() if form.validate_on_submit(): query = form.query.data df = pd.read_pickle('cmu_data_phrase.pkl') #Get top-n entries by score ranking df['score'] = df.apply(lambda row: get_score( query, row.noun_phrase, row.sentiment, alpha=0.95), axis=1) df_topn = df.nlargest(500, 'score') df_topn.reset_index(inplace=True) recommendations = get_recommendation(query, df, df_topn, n=500, NUM_CLUSTERS=10) # session['btitle'] = [] # for book in recommendations: # session['btitle'].append(book['book_title']) # flash('Query Submitted!','success') return render_template('output.html', recommendations=recommendations, query=query) return render_template('inputform.html', form=form)
def query_editor(request, query_id=None): form = QueryForm(request.POST) if request.method == 'POST' else QueryForm() query = None if query_id is not None: try: query = Query.objects.get(id=query_id) except: pass if not query: return HttpResponseRedirect("/sql_dashboards/query/") if request.method == "GET" and query_id is not None: form = QueryForm(instance=query) elif request.method == "POST" and ("run" in request.POST or "save" in request.POST or "run_save" in request.POST): form = QueryForm(request.POST, instance=query) if query else QueryForm(request.POST) if form.is_valid(): query = form.save(commit=("save" in request.POST or "run_save" in request.POST), user=request.user) if query and ("run" in request.POST or "run_save" in request.POST): query_executed = True print(request.POST.keys()) custom_data = dict([(k, v.initial) for k, v in CustomQueryForm(query).fields.items()]) if query.custom else None query.getAll(custom_data=custom_data) if request.method == "POST" and "save" in request.POST: return HttpResponseRedirect("/sql_dashboards/query/edit/%s" % query.id) return render_to_response("django_sql_dashboards/query_editor.html", locals(), RequestContext(request))
def index(request): if request.method == 'GET': form = QueryForm() return render(request, 'builder/index.html', { 'form': form, }) # Render Form elif request.method == 'POST': form = QueryForm(request.POST) if form.is_valid(): print form.cleaned_data query = 'SELECT %s FROM %s.%s.%s;' % ( form.cleaned_data['field'], form.cleaned_data['host'], form.cleaned_data['service'], form.cleaned_data['series'] ) data = db.query(query) data = influxdb_dataset(data) ret_value = json.dumps([series.to_dygraph() for series in data], indent=2) return render(request, 'api/basicgraph.html', { 'data': ret_value, 'query': query })
def queryHome(request): if request.method == "POST": # display query.query.html which includes queryResult.inc.html queryForm = QueryForm(request.POST) print queryForm.is_valid() queryID = md5.new(str(queryForm.cleaned_data)).hexdigest() if "queries" not in request.session: request.session["queries"] = {} request.session["queries"][queryID] = queryForm flows = Flow.objects.filter(getQFromQueryForm(queryForm)) return render_to_response("query.query.html", { 'queryForm': queryForm, 'queryID': queryID, 'resultsCount': len(flows), }, context_instance = RequestContext(request)) else: # display query.home.html queryForm = QueryForm() return render_to_response("query.home.html", { 'queryForm': queryForm, }, context_instance = RequestContext(request))
def home(): global q_str, doc_dict, posting, info, q_res if not (os.path.exists(rindex_file) and os.path.exists(docs_file)): ind_f = open(rindex_file, 'w') doc_f = open(docs_file, 'w') createIndex() json.dump(doc_dict, doc_f) json.dump(posting, ind_f) doc_f.close() ind_f.close() else: ind_f = open(rindex_file) doc_f = open(docs_file) d_dict = json.load(doc_f) doc_dict = { int(key):val for key,val in d_dict.items() } posting = json.load(ind_f) info = str(len(doc_dict)) + ' documents indexed with '\ + str(len(posting)) + ' unique words' doc_f.close() ind_f.close() content = {'info':info, 'res':q_res} form = QueryForm() if form.validate_on_submit(): q_str = form.queryid.data return redirect('/query') return render_template('home.html', content = content, form = form)
def delete_item(): form = QueryForm() if form.validate_on_submit(): db_session.query(Items).filter_by(name=form.name.data).delete( synchronize_session=False) db_session.commit() return redirect(url_for('success')) return render_template('delete.html', form=form)
def homepage(): """ Render the homepage template on the / route """ form = QueryForm() if form.validate_on_submit(): return redirect(url_for('home.show_results'), code=307) return render_template('home/index.html', form=form, title="Psiholeks")
def query(request): form = QueryForm(request.GET) if not form.is_valid(): return render_to_response('query.html') key=[] for fltr in ['commitee_filter', 'political_filter', 'country_filter']: val=form.cleaned_data.get(fltr) if val: key.append(val) meps = MEP.view('meps/query', startkey=key) return render_to_response('query.html', { 'meps': meps})
def success(): form = QueryForm() if form.validate() == False: flash('All fields are required.') req = request.form['query'] print("REQUEST: ", req) results = search(req) table = Results(results) table.border = True return render_template("search.html", table=table, form=form)
def get_history(): # usernames are unique so we don't have to worry here if current_user.name == 'admin': form = QueryForm(request.form) if request.method == 'POST' and form.validate(): query_id = form.data['query_id'] # could this be an issue? return redirect('/history/query{}'.format(query_id)) return render_template("query_admin.html", form=form) return render_template("query_history.html", query_spells=current_user.spell_check)
def queryPage(): results = None table = None form = QueryForm() if form.validate_on_submit(): table, results = query() return render_template('query.html', query=form, queryResult=results, table=table, isAdmin=config.adminLoggedIn)
def main_page(): form = QueryForm() if form.validate_on_submit(): movies = between_years(form.min_year.data, form.max_year.data, form.number.data) m = [ json.dumps(movie.__dict__, ensure_ascii=False) for movie in movies ] session['movies'] = m return redirect(url_for('movie_list')) return render_template('form.html', form=form)
def index(request): indexContext = {} if request.GET and request.method == 'GET': school_choice = request.GET.get('school_choice') sex_choice = request.GET.get('sex_choice') event_choice = request.GET.get('event_choice') name_choice = request.GET.get('name_choice') # Get results results = AthResults.objects.filter(school=school_choice, sex=sex_choice, event=event_choice, name=name_choice) indexContext['results'] = results # Prepare data if len(results) > 0: is_track = results[0].is_track else: is_track = 0 plot_x = [res.date.strftime('%Y-%m-%d') for res in results] plot_y = [res.result for res in results] # Prepare form form = QueryForm( initial={ 'school_choice': school_choice, 'sex_choice': sex_choice, 'event_choice': event_choice, 'name_choice': name_choice, }) else: # Prepare data is_track = 0 plot_x = [] plot_y = [] # Prepare form form = QueryForm( initial={ 'school_choice': None, 'sex_choice': None, 'event_choice': None, 'name_choice': None, }) indexContext['is_track'] = is_track indexContext['plot_x'] = json.dumps(plot_x) indexContext['plot_y'] = json.dumps(plot_y) indexContext['form'] = form return render(request, 'ath_res_vis/index.html', indexContext)
def query(request, **kwargs): if request.method == 'GET' and len(request.GET) > 0: form = QueryForm(request.GET) if form.is_valid(): db=form.cleaned_data['db'] db.encoding_in = form.cleaned_data['charset_in'] db.encoding_out = form.cleaned_data['charset_out'] db.syntax = form.cleaned_data['syntax'] books = db.query(form.cleaned_data['query_type'], form.cleaned_data['query']) b_len = len(books) else: form = QueryForm() return render_to_response(kwargs['tpl'], locals())
def index(): query_form = QueryForm() # 调用WTF的函数实现验证 if query_form.validate_on_submit(): # 验证通过 获取数据 input_word = query_form.word.data # 判断单词是否存在 查询数据库 session = Session() word = session.query(Dictionary).filter_by(word=input_word).first() if word: # try: words = session.query(Dictionary).filter_by(word=input_word) # print(words) session.close() return render_template("index.html", form=query_form, words=words) else: try: paraph = youdao.get_data(input_word) new_word = Dictionary(word=paraph[0], IPA=paraph[1], paraphrase=paraph[2], example_sentence=paraph[3] + paraph[4], other=paraph[5]) session.add(new_word) session.commit() flash("添加成功") words = session.query(Dictionary).filter_by(word=input_word) session.close() return render_template("index.html", form=query_form, words=words) except Exception as e: print(e) flash("添加失败") session.rollback() words = session.query(Dictionary).order_by( func.rand()).limit(5) session.close() return render_template("index.html", form=query_form, words=words) session = Session() words = session.query(Dictionary).order_by(func.rand()).limit(5) session.close() return render_template("index.html", form=query_form, words=words)
def query(request): form = QueryForm(request.GET) if not form.is_valid(): return render_to_response('query.html') key=[] #for fltr in ('commitee_filter', 'group_filter', 'country_filter'): # val=form.cleaned_data.get(fltr) # if val: key.append(val) key=[form.cleaned_data.get('country_filter') or u'DE', form.cleaned_data.get('group_filter') or u'PPE', form.cleaned_data.get('commitee_filter',None)] print key meps = MEP.view('meps/query', key=key) return render_to_response('query.html', { 'meps': meps})
def demo_page(): form = QueryForm() if form.validate_on_submit(): word = form.word.data model = form.model.data conf = form.conf.data iteration = form.iteration.data results, var_count = search_UrbanDict(word, model, conf, iteration) return render_template('index.html', data=results, var_count=var_count, form=form) return render_template('index.html', form=form)
def index(request): metalex_files = glob.glob(FILES_DIR + "*_ml.xml") r_count = len(metalex_files) if r_count == 0: r_count = 27000 # info = urllib2.urlopen("http://doc.metalex.eu:8000/status/size/") # html = info.read() # # match = re.search(r'<th>Total</th><td>(.*?)</td>', html) # if match : # t_count = long(match.group(1)) # else : # t_count = 100000000 try: locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') except: locale.setlocale(locale.LC_ALL, 'en_US') regulations_count = locale.format("%d", r_count, grouping=True) #triples_count = locale.format("%d", t_count, grouping=True) form = QueryForm() t = get_template('index.html') html = t.render( RequestContext(request, { 'regulations': regulations_count, 'form': form })) return HttpResponse(html)
def index(): form = QueryForm() if request.method == 'POST': query_str = form.name.data p = PersonInfo.query.filter( or_(PersonInfo.cn_name.like('%{}%'.format(query_str)), PersonInfo.en_name.like('%{}%'.format(query_str)), PersonInfo.gender.like('%{}%'.format(query_str)), PersonInfo.id_num.like('%{}%'.format(query_str)), PersonInfo.permit_num.like('%{}%'.format(query_str)), PersonInfo.passport.like('%{}%'.format(query_str)), PersonInfo.home_address.like('%{}%'.format(query_str)), PersonInfo.post_address.like('%{}%'.format(query_str)), PersonInfo.company_address.like('%{}%'.format(query_str)), PersonInfo.bank_account.like('%{}%'.format(query_str)), PersonInfo.party_tag.like('%{}%'.format(query_str)), PersonInfo.occupation.like('%{}%'.format(query_str)), PersonInfo.private_phone.like('%{}%'.format(query_str)), PersonInfo.office_phone.like('%{}%'.format(query_str)), PersonInfo.fax.like('%{}%'.format(query_str)), PersonInfo.other_number.like('%{}%'.format(query_str)), PersonInfo.email.like('%{}%'.format(query_str)), PersonInfo.internet_account.like('%{}%'.format(query_str)), PersonInfo.home_page.like('%{}%'.format(query_str)), PersonInfo.family.like('%{}%'.format(query_str)), PersonInfo.hobby.like('%{}%'.format(query_str)), PersonInfo.experience.like('%{}%'.format(query_str)), PersonInfo.event.like('%{}%'.format(query_str)), PersonInfo.stain.like('%{}%'.format(query_str)))).all() return render_template('list.html', data=p) else: return render_template('index.html', form=form)
def new_query(request, report): report = get_object_or_404(Report, slug=report) if request.method == 'POST': form = QueryForm(request.POST) if form.is_valid(): f = form.save(commit=False) f.report = report f.created_by = request.user.username f.save() messages.success(request, "Created new report query: %s" % f.query) return HttpResponseRedirect(reverse('reports.views.view_report', kwargs={'report':report.slug})) else: form = QueryForm() return render(request, 'reports/new_query.html', {'form': form, 'report': report })
def submit_queries(): qform = QueryForm() error = None data = "" if qform.validate_on_submit(): #user input patient_id = qform.p_id.data start_date = qform.start_date.data end_date = qform.end_date.data query_type = qform.query_type.data data = run_query(patient_id, start_date.strftime('%Y-%m-%d'), end_date.strftime('%Y-%m-%d'), query_type) else: data = "Not Ready" return render_template('queries.html', error=error, form=qform, results=data) return render_template('queries.html', error=error, form=qform, results=data)
def query_from_form(): form = QueryForm( queryText='enwiki:Antibiotics/Medical%20uses/Administration') if form.is_submitted() and form.validate(): # ----------------- EVAL ----------------- if form.rankOrEval.data == "eval": formatted_response = send_request(form) if formatted_response == 0: flash(f'Query {form.queryText.data} failed!', 'danger') return render_template("queries.html", title="Query", form=form) if form.expansionModel.data == "none" and form.expansionWords.data == "" and form.file.data is None: flash(f'Query {form.queryText.data} submitted!', 'success') return render_template("singleQuery.html", query=formatted_response) else: flash(f'Query {form.queryText.data} submitted!', 'success') return render_template("expandedQuery.html", query=formatted_response) # ----------------- RANK ----------------- elif form.rankOrEval.data == "rank": ranked_results = ranking_query_form(form) if ranked_results == 0: flash(f'Query {form.queryText.data} failed!', 'danger') return render_template("queries.html", title="Query", form=form) flash(f'Query {form.queryText.data} submitted!', 'success') return render_template("rankView.html", title="Query", response=ranked_results[0], good_word_map=ranked_results[1], count=ranked_results[2], original=ranked_results[3]) # ----------------- Failure ----------------- flash(f'Query {form.queryText.data} failed!', 'danger') return render_template("queries.html", title="Query", form=form)
def main(): form = QueryForm() if request.method == 'POST': if form.validate() is False: flash('required') return render_template('main.html', form=form) else: filterDict = makeFiltersList(form) print(filterDict) results = IndexHandle('musicindex', 'music', form.search_key.data, filterDict) playlist = build_playlist(results.results) # app.logger.info(playlist) return render_template('index.html', form=form, results=results.results, playlist=playlist) elif request.method == 'GET': return render_template('main.html', form=form)
def edit_query(request, report, query_id): report = get_object_or_404(Report, slug=report) query = get_object_or_404(Query, id=int(query_id)) if request.method == 'POST': form = QueryForm(request.POST) if form.is_valid(): f = form.save(commit=False) f.report = report f.created_by = request.user.username f.save() query.delete() messages.success(request, "Edited query: %s" % f.query) return HttpResponseRedirect(reverse('reports.views.view_report', kwargs={'report':report.slug})) else: form = QueryForm(instance=query) return render(request, 'reports/edit_query.html', {'form': form, 'report': report, 'query_id':query_id })
def list_results(request): """ list_results(request): called when list_requests.html is accessed. Displays bibtex info in user-friendly format for terms that match query """ outstring = 'No Results to Display' # if no results, display this to user if request.method == 'POST': form=QueryForm(request.POST) if form.is_valid(): search=str(request.POST['title']) connection = sqlite3.connect("bibtexinfo.db") cursor = connection.cursor() sql_cmd="SELECT * FROM bib WHERE "+search try: cursor.execute(sql_cmd) db_info = cursor.fetchall() if len(db_info)>0: outstring='' # if query successful, no error message is printed except: outstring = 'Invalid Format! Please Try Again' # if exception is raised, print format error db_info = [] form=QueryForm() return render_to_response('list_results.html',locals(),context_instance=RequestContext(request))
def query(): sno = {} sname = {} class_1 = {} class_2 = {} class_3 = {} class_4 = {} class_5 = {} qz = {} qm = {} group = {} chaiji = {} form = QueryForm() if form.validate_on_submit(): num = form.student_number.data results = Marks_record.query.filter_by(username=num).order_by( Marks_record.id.asc()).first() sno[num] = results.sno sname[num] = results.sname class_1[num] = results.class_1 class_2[num] = results.class_2 class_3[num] = results.class_3 class_4[num] = results.class_4 class_5[num] = results.class_5 qz[num] = results.qz qm[num] = results.qm group[num] = results.group chaiji[num] = results.chaiji return render_template('main/query.html', form=form, sno=sno, sname=sname, class_1=class_1, class_2=class_2, class_3=class_3, class_4=class_4, class_5=class_5, qz=qz, qm=qm, group=group, chaiji=chaiji)
def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['form'] = QueryForm() context['pagination'] = self.pagination context['statics'] = self.statics context['unconfirmed'] = str( sum((value for key, value in self.statics.items() if key != "confirmed"))) context['notice'] = _( 'Notice:you have %s of work order not been confirmed!' ) % context['unconfirmed'] return context
def post(self, request): """A handler for a POST web request from search view Provides a web page with filled query form and listed queried tweets from twitter and/or saved queried data in mongoDB database with a specified tag :param request: HTTP web POST request :return: a web page with a search interface """ form = QueryForm(request.POST) if form.is_valid(): if 'form_save' in request.POST: # TODO: Implement async waiting for saving with progress bar self.save(form) return self.search(request, form) header = 'Error occurred' pages = [] return render( request, self.template_name, {'form': form, 'header': header, 'pages': pages})
def get_form_params(self): req = self.request form = QueryForm(req.GET) params = {} params["pageNo"] = req.GET.get('page_no', 0) params["pageSize"] = utils.get_page_size(req) params["apply_start"] = req.GET.get('start', ) params["apply_end"] = req.GET.get('end', ) params["status"] = req.GET.get('status', 'all') params["type"] = req.GET.get('type', 'all') params["sno"] = req.GET.get('workorder_no', ) params["apply_by"] = req.user.username params["user"] = req.user.username return params
def query_new(request): if request.method == "POST": form = QueryForm(request.POST.copy()) if form.is_valid(): query = form.save(commit=False) query.user = request.user query.save() return redirect('pred_list') else: form = QueryForm() return render(request, 'deep_stylo/query_edit.html', {'form': form})
def query(): form = QueryForm() g = rdflib.Graph() if(os.path.isfile('.\generated\DeviceList-a-rdf.xml') == False): return render_template("FileNotExist.html") g.parse(".\generated\DeviceList-a-rdf.xml") #form.query.data = '''SELECT DISTINCT ?name # WHERE { # ?a MAWSDevice:hasLocation ?name.}''' if form.confirm.data: queryStr = str(form.query.data) qres = g.query(queryStr) resutlStr ='' for row in qres: resutlStr = resutlStr+str(row) form.result.data = resutlStr form.query.data = queryStr return render_template('MAWSQuery.html', form=form)
def clientesPorProducto(): if 'username' in session: fileStatus = data_manipulation.error_check() queryForm = QueryForm() productList = data_manipulation.get_product_list() if not fileStatus: if queryForm.autocompleteInput.data in productList: fileHeader = ['CODIGO', 'PRODUCTO', 'CLIENTE', 'CANTIDAD', 'PRECIO'] clientList = data_manipulation.clients_by_product(queryForm.autocompleteInput.data) return render_template('clientesPorProducto.html', row1=fileHeader, dataTable=clientList, productList=productList, form=queryForm, username=session.get('username')) flash('Por favor seleccione un producto de la lista') return render_template('clientesPorProducto.html', productList=productList, form=queryForm, fileStatus=fileStatus, username=session.get('username')) flash('Debe estar logueado para acceder al modulo') return redirect('/login')
def queries(): form = QueryForm() cities = mongo.db.cities citiesData = [] holder = cities.find().sort("population",1) for city in holder: citiesData.append({'name': city['name'] , 'population': city['population']}) #citiesData = jsonify(citiesData) #print citiesData[] query={} if request.method == 'POST': result = [] if (request.form['sort']=='D'): key = -1 else: key= 1 #country only and country and continent if (request.form['country']): cty = request.form['country'] for city in cities.find({'country':cty}).sort('population',key): result.append({'name': city['name'] , 'population': city['population']}) #none elif (not request.form['country'] and request.form['continent']=='Unspecified'): holder = cities.find().sort('population',key) for city in holder: result.append({'name': city['name'] , 'population': city['population']}) #continent only elif (not request.form['country'] and request.form['continent']!='Unspecified'): holder = cities.find({"timeZone" : {'$regex' : '.*' + request.form['continent'] + '.*'}}).sort('population',key) for city in holder: result.append({'name': city['name'] , 'population': city['population']}) else: result = str("Try again!") return render_template('queries.html',form=form,citiesData=result) return render_template('queries.html', form=form, citiesData=citiesData)
def query_edit(request, query_id=False, template='poll/query_form.html'): if query_id: instance = Query.objects.get(id=query_id) else: instance = None if request.method == 'POST': form = QueryForm(request.POST, instance=instance) if form.is_valid(): query = form.save(commit=False) if not query_id: query.user = request.user query.save() messages.add_message(request, messages.SUCCESS, ugettext("Successfully saved query: %s") % query.name) return HttpResponseRedirect(reverse('query-view', args=[query.id])) form = QueryForm(instance=instance) data = {'form': form} return render_to_response(template, data, context_instance=RequestContext(request))
def index(): form = QueryForm(request.form) return render_template('index.html', form=form)
def search(request): if request.method == 'POST' : form = QueryForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] date = form.cleaned_data['date'] query = """PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX dcterms: <http://purl.org/dc/terms/> PREFIX prov: <http://www.w3.org/ns/prov#> SELECT DISTINCT ?regulation ?title ?date ?sc WHERE {{ ?regulation dcterms:title ?title . ?title bif:contains "{}" OPTION( SCORE ?sc ). ?regulation prov:wasGeneratedAtTime ?date . FILTER(?date <= '{}'^^xsd:date) }} ORDER BY DESC(?sc) DESC(?date) LIMIT 500 """ sparql = SPARQLWrapper(SPARQL_ENDPOINT) sparql.setReturnFormat(JSON) try : formatted_query = query.format(title, date) sparql.setQuery(formatted_query) sparql_results = sparql.query().convert() except : try : formatted_query = query.format("'{}'".format(title),date) sparql.setQuery(formatted_query) sparql_results = sparql.query().convert() except : return HttpResponse("Something went wrong!<br/>Your query was:<br/><pre>{}</pre>".format(formatted_query)) results = [] for row in sparql_results['results']['bindings'] : r = {} r['uri'] = row['regulation']['value'] r['title'] = row['title']['value'] r['date'] = row['date']['value'] r['xml'] = r['uri'].replace('/id/','/doc/') + '/data.xml' r['n3'] = r['uri'].replace('/id/','/doc/') + '/data.n3' r['score'] = row['sc']['value'] results.append(r) endpoint = "http://doc.metalex.eu:8000/sparql" query_link = "http://yasgui.data2semantics.org/?query={}&endpoint={}&tabTitle={}".format(urllib.quote(formatted_query),urllib.quote(endpoint), urllib.quote(title)) t = get_template('results.html') html = t.render(RequestContext(request, {'results': results, 'title': title, 'date': date, 'query_link': query_link})) return HttpResponse(html) else: form = QueryForm() t = get_template('search.html') html = t.render(RequestContext(request, {'form': form,})) return HttpResponse(html)
def runquery(): form = QueryForm() query_results = [] columns = [] if form.validate_on_submit(): try: s = str(form.query.data) s = s.strip() if s.find(';') == -1: raise Exception("Semicolon (;) missing") if s.find(';') != len(s) - 1: raise Exception("Multiple queries not allowed") try: cursor.execute(form.query.data) except: re_connect() cursor.execute(form.query.data) results = cursor.fetchall() columns = cursor.column_names query_results = results except Exception as e: if ("Table" in str(e)) and ("doesn't exist" in str(e)): # means has to suggest table also... if all_table_names == []: fill_all_table_names() last_index = str(e).find("' doesn't") first_index = str(e).find("'antique_store") suggestion = difflib.get_close_matches( str(e)[first_index + 15:last_index], all_table_names) #print('Error: ' + str(e) + "\n Do you mean: " + str(suggestion)) if (suggestion == []): message = 'Error: ' + str( e ) + "... NO table found in the database with similar name " else: message = 'Error: ' + str(e) + "... Do you mean: " + str( suggestion) flash(message, 'danger') elif "Unknown column" in str(e): first_index = 16 + str(e).find("Unknown column") last_index = str(e).find("' in 'field list'") column_name_inserted = str(e)[first_index:last_index] q = str(form.query.data) table_name = q[q.find("from") + 5:-1] column_names = get_column_names(table_name) #print(column_names) #print(column_name_inserted) suggestion = difflib.get_close_matches(column_name_inserted, column_names) if (suggestion == []): message = 'Error: ' + str( e ) + "...... NO column found in the table with similar name " else: message = 'Error: ' + str( e) + "...... Do you mean: " + str(suggestion) flash(message, 'danger') else: flash('Error: ' + str(e), 'danger') else: flash('Query run successfully!', 'success') # if request.method == 'POST': # if request.form['export_btn'] == "export to csv": # si = StringIO.StringIO() # cw = csv.writer(si) # cw.writerow([columns]) # cw.writerows(query_results) # response = make_response(si.getvalue()) # response.headers['Content-Disposition'] = 'attachment; filename=report.csv' # response.headers["Content-type"] = "text/csv" # return response return render_template('runquery.html', form=form, columns=columns, query_results=query_results, title='Run query')
def search(): form = QueryForm() if form.validate() == False: flash('All fields are required.') return render_template('search.html', form=form, table="")
def query(): form = QueryForm() if form.number.data: Number = form.number.data if form.testTool.data: if form.starttime.data and form.stoptime.data: modules3 = Modules.query.filter( Modules.number.like('%' + str(Number) + '%')).all() modules1 = Modules.query.filter_by( testTool=form.testTool.data).all() modules2 = Modules.query.filter( Modules.testTime >= form.starttime.data, Modules.testTime < form.stoptime.data).all() all_modules = list(set(modules1).intersection(set(modules2))) modules = list(set(modules3).intersection(set(all_modules))) return render_template('query.html', form=form, modules=modules) #modules1=Modules.query.filter_by(number = Number,testTool = form.testTool.data).all() #modules2=Modules.query.filter(Modules.testTime>=form.starttime.data,Modules.testTime<form.stoptime.data).all() #modules=list(set(modules1).intersection(set(modules2))) #return render_template('query.html',form=form,modules=modules) else: #modules=Modules.query.filter_by(number=form.number.data,testTool = form.testTool.data).all() #return render_template('query.html',form=form,modules=modules) modules1 = Modules.query.filter( Modules.number.like('%' + str(Number) + '%')).all() modules2 = Modules.query.filter_by( testTool=form.testTool.data).all() modules = list(set(modules1).intersection(set(modules2))) return render_template('query.html', form=form, modules=modules) else: if form.starttime.data and form.stoptime.data: modules1 = Modules.query.filter( Modules.number.like('%' + str(Number) + '%')).all() modules2 = Modules.query.filter( Modules.testTime >= form.starttime.data, Modules.testTime < form.stoptime.data).all() modules = list(set(modules1).intersection(set(modules2))) return render_template('query.html', form=form, modules=modules) else: #print number #共单号查询 #modules=Modules.query.filter_by(number=form.number.data).all() #return render_template('query.html',form=form,modules=modules) modules = Modules.query.filter( Modules.number.like('%' + str(Number) + '%')).all() return render_template('query.html', form=form, modules=modules) else: if form.testTool.data: if form.starttime.data and form.stoptime.data: modules1 = Modules.query.filter_by( testTool=form.testTool.data).all() modules2 = Modules.query.filter( Modules.testTime >= form.starttime.data, Modules.testTime < form.stoptime.data).all() modules = list(set(modules1).intersection(set(modules2))) return render_template('query.html', form=form, modules=modules) else: modules = Modules.query.filter_by( testTool=form.testTool.data).all() return render_template('query.html', form=form, modules=modules) else: if form.starttime.data and form.stoptime.data: modules = Modules.query.filter( Modules.testTime >= form.starttime.data, Modules.testTime < form.stoptime.data).all() return render_template('query.html', form=form, modules=modules) else: modules = "" return render_template('query.html', form=form, modules=modules) modules = "" return render_template('query.html', form=form, modules=modules)
def query_item(): form = QueryForm() if form.validate_on_submit(): results = db_session.query(Items).filter_by(name=form.name.data).all() return str(results) return render_template('query.html', form=form)
def index(): form = QueryForm() if form.validate_on_submit(): result_url = "/val={}".format(form.number.data) return redirect(result_url) return render_template("index.html", form=form)