Flask和Python如何从mysql数据库中获取数据的搜索引擎

Srd*_*tic 4 python mysql flask

我想通过在html输入字段中输入他们的名字来为学生的信息制作某种搜索引擎,但我的代码有些麻烦.我虽然使用带有Python的Flask.这是我的project.py代码:

@app.route('/search', methods=['GET', 'POST'])
def search():
    if request.method == "POST":
        db = MySQLdb.connect(user="root", passwd="", db="cs324", host="127.0.0.1")
        c=db.cursor()
        c.executemany('''select * from student where name = %s''', request.form['search'])
        for r in c.fetchall():
            print r[0],r[1],r[2]
            return redirect(url_for('search'))
    return render_template('search.html')
Run Code Online (Sandbox Code Playgroud)

这是我的search.html代码:

{% extends "hello.html" %}
{% block content %}
<div class="search">
<form action="" method=post>
    <input type=text name=search value="{{ request.form.search}}"></br>
    <div class="actions"><input type=submit value="Search"></div>
</form>
</div>
{% for message in get_flashed_messages() %}
<div class=flash>
    {{ message }}
</div>
{% endfor %}
{% endblock %}
Run Code Online (Sandbox Code Playgroud)

当我点击搜索按钮时没有任何反应,我检查数据库它有一些数据,所以它不是空的,我找不到我在哪里弄错了,请帮忙?

Jan*_*sky 6

确保,行动指向正确的网址

我认为您提交表单时表示错误action.

你的版本正在使用action="",我想,它应该是action="/search"

所以你的模板应该改变如下:

{% extends "hello.html" %}
{% block content %}
<div class="search">
<form action="/search" method=post>
    <input type=text name=search value="{{ request.form.search}}"></br>
    <div class="actions"><input type=submit value="Search"></div>
</form>
</div>
{% for message in get_flashed_messages() %}
<div class=flash>
    {{ message }}
</div>
{% endfor %}
{% endblock %}
Run Code Online (Sandbox Code Playgroud)

不要重定向到您的结果

您现有的代码正在处理POST,但在第一个循环中它最终返回 redirect

@app.route('/search', methods=['GET', 'POST'])
def search():
    if request.method == "POST":
        db = MySQLdb.connect(user="root", passwd="", db="cs324", host="127.0.0.1")
        c=db.cursor()
        c.executemany('''select * from student where name = %s''', request.form['search'])
        for r in c.fetchall():
            print r[0],r[1],r[2]
            return redirect(url_for('search')) # <- Here you jump away from whatever result you create
    return render_template('search.html')
Run Code Online (Sandbox Code Playgroud)

为最终报告渲染模板

您的代码不会在POST分支中显示任何尝试呈现您在数据库中找到的内容.

而不是print r[0], r[1]...你应该打电话render_template()

像这样的东西

@app.route('/search', methods=['GET', 'POST'])
def search():
    if request.method == "POST":
        db = MySQLdb.connect(user="root", passwd="", db="cs324", host="127.0.0.1")
        c=db.cursor()
        c.executemany('''select * from student where name = %s''', request.form['search'])
        return render_template("results.html", records=c.fetchall())
    return render_template('search.html')
Run Code Online (Sandbox Code Playgroud)