简体   繁体   English

Python Flask:获取和发布方法的不同render_template可能吗?

[英]Python Flask: Different render_template for Get and Post Methods Possible?

I have a template ( index.html ) that I would like to display on GET and the same template, with a variable added, on POST . 我有一个模板( index.html ),我想在GET上显示,而同一模板,在POST上添加了变量。

app.py: app.py:

from flask import Flask, render_template
app = Flask(__name__)

@app.route("/")
def hello():
    return render_template("index.html")

@app.route("/", methods=["POST"])
def hello_():
    return render_template("index.html", string_="Success!")

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=4567)

index.html: index.html的:

<html>
    <head>
        <script type="text/javascript" src="/static/jquery.js"></script>
    </head>

    <body>

    <button onclick="signIn();">Sign In</button>
    <h1>{{ string_ }}</h1>

    <script>
        function signIn() {
        var data = "data";

        $.ajax({
            type : "POST",
            data: JSON.stringify(data, null, '\t'),
            contentType: 'application/json',
            success: function(result) {
                console.log(result);
                }
              });
        }
    </script>
    </body>
</html>

traceback: 追溯:

 * Running on http://0.0.0.0:4567/ (Press CTRL+C to quit)
127.0.0.1 - - [11/Dec/2015 11:16:17] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [11/Dec/2015 11:16:17] "GET /static/jquery.js HTTP/1.1" 304 -
127.0.0.1 - - [11/Dec/2015 11:16:21] "POST / HTTP/1.1" 200 -

I'm not receiving an error, but the variable string_ isn't appearing in the template on POST (after I click the button). 我没有收到错误,但是在POST的模板中没有出现变量string_ (单击按钮后)。 It appears that the template I have set to render on POST isn't working. 我设置为在POST上呈现的模板似乎无法正常工作。

Is it possible to render a different template in Flask based on request.method ? 是否可以根据request.method在Flask中渲染不同的模板?

It makes the most sense to split this into two distinct routes, one serving the GET and one serving the POST . 将它分成两条截然不同的路径是最有意义的,一条为GET服务,另一条为POST服务。

@app.route('/')
def index_as_get():
    return render_template('index.html', name="")

@app.route('/', methods=["POST"])
def index_as_post():
    r = request.get_json()
    name = r['name']
    return render_template('index.html', name=name)

Note that you actually have to invoke this behavior through a REST client that can invoke a POST request to your root page before you can notice anything. 请注意,您实际上必须通过REST客户端来调用此行为,该客户端可以在您注意到任何内容之前调用对根页的POST请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM