TL;DR Flask is used to implement a basic search functionality with SQLite database, which stores search queries and results. The code sets up routes for form submissions and retrieving results in JSON format, and creates templates for rendering results. This is just the starting point for further customization and extension.
Building a Basic Search Functionality in Flask: A Step-by-Step Guide
As developers, we've all been there - trying to build a search functionality that's both efficient and user-friendly. In this article, we'll take a closer look at how to implement a basic search feature using the popular Python web framework, Flask.
What is Flask?
Flask is a micro web framework written in Python. It's known for its simplicity, flexibility, and ease of use, making it an ideal choice for building web applications quickly. With Flask, you can focus on writing your application logic without getting bogged down by complex frameworks or libraries.
Setting Up the Project Structure
Before we dive into the code, let's set up our project structure. We'll create a new directory called flask-search and add the following files:
app.py: This will be our main Flask application file.templates/: A folder for storing our HTML templates.static/: A folder for storing static assets like CSS, JavaScript, and images.
Installing Required Packages
To implement search functionality, we'll need the following packages:
pip install flask flask_sqlalchemy
We'll also need a database to store our data. For this example, let's use SQLite.
Database Setup
Create a new file called database.py and add the following code:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///search.db"
db = SQLAlchemy(app)
class Search(db.Model):
id = db.Column(db.Integer, primary_key=True)
query = db.Column(db.String(100), nullable=False)
results = db.relationship("Result", backref="search", lazy=True)
class Result(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
link = db.Column(db.String(200), nullable=False)
This code sets up a SQLite database with two tables: Search and Result.
Implementing Search Functionality
Now that we have our database set up, let's implement the search functionality. Add the following code to your app.py file:
from flask import Flask, render_template, request, jsonify
from database import db
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///search.db"
db.init_app(app)
@app.route("/", methods=["GET", "POST"])
def index():
if request.method == "POST":
query = request.form.get("query")
search = Search.query.filter_by(query=query).first()
if not search:
# Create a new search record
search = Search(query=query)
db.session.add(search)
db.session.commit()
# Retrieve results from the database
results = Result.query.filter(Result.search_id == search.id).all()
return render_template("results.html", query=query, results=results)
return render_template("index.html")
@app.route("/search.json", methods=["GET"])
def search():
query = request.args.get("query")
results = Result.query.filter_by(search__query=query).limit(10).all()
data = []
for result in results:
data.append({"title": result.title, "link": result.link})
return jsonify(data)
This code sets up two routes: / and /search.json. The / route handles form submissions from the index.html template, while the /search.json route returns JSON data to our JavaScript client.
Creating Templates
Create a new file called index.html in your templates folder:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Search</title>
</head>
<body>
<form action="" method="post">
<input type="text" id="query" name="query" placeholder="Enter your search query">
<button type="submit">Search</button>
</form>
{% if results %}
<h2>Results for "{{ query }}"</h2>
<ul>
{% for result in results %}
<li>
<a href="{{ result.link }}">{{ result.title }}</a>
</li>
{% endfor %}
</ul>
{% endif %}
</body>
</html>
And create a new file called results.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Results</title>
</head>
<body>
<h2>Results for "{{ query }}"</h2>
<ul>
{% for result in results %}
<li>
<a href="{{ result.link }}">{{ result.title }}</a>
</li>
{% endfor %}
</ul>
{{ super() }}
</body>
</html>
Conclusion
In this article, we've implemented a basic search functionality using Flask. We've set up a database with two tables: Search and Result. We've created routes to handle form submissions and retrieve results from the database. Finally, we've created templates for rendering the results.
This is just a starting point, and you can customize and extend this code as needed for your application. Remember to commit your changes regularly and run migrations to keep your database up-to-date!
What's Next?
In our next article, we'll explore more advanced search functionality, such as:
- Implementing faceted searching
- Using Elasticsearch or other full-text search engines
- Optimizing performance for large datasets
Stay tuned!
