【发布时间】:2018-05-19 12:03:27
【问题描述】:
我有一个来自 HTML 表单的字符串变量,我想将它用作其他函数的参数。但是,flask 渲染变量而不是渲染其他内容。在我的情况下,有问题的变量是 sub
@server.route('/')
def main():
return render_template("main.html") #HTML input form is here
@server.route('/index', methods=['POST'])
def index_post():
sub = request.form['search_sub'] #sub is user input
return sub # Don't want render. Just normal return
@server.route('/index') #This page should load after user enters on form
def index():
return render_template("index.html")
@server.route('/index/result', methods=['POST']) # This is where sub will be needed
@cache_flask.cached(timeout=240)
def result():
sub = index_post() # declaring sub here?
main_info = redditnlp.version125_flask(sub) # sub is a parameter here
return render_template("result.html", main_info=main_info)
如果有帮助,这里是我的 main.html 和 index.html 的 HTML 文件
main.html
<form action="/index", method = "POST">
<input id ="input" class="form-control" type="text" placeholder="Insert subreddit" name="search_sub">
</form>
index.html
<form action="/index/result" method="POST">
<button id="result_button" class="button"><span>See sentiment results</span></button>
</form>
【问题讨论】:
-
这很难理解。为什么不能在
result()函数中直接获取request.form['search_sub ']? “渲染变量”是什么意思? -
@DanielRoseman 很抱歉,如果不清楚。当我在
result()中执行sub = request.form['search_sub']时,我得到结果400 Bad Request: KeyError: 'search_sub'我想如果我只是将用户的输入作为字符串变量返回,那么我可以避免这个错误。我所说的渲染的意思是,flask 使用用户输入的值生成一个网页。 -
我还是不明白。 “将用户的输入作为字符串变量返回”是什么意思?如果您收到该错误,那是因为请求中没有这样的表单数据,所以我看不出在同一个请求中调用另一个函数有什么帮助。
标签: python python-3.x flask