【问题标题】:How to not render/display a variable returned in flask?如何不渲染/显示烧瓶中返回的变量?
【发布时间】: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


【解决方案1】:

我假设您使用的是Flask-CachingFlask-Cache

首先,您似乎试图通过缓存result() 视图函数来缓存search_sub 表单字段的值以供将来的请求使用。但是,您正在缓存错误的视图函数。您应该缓存index_post(),因为这是生成您希望在请求之间保留的值的视图。

其次,这是行不通的。直接调用缓存视图会绕过缓存,因为键名默认为路由路径。您可以通过在 key_prefix 参数中提供自己的密钥来覆盖它:

@server.route('/index', methods=['POST'])
@server.cache.cached(timeout=240, key_prefix='index_post')
def index_post():
    sub = request.form['search_sub']
    return sub

这会将缓存键设置为index_post。现在直接调用这个函数,或者作为一个视图,都可以工作了。


这似乎是一种非常复杂的处理方式。或许你应该看看 Flask 内置的sessions

【讨论】:

  • 对不起,我认为我最初的问题没有意义。问题是,main() 函数(如果你可以调用它)就像谷歌主页。在这种情况下,用户输入他们想要查找的 subreddit 和 index() 函数然后以按钮的形式为他们提供他们想要调用的函数的选项,result() 就是其中之一。 pt1
  • ...我正在尝试将我的输入/search_sub 加载到result() 函数,因为redditnlp.version125_flask(sub) 来自另一个Python 文件的函数需要search_subsub 作为参数。 我遇到的主要问题是从main() 获取用户输入并将其作为参数sub 插入到result() 下的python 函数redditnlp.version125_flask(sub) 我有缓存的原因result() 是因为这个函数在你第一次调用它时需要一段时间来加载数据,因为它正在从 Reddit 中获取数据。希望这可以帮助。谢谢
  • 使用烧瓶sessions。将sub 添加到index_post() 中的会话。然后在后续请求中可以在其他视图如result()访问。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-28
  • 2020-10-18
相关资源
最近更新 更多