我使用flask-msearch 编写了搜索功能来搜索产品名称和类型,但搜索结果不会显示。当我在搜索栏中输入关键字时,我被定向到 searchResult.html 页面,但没有显示任何结果。所以我认为调用数据库有问题,或者没有创建数据库,但我不确定是什么问题。或者,如果这不起作用,是否还有其他方法可以执行搜索功能。
_ init _.py
from flask import render_template, request, redirect, url_for
from Forms import AddProduct
import shelve, Products
from Models import Products
from app import app, search, db
@app.route('/')
def home():
return render_template('home.html')
@app.route('/searchResults')
def result():
searchword = request.args.get('q')
products = Products.query.msearch(searchword, fields=['name', 'type'], limit=3)
return render_template('searchResults.html', products=products)
app.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_msearch import Search
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///shop.db'
db = SQLAlchemy(app)
search = Search()
search.init_app(app)
模型.py
from app import db
from datetime import datetime
class Products(db.Model):
__tablename__ = 'product'
__searchable__ = ['name', 'type']
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)
price = db.Column(db.Numeric(10,2), nullable=False)
type = db.Column(db.Text, nullable=False)
pub_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
def __repr__(self):
return '<Products %r>' % self.name
db.create_all()
_navbar.html
<form class="form-inline ml-auto" action="{{url_for('result')}}">
<div class="md-form my-0">
<input class="form-control" type="search" placeholder="Search" aria-label="Search" name="q">
</div>
<button class="btn btn-outline-white btn-md my-0 ml-sm-2" type="submit">Search</button>
</form>
searchResults.html
{% extends "base.html" %}
{% block title %}Search Results{% endblock %}
{% block content %}
<h1 class="display-4">Search Results</h1>
{% for product in products %}
{{product.name}}
{% endfor %}
{% endblock %}