Full text search for flask.

Overview

flask-msearch

https://img.shields.io/badge/pypi-v0.2.9-brightgreen.svg https://img.shields.io/badge/python-2/3-brightgreen.svg https://img.shields.io/badge/license-BSD-blue.svg

Installation

To install flask-msearch:

pip install flask-msearch
# when MSEARCH_BACKEND = "whoosh"
pip install whoosh blinker
# when MSEARCH_BACKEND = "elasticsearch", only for 6.x.x
pip install elasticsearch==6.3.1

Or alternatively, you can download the repository and install manually by doing:

git clone https://github.com/honmaple/flask-msearch
cd flask-msearch
python setup.py install

Quickstart

from flask_msearch import Search
[...]
search = Search()
search.init_app(app)

# models.py
class Post(db.Model):
    __tablename__ = 'post'
    __searchable__ = ['title', 'content']

# views.py
@app.route("/search")
def w_search():
    keyword = request.args.get('keyword')
    results = Post.query.msearch(keyword,fields=['title'],limit=20).filter(...)
    # or
    results = Post.query.filter(...).msearch(keyword,fields=['title'],limit=20).filter(...)
    # elasticsearch
    keyword = "title:book AND content:read"
    # more syntax please visit https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html
    results = Post.query.msearch(keyword,limit=20).filter(...)
    return ''

Config

# when backend is elasticsearch, MSEARCH_INDEX_NAME is unused
# flask-msearch will use table name as elasticsearch index name unless set __msearch_index__
MSEARCH_INDEX_NAME = 'msearch'
# simple,whoosh,elaticsearch, default is simple
MSEARCH_BACKEND = 'whoosh'
# table's primary key if you don't like to use id, or set __msearch_primary_key__ for special model
MSEARCH_PRIMARY_KEY = 'id'
# auto create or update index
MSEARCH_ENABLE = True
# logger level, default is logging.WARNING
MSEARCH_LOGGER = logging.DEBUG
# SQLALCHEMY_TRACK_MODIFICATIONS must be set to True when msearch auto index is enabled
SQLALCHEMY_TRACK_MODIFICATIONS = True
# when backend is elasticsearch
ELASTICSEARCH = {"hosts": ["127.0.0.1:9200"]}

Usage

from flask_msearch import Search
[...]
search = Search()
search.init_app(app)

class Post(db.Model):
    __tablename__ = 'basic_posts'
    __searchable__ = ['title', 'content']

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(49))
    content = db.Column(db.Text)

    def __repr__(self):
        return '<Post:{}>'.format(self.title)

if raise sqlalchemy ValueError,please pass db param to Search

db = SQLalchemy()
search = Search(db=db)

Create_index

search.create_index()
search.create_index(Post)

Update_index

search.update_index()
search.update_index(Post)
# or
search.create_index(update=True)
search.create_index(Post, update=True)

Delete_index

search.delete_index()
search.delete_index(Post)
# or
search.create_index(delete=True)
search.create_index(Post, delete=True)

Custom Analyzer

only for whoosh backend

from jieba.analyse import ChineseAnalyzer
search = Search(analyzer=ChineseAnalyzer())

or use __msearch_analyzer__ for special model

class Post(db.Model):
    __tablename__ = 'post'
    __searchable__ = ['title', 'content', 'tag.name']
    __msearch_analyzer__ = ChineseAnalyzer()

Custom index name

If you want to set special index name for some model.

class Post(db.Model):
    __tablename__ = 'post'
    __searchable__ = ['title', 'content', 'tag.name']
    __msearch_index__ = "post111"

Custom schema

from whoosh.fields import ID

class Post(db.Model):
    __tablename__ = 'post'
    __searchable__ = ['title', 'content', 'tag.name']
    __msearch_schema__ = {'title': ID(stored=True, unique=True), 'content': 'text'}

Note: if you use hybrid_property, default field type is Text unless set special __msearch_schema__

Custom parser

from whoosh.qparser import MultifieldParser

class Post(db.Model):
    __tablename__ = 'post'
    __searchable__ = ['title', 'content']

    def _parser(fieldnames, schema, group, **kwargs):
        return MultifieldParser(fieldnames, schema, group=group, **kwargs)

    __msearch_parser__ = _parser

Note: Only for MSEARCH_BACKEND is whoosh

Custom index signal

flask-msearch uses flask signal to update index by default, if you want to use other asynchronous tools such as celey to update index, please set special MSEARCH_INDEX_SIGNAL

# app.py
app.config["MSEARCH_INDEX_SIGNAL"] = celery_signal
# or use string as variable
app.config["MSEARCH_INDEX_SIGNAL"] = "modulename.tasks.celery_signal"
search = Search(app)

# tasks.py
from flask_msearch.signal import default_signal

@celery.task(bind=True)
def celery_signal_task(self, backend, sender, changes):
    default_signal(backend, sender, changes)
    return str(self.request.id)

def celery_signal(backend, sender, changes):
    return celery_signal_task.delay(backend, sender, changes)

Relate index(Experimental)

for example

class Tag(db.Model):
    __tablename__ = 'tag'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(49))

class Post(db.Model):
    __tablename__ = 'post'
    __searchable__ = ['title', 'content', 'tag.name']

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(49))
    content = db.Column(db.Text)

    # one to one
    tag_id = db.Column(db.Integer, db.ForeignKey('tag.id'))
    tag = db.relationship(
        Tag, backref=db.backref(
            'post', uselist=False), uselist=False)

    def __repr__(self):
        return '<Post:{}>'.format(self.title)

You must add msearch_FUN to Tag model,or the tag.name can’t auto update.

class Tag....
  ......
  def msearch_post_tag(self, delete=False):
      from sqlalchemy import text
      sql = text('select id from post where tag_id=' + str(self.id))
      return {
          'attrs': [{
              'id': str(i[0]),
              'tag.name': self.name
          } for i in db.engine.execute(sql)],
          '_index': Post
      }
Owner
honmaple
风落花语风落天,花落风雨花落田.
honmaple
A Flask app template with integrated SQLAlchemy, authentication, and Bootstrap frontend

Flask-Bootstrap Flask-Bootstrap is an Flask app template for users to clone and customize as desired, as opposed to a Flask extension that you can ins

Eric S. Bullington 204 Dec 26, 2022
A swagger 2.0 spec extractor for flask

flask-swagger A Swagger 2.0 spec extractor for Flask You can now specify base path for yml files: app = Flask(__name__) @app.route("/spec") def spec(

Sling 457 Dec 02, 2022
The Coodesh Python Backend Challenge (2021) written in Flask

Coodesh Back-end Challenge 🏅 2021 ID: 917 The Python Back-end Coodesh Challenge Description This API automatically retrieves users from the RandomUse

Marcus Vinicius Pereira 1 Oct 20, 2021
Track requests to your Flask website with Matomo

Flask-Matomo Flask-Matomo is a library which lets you track the requests of your Flask website using Matomo (Piwik). Installation pip install flask-ma

Lucas Hild 13 Jul 14, 2022
Telegram bot + Flask API ( Make Introduction pages )

Introduction-Page-Maker Setup the api Upload the flask api on your host Setup requirements Make pages file on your host and upload the css and js and

Plugin 9 Feb 11, 2022
Simple flask api. Countdown to next train for each station in the subway system.

Simple flask api. Countdown to next train for each station in the subway system.

Kalyani Subbiah 0 Apr 17, 2022
WebSocket support for Flask

flask-sock WebSocket support for Flask Installation pip install flask-sock Example from flask import Flask, render_template from flask_sock import Soc

Miguel Grinberg 165 Dec 27, 2022
:rocket: Generate a Postman collection from your Flask application

flask2postman A tool that creates a Postman collection from a Flask application. Install $ pip install flask2postman Example Let's say that you have a

Numberly 137 Nov 08, 2022
A flask template with Bootstrap 4, asset bundling+minification with webpack, starter templates, and registration/authentication.

cookiecutter-flask A Flask template for cookiecutter. (Supports Python ≥ 3.6) See this repo for an example project generated from the most recent vers

4.3k Jan 06, 2023
a flask zipkin extension based on py_zipkin.

flask-zipkin a flask zipkin extension based on py_zipkin. Installation pip install flask_zipkin usage you can simply use it as other flask extensions.

39 Jul 03, 2022
Flask Boilerplate - Paper Kit Design | AppSeed

Flask Paper Kit Open-Source Web App coded in Flask Framework - Provided by AppSeed Web App Generator. App Features: SQLite database SQLAlchemy ORM Ses

App Generator 86 Nov 29, 2021
A python package for integrating ripozo with Flask

flask-ripozo This package provides a dispatcher for ripozo so that you can integrate ripozo with Flask. As with all dispatchers it is simply for getti

Vertical Knowledge 14 Dec 03, 2018
Analytics snippets generator extension for the Flask framework.

Flask-Analytics Flask Analytics is an extension for Flask which generates analytics snippets for inclusion in templates. Installation $ pip install Fl

Mihir 80 Nov 30, 2022
This is a small notes web app, with python and flask microframework. Using sqlite3

Python Notes App. This is a small web application maked with flask-python for add notes easily and quickly. Dependencies. You can create a virtual env

Eduard 1 Dec 26, 2021
A simple demo of using aiogram + async sqlalchemy 1.4+

aiogram-and-sqlalchemy-demo A simple demo of using aiogram + async sqlalchemy 1.4+ Used tech: aiogram SQLAlchemy 1.4+ PostgreSQL as database asyncpg a

Aleksandr 68 Dec 31, 2022
This is a API/Website to see the attendance recorded in your college website along with how many days you can take days off OR to attend class!!

Bunker-Website This is a GUI version of the Bunker-API along with some visualization charts to see your attendance progress. Website Link Check out th

Mathana Mathav 11 Dec 27, 2022
docker-compose uWSGI nginx flask

docker-compose uWSGI nginx flask Note that this was tested on CentOS 7 Usage sudo yum install docker

Abdolkarim Saeedi 3 Sep 11, 2022
REST API with mongoDB and Flask.

Flask REST API with mongoDB py 3.10 First, to install all dependencies: python -m pip install -r requirements.txt Second, into the ./src/ folder, cop

Luis Quiñones Requelme 3 Mar 05, 2022
Flask + marshmallow for beautiful APIs

Flask-Marshmallow Flask + marshmallow for beautiful APIs Flask-Marshmallow is a thin integration layer for Flask (a Python web framework) and marshmal

marshmallow-code 770 Jan 05, 2023
A live chat built with python(flask + gevent + apscheduler) + redis

a live chat room built with python(flask / gevent / apscheduler) + redis Basic Architecture Screenshot Install cd /path/to/source python bootstrap.py

Limboy 309 Nov 13, 2022