Added autocomplete as part of a user session. Hooray, no more autocomplete based on other users!!

geo
Jocavdh 7 years ago
parent 23ad268c0b
commit b1371fdb3e

@ -40,4 +40,3 @@ app.config.from_object(__name__)
from app import views
flask_whooshalchemyplus.init_app(app) # initialize

@ -160,10 +160,10 @@ $(document).ready(function()
// Autocomplete for search - Contact Joca in case of trouble
$('#search').on("input", function() {
var query = this.value;
$.ajax({
url: "/autocomplete_suggestions",
data: $('form').serialize(),
@ -173,83 +173,21 @@ $('#search').on("input", function() {
}
});
function getData() {
var deferredData = new jQuery.Deferred();
$.ajax({
type: "GET",
url: "/autocomplete_suggestions",
dataType: "json",
success: function(data) {
deferredData.resolve(data);
}
});
return deferredData; // contains the passed data
};
var dataDeferred = getData();
$.when(dataDeferred).done( function( data ) {
var suggestion_list = data;
console.log(suggestion_list);
$().ready(function() {
// search only, if the regexp matches
var suggestions = data;
// Defines for the example the match to take which is any word (with Umlauts!!).
function _leftMatch(string, area) {
//return string.substring(0, area.selectionStart).match(/[\wäöüÄÖÜß]+$/)
//console.log(string.substring(string.lastIndexOf(" ")+1).match(/[\wäöüÄÖÜß]+$/))
return string.substring(string.lastIndexOf(" ")+1).match(/[\wäöüÄÖÜß]+$/)
}
function _setCursorPosition(area, pos) {
if (area.setSelectionRange) {
area.setSelectionRange(pos, pos);
} else if (area.createTextRange) {
var range = area.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
$("#search").autocomplete({
position: { my : "right top", at: "right bottom" },
source: function(request, response) {
var str = _leftMatch(request.term, $("#search")[0]);
str = (str != null) ? str[0] : "";
console.log(str);
response($.ui.autocomplete.filter(
suggestions, str));
},
minLength: 1, // does have no effect, regexpression is used instead
focus: function() {
// prevent value inserted on focus
return false;
},
// Insert the match inside the ui element at the current position by replacing the matching substring
select: function(event, ui) {
//alert("completing "+ui.item.value);},
var m = _leftMatch(this.value, this)[0];
var beg = this.value.substring(0, this.selectionStart - m.length);
this.value = beg + ui.item.value + this.value.substring(this.selectionStart, this.value.length);
var pos = beg.length + ui.item.value.length;
_setCursorPosition(this, pos);
return false;
},
search:function(event, ui) {
var m = _leftMatch(this.value, this);
return (m != null )
}
// Start autocomplete
var availableTags = data;
console.log(availableTags);
$( "#search" ).autocomplete({
source: availableTags
});
})
// End of autocomplete
}
});
});

@ -15,6 +15,7 @@
<![endif]-->
<link rel="stylesheet" href="/static/css/style.css">
<link rel="stylesheet" href="/static/js/jquery-ui-1.12.1.custom/jquery-ui.css">
<link rel="stylesheet" href="/static/js/jquery-ui-1.12.1.custom/jquery-ui.js">
{% block css %} {% endblock%}
</head>
<body>

@ -3,6 +3,7 @@
{% block main %}
<div class="container">
{% from "_formhelpers.html" import render_field %}
<form method="POST">
<div>{{ form.select(style="width: 100px; margin: 10px; float: left; font-size: 20px") }}</div>
<div class="search">

@ -6,7 +6,7 @@ This file creates your application.
"""
from app import app, db, socketio, DOMAIN
from flask import Flask, Response, render_template, request, redirect, url_for, flash, send_from_directory, jsonify, abort
from flask import Flask, Response, session, render_template, request, redirect, url_for, flash, send_from_directory, jsonify, abort
import json
from sqlalchemy.sql.expression import func, select
from app.forms import UploadForm, EditForm, SearchForm, ChatForm, StackForm, AddtoStackForm
@ -303,6 +303,8 @@ def show_stack_by_id(id, is_tab=False):
@app.route('/books', methods= ['POST','GET'])
def show_books():
autocomplete.load() #Train markov model once, for autocomplete in search
books = db.session.query(Book).all()
search = SearchForm(request.form)
if request.method == 'POST':
@ -338,11 +340,11 @@ def search_results(searchtype, query):
## Search - autocomplete
autocomplete_suggestions = []
autocomplete.load() #Train markov model once, for autocomplete in search
@app.route('/autocomplete_suggestions', methods=['GET', 'POST'])
def test1():
if request.method == 'POST':
autocomplete.load()
query = request.form['search']
query_tokenized = query.lower().split()
print(query_tokenized)
@ -354,9 +356,13 @@ def test1():
for suggestion, score in autocomplete_output:
autocomplete_suggestions.append(suggestion)
print(autocomplete_suggestions)
session['autocomplete_suggestions'] = str(autocomplete_suggestions)
print(session['autocomplete_suggestions'])
return Response(json.dumps(session['autocomplete_suggestions']), mimetype='application/json')
return Response(json.dumps(autocomplete_suggestions), mimetype='application/json')
## STACKS!
@app.route('/add_to_stack/<int:id>', methods=['GET', 'POST'])
def add_to_stack(id):

Loading…
Cancel
Save