我要做的是在单击Submit按钮时触发函数get_lyrics()。该操作可能成功运行,然后触发另一个操作,或者它可能无法显示“已到达的API调用。稍后再试”。
但是,一旦我加载页面,文本'API调用就到达了,稍后再试。‘已经存在,而只有在触发的函数失败时才会出现。
这是我的app.py:
import os
import json
from flask import Flask, render_template, request, session
from src.get_lyrics import get_lyrics
app = Flask(__name__)
@app.route('/')
def web_page():
return render_template('simple.html')
@app.route('/artist', methods=['POST'])
def insert_text():
if request.method=='POST':
artist_name = request.form.get("artist")
number_songs = request.form.get("number")
try:
titles, lyrics, no_of_songs = get_lyrics(artist = artist_name,
max_no_songs = number_songs,
path_to_txt="C:/Users/test_new.txt")
train = True
except:
train = False
titles= None
no_of_songs = None
return render_template('simple.html', titles=titles, no_songs=no_of_songs, train=train)这是html位:
<!DOCTYPE html>
<link href="static/simple.css" rel="stylesheet" type="text/css"</link>
<html>
<div class="image"></div>
<body>
<div class="gray-block-1">
<div class="block-1">
<h2>Instructions</h2>
</div>
<div class="block-2">
<form action = "./artist" method = "POST">
<input type="text" placeholder="Artist name" name="artist" />
<input type="text" placeholder="Number of songs" name="number" />
<div class="submit-button">
<button type = "submit"> Submit</button>
</div>
</form>
</div>
</div>
<div class="gray-block-2">
{% if train %}
{% for title in titles %}
<p>{{title}}</p
{% endfor %}
<form action = "./train" method = "POST">
<input type = "text" placeholder="Number of lines" name = "lines" />
<div class="submit-button-2">
<button type = "predict"> Predict</button>
</div>
</form>
{% else %}
API calls reached. Try again later.
{% endif %}
</div>
</body>
</html>发布于 2021-03-19 00:17:39
当第一次用simple.html请求加载GET时,没有定义变量train。因此,if train将返回False,else语句中的文本将显示:“已达到的API调用。再试一次。“
您可以在后端设置另一个变量。
@app.route('/artist', methods=['POST'])
def insert_text():
…
return render_template('simple.html', is_post=True, …)并相应地更新前端。
<div class="gray-block-2">
{% if is_post %}
{% if train %}
…
{% else %}
API calls reached. Try again later.
{% endif %}
{% endif %}
</div>也许还有更好的办法。我只是想给你指明正确的方向。
https://stackoverflow.com/questions/66695876
复制相似问题