【问题标题】:How to Make a search bar in python flask using mongodb如何使用 mongodb 在 python 烧瓶中创建搜索栏
【发布时间】:2020-09-28 23:09:19
【问题描述】:

我尝试为我的大学项目制作一个搜索栏,但我不知道我哪里出错了它在我的控制台中给我一个错误 405 我不确定但我认为我在 python 烧瓶中的搜索命令我想搜索那些产品错了,如果这个问题困扰你,我很抱歉,我是 python flask 和 mongo db 的新手

jquery

$(document).ready(function(){
                $("#livebox").on("input",function(e){
                    textinLivebox = $("#livebox").val();
                    console.log(textinLivebox)
                    $.ajax({
                        method:"post",
                        url:"/livesearch",
                        data:{text:textinLivebox},
                        success: function(res){
                            console.log(res)
                        }
                    })
                });
            })

蟒蛇烧瓶

@app.route("/livesearch")
def livesearch():
    searchbox = request.form.get("text")
    data = mongo.db.Product.find({"title"})
    result = Product.objects.all(data)
    return jsonify(result)

我的数据库

class Product(db.Document):
    product_id  = db.IntField( unique=True)
    title       = db.StringField(max_length = 50)
    img_file    = db.StringField(nullable=False, default='static/img/dettol.jpg')
    price       = db.StringField(max_length = 50 )
    description = db.StringField( max_length = 50)

【问题讨论】:

标签: python jquery mongodb flask pymongo


【解决方案1】:

请按照以下步骤操作:

  1. 在文本上创建索引(在 Mongo shell 中):

    db.collection.createIndex( { name: "text", description: "text" } )
    
  2. 使用$text 运算符进行搜索(在 Python 代码中):

    db.collection.find( { '$text': { '$search':  searchbox} } )
    

    你可以阅读更多关于这个here的信息。

对于405错误,可以在路由中添加POST方法:

@app.route("/livesearch", methods=["POST"])

【讨论】:

    猜你喜欢
    • 2013-02-24
    • 2020-05-18
    • 1970-01-01
    • 2018-06-09
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    相关资源
    最近更新 更多