我有一个小应用程序,从用户那里获取输入,并根据它在html上显示数据。我必须从flask发送数据到html上显示但无法找到方法。我遇到没有错误。
[增订]: Python脚本:
from flask import Flask, render_template, request
import random
app = Flask(__name__, template_folder='templates')
@app.route('/', methods=['GET','POST'])
def samplefunction():
if request.method == 'GET':
return render_template('new.html')
if request.mthod == 'POST':
greetIn = ['hey', 'hi', 'hey there', 'hi there', 'hello', 'hola', 'yoo']
byeIn = ['bye', 'see you later', 'catch you later', 'toodles']
nameOut = ['my name is Fatty!!', 'Fatty is my name', 'you can call me Fatty', 'I go by the name of Fatty']
greetOut = ['hey there!', 'hi!', 'hi there!', 'hey!']
byeOut = ['bye bye', 'bye. see you later']
human1 = request.form['human']
if human1 in greetIn:
bot = random.choice(greetOut)
return render_template('new.html', bot=bot)
else:
bot = 'Sorry..no idea!!!'
return render_template('new.html', bot=bot)
if __name__ == "__main__":
app.run(debug=True)
HTML code:
<html>
<head>
<title>BOT</title>
<script>
var bot = {{ bot }}
</script>
</head>
<body>
<h1>Hello, type something to begin!</h1>
<form method='post'>
Human: <input type='text' name='human'><br>
Bot: {{ bot }}<br>
<input type="submit" name="action">
</form>
</body>
</html>
任何帮助都将不胜感激。
谢谢!
答案 0 :(得分:1)
<强>问题强>
由于初始返回语句,您的函数samplefunction()
始终呈现new.html
而不包含变量。
def samplefunction():
return render_template('new.html')
<强>修正强>
您需要添加if request.method == 'GET':
和if request.method == 'POST':
,然后您的代码才能生效。并按@Harrison建议更改变量名称作为另一个答案:bot = random.choice(greetOut)
而非bot = random.choice(greetout)
更新代码
def samplefunction():
if request.method == 'GET':
return render_template('new.html')
if request.method == 'POST':
greetIn = ['hey', 'hi', 'hey there', 'hi there', 'hello', 'hola', 'yoo']
byeIn = ['bye', 'see you later', 'catch you later', 'toodles']
nameOut = ['my name is Fatty!!', 'Fatty is my name', 'you can call me Fatty', 'I go by the name of Fatty']
greetOut = ['hey there!', 'hi!', 'hi there!', 'hey!']
byeOut = ['bye bye', 'bye. see you later']
human1 = request.form['human']
if human1 in greetIn:
bot = random.choice(greetOut)
return render_template('new.html', bot=bot)
else:
render_template('new.html')
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8080, debug=True)
答案 1 :(得分:0)
greetOut = ['hey there!', 'hi!', 'hi there!', 'hey!']
&lt; - greet 0 ut
bot = random.choice(greetout)
&lt; - greet o ut
除此之外,你的模板看起来很好。如果你更正了大写,它应该有用。
此外,不是强制性的,但您可以将Flask导入压缩为1行,如下所示:
from flask import Flask, render_template, request