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

时间:2017-11-14 03:41:00

标签: python flask ctypes locals

所以我对烧瓶非常陌生,并且正在修补CTypes模块以及 - 使用C&在.so文件中编译的C ++文件在Python中使用... 我有一个简单的函数使用CTypes导入到python中,然后使用Flask到html文件中显示函数的返回值(一个随机数为2的幂; x ^ 2)以及一些示例介绍,以防我去从现在开始一年后偶然发现这个文件 - 我清楚地知道为什么我做这个随机样本。 现在,这一切都很好,但是,我在互联网的街道上听到我可以使用** 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)

如果你能提供帮助,请告诉我! :)

1 个答案:

答案 0 :(得分:1)

正如您的代码中所显示的那样,namevalue是全局定义的,因此不是 local 到函数index,因此它们不会当您从locals()函数中调用locals时,会显示在index

如果您将这些内容移动到函数中,这将有效...

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

这会使模板中的名称valuename可用。