异常。未定义错误:'函数&未定义未定义、函数、异常、错误

2023-09-03 11:03:30 作者:成绩单是一份微凉的遗书

我在nginx+uwsgi上运行一个FASK服务器。当我通过python server.py只运行flASK服务器时,我能够在我的JJIA2模板中使用id_encode函数,没有抛出错误。

但是,当我通过

启动(server.py)时 javascript onclick调用函数,进入不了函数,报函数未定义的错误

uwsgi --socket 0.0.0.0:8002 --module server --callab app

它将崩溃,并报告找不到函数id_encode

jinja2.exceptions.UndefinedError: 'id_encode' is undefined

声明方式:

if __name__ == '__main__':
    app.jinja_env.globals.update(id_encode=id_encode)
    app.run(host=host,port=5000, debug=True)

导致此问题的原因以及如何使该功能可用?

推荐答案

问题是,只有当脚本作为顶级脚本运行时,才会执行__main__块。Uwsgi导入模块,因此__main__块永远不会运行。将app.jinja_env.globals.update(id_encode=id_encode)移出__main__块,一切都应该正常工作。