【问题标题】:Flask search based on a keyword基于关键字的烧瓶搜索
【发布时间】:2021-06-15 13:35:39
【问题描述】:

我是 flask 的新手,我正在做一个博客项目,我正在尝试添加一个搜索框,访问者或用户可以在其中输入关键字,并且将显示与该关键字相关的帖子。 我尝试了 whoosh 索引,但由于我使用的是 python3.9,所以它不起作用所以我尝试了这个:

@app.route('/search', methods =["GET", "POST"])
def search():
    search_keyword = request.form.get("search_box")
    results =  db.engine.execute("SELECT * FROM post "
                           "WHERE title = search_box ")
    return render_template('home.html', results=results)

试图获取输入字段的值

<form class="form-inline my-2 my-lg-0">
                  <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" method="GET" action="search"  name="search_box">
                  <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
                </form>

没有错误,但它不起作用,有人可以帮我吗?谢谢

【问题讨论】:

  • 您在 db 中是否有任何标题等于 search_box 的条目?
  • 我正在尝试获取search_box输入字段的值并根据它进行搜索请求,search_box是输入字段的名称,我不知道如何获取输入的值在sql请求中
  • 您使用的是哪种类型的数据库 sqlite 或 mysql。如果您使用的是 mysql,那么我可以给您搜索命令,但我认为它在 sqlite 中不起作用
  • 我正在使用 sqlite 数据库
  • 对不起,该命令不适用于 sqlite,但我有另一个正在使用 python 3 的库,请参阅此处github.com/honmaple/flask-msearch,whoosh 不支持 python 3

标签: python python-3.x flask flask-sqlalchemy


【解决方案1】:

最终,我最终使用了 flask_msearch

我安装了它:pip install flask-msearch

init.py

from flask_msearch import Search
...
search = Search(app)
search.init_app(app)
search.create_index(update=True)
MSEARCH_INDEX_NAME =  os.path.join(app.root_path,'msearch')
MSEARCH_PRIMARY_KEY = 'id'
MSEARCH_ENABLE = True

models.py 中:

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

routes.py

@app.route('/search/')
def search():
    keyword = request.args.get('query')
    posts = Post.query.msearch(keyword,fields=['title', 'content'])
    return render_template("home.html",title='Searching..' + keyword, posts=posts)

在我的模板中:

<form method="GET" action="/search/">
                      <input type="text" name="query" class="form-control" placeholder="Search..." />
                      <button type="submit" class="btn btn-light-primary font-weight-bold">
                              
                      </button>
                    </div>
                  </form>
                  </div>

感谢所有试图帮助我的人

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 2013-07-16
    相关资源
    最近更新 更多