Flask render_template() & **locals() arg 不工作...不会在 HTML 文本中显示 python 变量

Flask render_template() & **locals() arg not working... Won't display python variables in HTML text

所以我对 Flask 还很陌生,我也在研究 CTypes 模块 - 研究编译在 .so 文件中的 C 和 C++ 文件,以便在 Python 中使用... 我有一个使用 CTypes 导入到 python 的简单函数,然后使用 Flask 将函数的 return 值(一个随机数的 2 次方;x^2)显示到 html文件连同一个小样本介绍,以防一年后我偶然发现这个文件——我会清楚地知道我为什么制作这个随机样本。 现在,一切都很好,但我在网上听说我可以使用 **locals() 将多个(所有)我的 python 变量导入我的 HTML 模板。 我见过其他人让这个工作,但唉 - 我不能...... 我将创建一个 Python 函数来替换 C++ 文件,这样你们就不必弄乱它了……它工作正常,只是这个文件的一部分,而不是问题的固有部分。我太天真了以至于我完全忽略了一些东西,而 CTypes 模块可能是这个困境的根源。

from flask import Flask, render_template
# disabled the CTypes module for your convenience...
# from ctypes import *
def c_plus_plus_replacement(x):
    return pow(x, 2)

# libpy = CDLL("./libpy.so")
# value = libpy.main(10)

value = c_plus_plus_replacement(5)
name = "Michael"

app = Flask(__name__)

@app.route("/")
def index():
    # ---- The problem is at this return statement to render the HTML template...
    # render_template("base.html", value=value, name=name) works fine, but I would like this statement to work...
    return render_template("base.html", value=value)

if __name__ == '__main__':
    app.run(debug=False)

如果你能帮上忙,请告诉我! :)

如您的代码所示,namevalue 是全局定义的,因此对于函数 index 而言不是 local,因此,当您从 index 函数中调用 locals 时,它们不会出现在 locals() 中。

如果您将它们移动到函数中,这将起作用...

def index():
    value = c_plus_plus_replacement(5)
    name = "Michael"
    return render_template('base.html', **locals())

这将使名称 valuename 在呈现的模板中可用。