使用Flask,Jinja2,HTML在buttonpress上更新页面

时间:2016-04-13 02:59:27

标签: python html flask jinja2

我是Flask / Jinja的新手,有点困惑。

我有一个index.html文件,其中包含文本输入字段,按钮和无序列表。我还有一个main.py文件,其中包含一些输入的函数。

当我按下按钮时我想在输入字段中输入文本,将文本传递给我的python文件(将执行一些处理/ API调用),然后将列表传递回HTML文件,而不是渲染页面。我该如何做到这一点?

以下是我的代码段:

在index.html中:

OnCreate

在main.py中:

#This is where I want to get the input from 
<input type="text" style="text-align:center;">

#This is the button that should generate the list when I press it
<li><a href="#content" class="button big special">Search</a></li>

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

该程序演示了一种进行维基百科主题搜索的方法。请注意,这依赖于纯HTML。因此,每次用户单击按钮时,它都会重新呈现页面。

from flask import Flask, render_template_string
from flask_wtf import Form
from wtforms import StringField
from wtforms.validators import DataRequired
import wikipedia

app = Flask(__name__)
app.secret_key = 'secret'

class WikiForm(Form):
    key = StringField('Search Term', validators=[DataRequired()])

index_html='''
<html><body>
<form method="POST">
    {{ form.csrf_token }}
    {{ form.key.label }}: {{ form.key() }}
    <input type="submit" value="Go"/>
</form>
<hr />
{% if topics %}<ul>
    {% for topic in topics %}<li>{{ topic }}</li>{% endfor %}
</ul>{% endif %}
</body></html>
'''

@app.route('/', methods=('GET', 'POST'))
def index():
    form = WikiForm()
    if form.validate_on_submit():
        topics = wikipedia.search(form.key.data) or ['No topic found']
        return render_template_string(index_html, topics=topics, form=form)
    return render_template_string(index_html, topics=None, form=form)

app.run(debug=True)

这是一个使用Javascript的示例,包括jQuery和AJAX。它在不重新渲染的情况下更新页面,但它确实要求用户启用Javascript。

from flask import Flask, render_template_string, request, jsonify
import wikipedia

app = Flask(__name__)

index_html='''
<html><body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script type=text/javascript>
  function submit() {
    $.getJSON({{ request.script_root|tojson|safe }} + '/topics',
      { key: $('#key').val() },
      function(data) {
        var ul = $('#result');
        ul.empty();
        $(data.topics).each(function(index, item) {
          ul.append($('<li>',{text:item}));});});}
</script>
Search Term: <input id="key" name="key"/>
<input id="submit" type="button" value="Go" onclick="submit();" />
<hr /><ul id="result"></ul>
</body></html>'''

@app.route('/')
def index():
    return render_template_string(index_html)

@app.route('/topics')
def topics():
    key = request.args.get('key')
    topics = wikipedia.search(key) or ['No topic found']
    return jsonify(topics=topics)

app.run(debug=True)

参考文献: