2016-04-13 36 views
-2

私はフラスコ/ジンジャーに少し戸惑っています。Flask、Jinja2、HTMLを使用してボタンプレスのページを更新する

私は、テキスト入力フィールド、ボタン、および順序付けられていないリストを持つindex.htmlファイルを持っています。私はまた、入力を取るいくつかの関数を持つmain.pyファイルを持っています。

ボタンを押すと、入力フィールドのテキストを取り込み、そのテキストをPythonファイル(いくつかの処理/ API呼び出しを行います)に渡してから、リストをHTMLファイルに戻します - ページをレンダリングする。これをどのように達成するのですか?

のindex.htmlで:

#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> 

main.pyで:任意の助けをいただければ幸いです

@app.route('/') 
def hello(): 
    """Return a friendly HTTP greeting.""" 
    return 'Hello World!' 

def doesArticleExist(topic): 
    foundTopics = wikipedia.search(topic) 
    if (len(foundTopics) > 0): 
     return foundTopics 
    return ["No topics were found! Your topic is new!"] 

は、ここに私のコードスニペットです!

+1

。私の提案は、良いチュートリアルから始めることです。私も本を書いたMiguel Grinberg(http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world)を推薦することができ、非常に有用なチュートリアルを行っている)。 – Cyb3rFly3r

+1

[Ajax](https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started)はあなたが探しているものです。 – dirn

答えて

1

このプログラムは、Wikipediaのトピック検索を行うための1つの方法を示しています。これは純粋な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) 

ここでは、jQueryとAJAXを含むJavascriptを使用する例を示します。それは再レンダリングせずにページを更新しますが、ユーザーに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) 

参考文献:例のこの種をカバーし、ウェブ上のフラスコのドキュメントがたくさんある

+0

ありがとう!今起こっていることをもっとよく理解していると思います。残念なことに、これらの両方の実装は私にチャンクエラーを与えますが、それは別の質問です。 – Chris

関連する問題