Autocomplete Input Suggestion using Python and Flask

Introduction

Autocomplete is a feature in which an application predicts the rest of a word a user is typing. In graphical user interfaces, users can typically press the tab key to accept a suggestion or the down arrow key to accept one of several.

Autocomplete speeds up human-computer interactions when it correctly predicts the word a user intends to enter after only a few characters have been typed into a text input field. The autocomplete is a normal text input enhanced by a panel of suggested options.

In this example I am going to show you how to do auto complete input suggestion for the given user input. I am using to show input suggestion on JavaScript’s key up event. The minimum number of characters user should input is two before he/she can see the autocomplete suggestion based on his/her input.

I am going to use sample static JSON data from a file, ideally the results for the given search string should come from persistence storage or external services. So here I am going to see how to load static JSON data file from a location using flask framework.

I will only return the matched lines for a given string from the sample JSON data.

Prerequisites

Python 3.8.3 – 3.9.5, Flask 1.1.2, jQuery 3.5.1 – 3.6.0, jQuery UI 1.12.1

Project Directory

Create a project root directory called python-flask-autocomplete-input-suggestion as per your chosen location.

I may not mention the project’s root directory name in the subsequent sections but I will assume that I am creating files with respect to the project’s root directory.

Flask Configuration

You need a flask instance in order to run web application using Flask framework.

Create a file called app.py with the below code.

from flask import Flask

app = Flask(__name__)
app.secret_key = "secret key"

Template View File

The default location in flask based applications of the template or view files is templates folder. This is autocomplete.html page kept under templates directory.

I have an input field where user will type a string and if this string matches with the JSON data then it will return the results.

I am using AJAX technique with jQuery to call the REST API and display the results.

<!doctype html>
<html>
<head>
	<title>Autocomplete input suggestion using Python and Flask</title>

	<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
	<!--<script src="https://code.jquery.com/jquery-3.5.1.min.js" crossorigin="anonymous"></script>-->
	<script src="https://code.jquery.com/jquery-3.6.0.min.js" crossorigin="anonymous"></script>
	<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" crossorigin="anonymous"></script>
	<script>
		$(function() {
			$("#searchBox").autocomplete({
				source : function(request, response) {
					$.ajax({
						type: "POST",
						url : "http://localhost:5000/search",
						dataType : "json",
						cache: false,
						data : {
							q : request.term
						},
						success : function(data) {
							//alert(data);
							//console.log(data);
							response(data);
						},
						error: function(jqXHR, textStatus, errorThrown) {
							console.log(textStatus + " " + errorThrown);
						}
					});
				},
				minLength : 2
			});
		});
	</script>
</head>
<body>
	<div style="width: 600px; margin: auto;">
		<h2>Autocomplete input suggestion using Python and Flask</h2>
		<p style="width: 560px; margin: auto;">
			<label>Search Here</label>&nbsp;&nbsp;<input type="text" name="search" id="searchBox"/>
		</p>
	</div>
</body>

Autocomplete – REST API

Now to display the view file to end user I am using render_template() function from flask framework.

I have used REST endpoint /search when user type in the input field to return the corresponding results on key up event.

Notice how I am loading the JSON data file using flask. Also notice how I am filtering the values from the JSON data for the given input value.

import os, json
from app import app
from flask import Flask, jsonify, request, redirect, render_template
	
@app.route('/')
def upload_form():
	return render_template('autocomplete.html')

@app.route('/search', methods=['POST'])
def search():
	term = request.form['q']
	print ('term: ', term)
	
	SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
	json_url = os.path.join(SITE_ROOT, "data", "results.json")
	json_data = json.loads(open(json_url).read())
	#print (json_data)
	#print (json_data[0])
	
	filtered_dict = [v for v in json_data if term in v]	
	#print(filtered_dict)
	
	resp = jsonify(filtered_dict)
	resp.status_code = 200
	return resp

if __name__ == "__main__":
    app.run()

Data

The sample data are kept into results.json file under data folder.

[
	"Lorem Ipsum is simply dummy text of the printing and typesetting",
	"Lorem Ipsum has been the industry's standard dummy",
	"nd scrambled it to make a type specimen book. It",
	"typesetting, remaining essentially unchanged. It ",
	"sum passages, and more recently with desktop publi",
	"Contrary to popular belief, Lorem Ipsum is not sim",
	"professor at Hampden-Sydney College in Virginia, looked up one",
	"passage, and going through the cites of the word in",
	"comes from sections 1.10.32 and 1.10.33 of \"de Finibus Bonorum",
	"BC. This book is a treatise on the theory of ethics, very popu",
	"here are many variations of passages of Lorem Ipsum availa",
	"believable. If you are going to use a passage of Lorem Ips",
	"middle of text. All the Lorem Ipsum generators on the Intern",
	"tend to repeat predefined chunks as necessary, making this the",
	"first true generator on the Internet. It uses a dictionary of over 20",
	"he standard chunk of Lorem Ipsum used since the 1500s i",
	"1.10.33 from \"de Finibus Bonorum et Malorum\" by Cicero are als",
	"reproduced in their exact original form, accompanied by English",
	"eadable content of a page when looking at its layout. The point"
]

Deploy the Application

Now navigate to the project’s root directory using command line tool and execute the command python main.py, your server will be started on default port 5000.

If you want to change the port then you can change the line app.run() to app.run(port=5001), where 5001 is the new port.

Test the Application

When you hit the URL http://localhost:5000 in the browser to get the below page. So when you type something, for example, he then you will get these many of results for the given input he.

That’s all about autocomplete input suggestion using Python and Flask.

Source Code

Download

1 thought on “Autocomplete Input Suggestion using Python and Flask

Leave a Reply

Your email address will not be published. Required fields are marked *