Flask

Implementing Basic Search Functionality in Flask


Introduction

Implementing search functionality in a web application is crucial for allowing users to find specific content efficiently. In this guide, we'll explore how to implement basic search functionality in a Flask application, a Python web framework. You'll learn how to set up a search feature, collect user input, query a database, and display search results. By following this guide, you'll be able to add search capabilities to your web application and improve user experience.

Step 1: Setting Up Your Flask Application

Start by setting up your Flask application and creating a directory structure. Here's a sample structure:

basic-search/
    app.py
    templates/
        index.html
        search_results.html
    

Step 2: Creating the Search Application

Create a Flask application for the search feature. Here's an example of the Python code:

# app.py
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///search_data.db'
db = SQLAlchemy(app)
class Product(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
@app.route('/')
def index():
    return render_template('index.html')
@app.route('/search', methods=['POST'])
def search():
    keyword = request.form.get('search_keyword')
    if keyword:
        results = Product.query.filter(Product.name.contains(keyword)).all()
        return render_template('search_results.html', results=results, keyword=keyword)
    return redirect('/')
if __name__ == '__main__':
    app.run(debug=True)
        

Step 3: Creating HTML Templates

Create HTML templates for the search form and displaying search results. Here's an example:

<!-- templates/index.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Basic Search</title>
</head>
<body>
    <header>
        <h1>Basic Search</h1>
    </header>
    <section>
        <h2>Search for a Product</h2>
        <form method=`POST` action=`/search`>
            <input type=`text` name=`search_keyword` placeholder=`Enter a keyword`>
            <button type=`submit`>Search</button>
        </form>
    </section>
</body>
</html>
        
<!-- templates/search_results.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Search Results</title>
</head>
<body>
    <header>
        <h1>Search Results for `{{ keyword }}`</h1>
    </header>
    <section>
        <h2>Results</h2>
        <ul>
            {% for result in results %}
                <li>{{ result.name }}</li>
            {% endfor %}
        </ul>
    </section>
</body>
</html>
        

Step 4: Running Your Search Application

Run your Flask search application using the following command:

python app.py
        

Access your search page in a web browser and try searching for products using the keyword you entered.

Conclusion

Implementing basic search functionality in a Flask application is a valuable addition to improve user interaction. By following the steps in this guide, you can set up a search feature, collect user input, query a database, and display search results. This project serves as a starting point for more advanced search capabilities, including filtering, sorting, and additional features based on user requirements.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.