Flask应用搜索栏 [英] Flask app search bar

查看:160
本文介绍了Flask应用搜索栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Flask实现搜索栏,但是当我输入url/search时,出现405错误,不允许使用方法.

I am trying to implement a search bar using Flask, but when I enter the url/search, I got a 405 error, Method Not Allowed.

这是我的代码的摘要.任何帮助将不胜感激!

Here is a snippet of my code. Any help would be appreciated!

forms.py

from wtforms import StringField
from wtforms.validators import DataRequired

class SearchForm(Form):
  search = StringField('search', [DataRequired()])
  submit = SubmitField('Search',
                       render_kw={'class': 'btn btn-success btn-block'})

views.py

from flask_login import login_required
from forms import SearchForm
from models import User

@app.route('/')
def index():
  if current_user.is_authenticated:
    return redirect(url_for('profile'))
  return render_template('index.html')

@app.route('/profile', methods=['GET', 'POST'])
@login_required
def profile():
  # some code to display user profile page

@app.route('/search', methods=['POST'])
@login_required
def search():
  form = SearchForm()
  if not form.validate_on_submit():
    return redirect(url_for('index'))
  return redirect((url_for('search_results', query=form.search.data)))

@app.route('/search_results/<query>')
@login_required
def search_results(query):
  results = User.query.whoosh_search(query).all()
  return render_template('search_results.html', query=query, results=results)

models.py

from flask_sqlalchemy import SQLAlchemy
from flask_whooshalchemy import whoosh_index
from app import app

db = SQLAlchemy()

class User(db.model):
  __searchable__ = ['name']
  id = db.Column(db.Integer, primary_key=True)
  name = db.Column(db.String(64))

whoosh_index(app, User)

search.html

{% extends 'layouts/base.html' %}
{% set page_title = 'Search' %}
{% block body %}
    <div>
        {{ render_form(url_for('search'), form) }} # note: render_form is some marco from another .html file
    </div>
{% endblock %}

推荐答案

因为使用GET方法手动加载页面时,但是search控制器只允许使用POST.您需要更改

Because when you load page manually you using GET method, but only POST is allowed for search controller. You need to change

@app.route('/search', methods=['POST'])

@app.route('/search', methods=['GET', 'POST'])

更新

因此,基本上,最好更改您的search控制器.因为它没有使用 search.html 并且工作错误.

So basically it's better to change your search controller. Because it's not using search.html and works wrong.

@app.route('/search', methods=['GET', 'POST'])
@login_required
def search():
    form = SearchForm()
    if request.method == 'POST' and form.validate_on_submit():
        return redirect((url_for('search_results', query=form.search.data)))  # or what you want
    return render_template('search.html', form=form)

PEP-8

这篇关于Flask应用搜索栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆