便于使用带烧瓶的ftscoursor的扩展
Flask-FTSCursor的Python项目详细描述
烧瓶光标
便于使用FTSCursor和烧瓶的扩展名
安装
pip3 install flask-ftscursor
任务声明
这个包裹的灵感来自米格尔·格林伯格的 Flask Mega-Tutorial, 特别是Chapter 16: Full-Text Search。 更具体地说,就是这句话:
Using the searching capabilities of one of the relational databases could also be a good choice, but given the fact that SQLAlchemy does not support this functionality, I would have to handle the searching with raw SQL statements, or else find a package that provides high-level access to text searches while being able to coexist with SQLAlchemy.
flask ftscoursor就是这样一个包。它提供对sqlite3的高级访问 全文在能够与SQLAlchemy和谐共存的同时进行探索。
教程
这将是FTS
对象的最小演示。例如
使用flask ftscoursor的应用程序,请参见ucsd-bisb-unofficial。
首先导入我们需要的内容
importsqlite3fromflaskimportFlaskfromflask_ftscursorimportFTS
创建一个FTS
对象
fts=FTS()
定义应用程序工厂函数
defcreate_app():app=Flask(__name__)app.config['FTS_DATABASE']='fts.db'app.config['FTS_SOURCE_DATABASE']='app.db'fts.init_app(app)returnapp
创建应用程序
app=create_app()
将一些数据放入源数据库
conn=sqlite3.connect(app.config['FTS_SOURCE_DATABASE'])c=conn.cursor()c.executescript(''' CREATE TABLE my_table(id INTEGER, body TEXT); INSERT INTO my_table(id, body) VALUES (1, 'this is a test'), (2, 'a second test'); ''')conn.commit()
请尝试搜索(这将失败,因为尚未索引任何内容)
withapp.app_context()app.fts.search(table='my_table',query='this test',page=1,per_page=2)
为源数据库中的某些行编制索引(将它们添加到fts数据库中)
withapp.app_context()app.fts.index(table='my_table',id=1,searchable=('body',))app.fts.index(table='my_table',id=2,searchable=('body',))
执行全文搜索
withapp.app_context()app.fts.search(table='my_table',query='this test',page=1,per_page=2)
{'hits':{'total':1,'hits':({'_id':1},)}}
尝试其他查询
withapp.app_context()app.fts.search(table='my_table',query='second',page=1,per_page=2)
{'hits':{'total':1,'hits':({'_id':2},)}}
删除fts表,将其内容从fts数据库中删除
withapp.app_context()app.fts.drop(table='my_table')
配置
flask ftscoursor依赖于应用程序配置中的两项:FTS_DATABASE
以及FTS_SOURCE_DATABASE
。
FTS_SOURCE_DATABASE
的值应该是应用程序主文件的文件路径
sqlite3数据库,或包含
索引。FTS_DATABSE
的值应该是数据库所在的文件路径
将保留包含FTS表的内容。
抽象
flask ftscoursor提供名为add_to_index()
的函数,
remove_from_index()
,和query_index()
,它们可以用来代替
类似于miguel grinberg的flask mega教程中给出的函数,
Chapter 16: Full-Text Search,
在标题为“全文搜索摘要”的部分下。例如
使用这些功能的应用程序,请参见ucsd-bisb-unofficial。