如何不渲染/显示烧瓶中返回的变量?

时间:2018-05-19 12:03:28

标签: python python-3.x flask

我有一个来自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>

1 个答案:

答案 0 :(得分:0)

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

首先,您似乎通过缓存search_sub视图功能来尝试为将来的请求缓存result()表单字段的值。但是,您正在缓存错误的视图功能。您应该缓存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