jinja2.exceptions.UndefinedError: 'function' 未定义 [英] jinja2.exceptions.UndefinedError: 'function' is undefined

查看:93
本文介绍了jinja2.exceptions.UndefinedError: 'function' 未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 nginx + uwsgi 上运行一个 Flask 服务器.当我通过 python server.py 只运行 Flask 服务器时,我可以在我的 jinja2 模板中使用 id_encode 函数,不会抛出任何错误.

I am running a flask server on nginx + uwsgi. When I run just the flask server via python server.py, I am able to use id_encode function in my jinja2 templates, no errors thrown.

但是,当我通过

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

它会崩溃,说找不到函数id_encode.

It will crash saying that it was unable to find the function id_encode.

jinja2.exceptions.UndefinedError: 'id_encode' 未定义

声明方式:

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

导致此问题的原因是什么,我如何才能使该功能可用?

What's causing this problem and how can I make the function available?

推荐答案

问题是 __main__ 块只会在脚本作为顶部运行时才会被执行级别脚本.uwsgi 导入你的模块,所以 __main__ 块永远不会运行.将您的 app.jinja_env.globals.update(id_encode=id_encode) 移到 __main__ 块之外,一切都应该正常工作.

The issue is that the __main__ block will only get executed if the script is run as a top level script. uwsgi imports your module and so the __main__ block is never run. Move your app.jinja_env.globals.update(id_encode=id_encode) outside of the __main__ block and everything should work correctly.

这篇关于jinja2.exceptions.UndefinedError: 'function' 未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆