【问题标题】:[Flask]TypeError: 'function' object is not subscriptable[Flask]TypeError: 'function' 对象不可下标
【发布时间】:2021-11-16 17:10:32
【问题描述】:

下面的代码来自“Learn Python3 the Hard Way”。我收到的是 GET 而不是 POST 请求。烧瓶调试器指出在线索引中的错误
'return render_template["hello_form.html"]'- TypeError: 'function' object is not subscriptable. 这意味着它没有进入“POST”部分。表格是如何工作的?是 html文件正确吗?模板目录包含:

模板/hello_form.html

    <form action="/hello" method="POST">
        A Greeting: <input type="text" name="greet">
        </br>
        Your name: <input type="text" name="name">
        </br>
        <input type = "submit">
    </form>

模板/index.html

<body>
    {% if greeting %}
        I just wanted to say
        <em style="color: red; font-size: 2em;">{{ greeting }} </em>.
    {% else %}
        <em>Hello</em>, world!
    {% endif %}
</body>

app.py

@app.route("/hello", methods=['POST','GET'])
    def index():
        greeting = "Hello World"
        if request.method == "POST":
            name = request.form['name']
            greet = request.form['greet']
            greeting = f"{greet}, {name}"
            return render_template("index.html", greeting=greeting)
        else:
            return render_template["hello_form.html"]

[网址] http://localhost:5000/hello

【问题讨论】:

    标签: python flask


    【解决方案1】:

    变化:

    @app.route("/hello", methods=['POST','GET'])
        def index():
            greeting = "Hello World"
            if request.method == "POST":
                # ...
            else:
                return render_template["hello_form.html"] # < --- this
    

    收件人:

    @app.route("/hello", methods=['POST','GET'])
        def index():
            greeting = "Hello World"
            if request.method == "POST":
                # ...
            else:
                return render_template("hello_form.html") # < --- this
    

    正如@Xochozomatli 所说的那样,您需要使用一对括号来调用该函数,而不是为其下标的方括号。

    【讨论】:

      【解决方案2】:

      当你第一次去http://localhost:5000/hello时,这是一个GET请求,POST请求只在你提交表单时发生。

      它崩溃的原因是您在“hello_form.html”周围有方括号而不是括号(即,您像字典一样“下标”render_template,而不是像函数一样“调用”它)。

      代码的执行方式如下:

      1. 您转到http://localhost:5000/hello,它会向index 发送GET 请求。
      2. else 块执行并将hello_form.html 发送到您的浏览器。
      3. 您输入问候语,然后单击表单上的“提交”,该表单会向index 发送POST 请求和您的问候语。
      4. 现在index 再次运行,但这次if执行。

      【讨论】:

        猜你喜欢
        • 2021-02-14
        • 1970-01-01
        • 2019-09-10
        • 1970-01-01
        • 2018-05-02
        • 1970-01-01
        • 2016-07-20
        • 2020-07-28
        • 1970-01-01
        相关资源
        最近更新 更多