0

所以我对烧瓶很陌生,并且也在修改 CTypes 模块 - 玩弄在 .so 文件中编译以在 Python 中使用的 C 和 C++ 文件......我有一个使用 CTypes 导入到 python 中的简单函数,然后显示使用 Flask 将函数的返回值(一个随机数的 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)

让我知道您是否可以提供帮助!:)

4

1 回答 1

2

正如它在您的代码中出现的那样,name并且value是全局定义的,因此不是函数本地的,因此当您从函数内部调用时index它们不会出现。locals()localsindex

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

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

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

于 2017-11-14T03:46:22.460 回答