【问题标题】:Is there a way to return function output on a html template in Python?有没有办法在 Python 中的 html 模板上返回函数输出?
【发布时间】:2020-08-02 13:36:34
【问题描述】:

我正在使用以下代码:

def static_info(nm):
    cursor.execute("SELECT name,age,FROM MyDB where name like ?",(nm) + '%')
    for row in cursor:
        static={"NAME: ":row[0],"AGE: ":row[1]}
    return(static)

@app.route('/submit_form')
def submit_form():
    nm = request.form.get('name')
    info=static_info(nm)
    return render_template('static_display.html',info=info)

我需要在我的 static_display.html 页面上输出所需的函数输出(以字典的形式)

有什么建议吗?

【问题讨论】:

    标签: html flask python-3.7


    【解决方案1】:

    奇怪的编码。

    1. static_info(nm) 中的循环只会返回最后一项。你没有附加任何东西

    2. 您的 @app.route('/submit_form') 不接受 POST。你需要:

      @app.route('/submit_form', methods = ['GET', 'POST'])

    3. 在您的模板static_display.html 中,您将需要{{ info }}

    4. 如果您更改代码以便循环遍历模板中的列表,您将需要以下内容:

      {% for item in info %} {% for key, value in item.items() %}
      {{ 键 }} : {{ 值 }}
      {% endfor %} {% endfor %}

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-24
      • 2021-11-09
      • 1970-01-01
      相关资源
      最近更新 更多