指定最大长度的验证器时出现 Flask-WTForms 错误

Flask-WTForms error when specifying validator of maximum length

我在让搜索栏的最大长度验证器与我的 Flask 应用程序一起工作时遇到了一些问题。我目前收到一个错误:TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.

这是我的forms.py:

    class SearchForm(FlaskForm):
    query = StringField('query', validators=[DataRequired(), Length(max=20)])
    submit = SubmitField('')

和我在 routes.py 中的路线:

@app.route('/gsearch', methods=['POST'])
def gsearch():
    conn = sqlite3.connect("retro_games.db")
    cur = conn.cursor()
    form = SearchForm()
    if form.validate_on_submit():
        cur.execute("SELECT * FROM Games WHERE name LIKE ?",
                    ("%"+form.query.data+"%",))
        game = cur.fetchall()
        return render_template('gsearch.html', title='Search', game=game)

感谢您的帮助:)

当表单无效时你应该处理,

def gsearch():
    conn = sqlite3.connect("retro_games.db")
    cur = conn.cursor()
    form = SearchForm()
    if form.validate_on_submit():
        cur.execute("SELECT * FROM Games WHERE name LIKE ?",
                    ("%"+form.query.data+"%",))
        game = cur.fetchall()
        return render_template('gsearch.html', title='Search', game=game)
    # if form is not vaild, handle the logic here
    return {"error": "game not found"}

查看更多信息FLASK-WTF Validating Forms