Everything you need as a full stack developer

Flask Search with basic search functionality

- Posted in Flask by

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!

Fullstackist aims to provide immersive and explanatory content for full stack developers Fullstackist aims to provide immersive and explanatory content for full stack developers
Backend Developer 103 Being a Fullstack Developer 107 CSS 109 Devops and Cloud 70 Flask 108 Frontend Developer 357 Fullstack Testing 99 HTML 171 Intermediate Developer 105 JavaScript 206 Junior Developer 124 Laravel 221 React 110 Senior Lead Developer 124 VCS Version Control Systems 99 Vue.js 108

Recent Posts

Web development learning resources and communities for beginners...

TL;DR As a beginner in web development, navigating the vast expanse of online resources can be daunting but with the right resources and communities by your side, you'll be well-equipped to tackle any challenge that comes your way. Unlocking the World of Web Development: Essential Learning Resources and Communities for Beginners As a beginner in web development, navigating the vast expanse of online resources can be daunting. With so many tutorials, courses, and communities vying for attention, it's easy to get lost in the sea of information. But fear not! In this article, we'll guide you through the most valuable learning resources and communities that will help you kickstart your web development journey.

Read more

Understanding component-based architecture for UI development...

Component-based architecture breaks down complex user interfaces into smaller, reusable components, improving modularity, reusability, maintenance, and collaboration in UI development. It allows developers to build, maintain, and update large-scale applications more efficiently by creating independent units that can be used across multiple pages or even applications.

Read more

What is a Single Page Application (SPA) vs a multi-page site?...

Single Page Applications (SPAs) load a single HTML file initially, handling navigation and interactions dynamically with JavaScript, while Multi-Page Sites (MPS) load multiple pages in sequence from the server. SPAs are often preferred for complex applications requiring dynamic updates and real-time data exchange, but MPS may be suitable for simple websites with minimal user interactions.

Read more