python - 在 flask 应用程序上使用 cx_freeze

标签 python flask cx-freeze

我正在使用 Flask 开发 Python 应用程序。目前,我希望这个应用程序在本地运行。它通过 python 在本地运行良好,但是当我使用 cx_freeze 将它变成 Windows 的 exe 时,我不能再使用 Flask.render_template() 方法。当我尝试执行 render_template 时,我收到了一个 http 500 错误,就好像我要呈现的 html 模板不存在一样。

主 python 文件称为 index.py。起初我尝试运行:cxfreeze index.py。这不包括 cxfreeze“dist”目录中 Flask 项目的“templates”目录。因此,我尝试使用此 setup.py 脚本并运行 python setup.py build。这现在包括模板文件夹和 index.html 模板,但当它尝试呈现模板时我仍然收到 http:500 错误。

from cx_Freeze import setup,Executable

includefiles = [ 'templates\index.html']
includes = []
excludes = ['Tkinter']

setup(
name = 'index',
version = '0.1',
description = 'membership app',
author = 'Me',
author_email = 'me@me.com',
options = {'build_exe': {'excludes':excludes,'include_files':includefiles}}, 
executables = [Executable('index.py')]
)

这是脚本中的示例方法:

@app.route('/index', methods=['GET'])
def index():
    print "rendering index"
    return render_template("index.html")

如果我运行 index.py 然后在控制台我得到:

 * Running on http://0.0.0.0:5000/
 rendering index
 127.0.0.1 - - [26/Dec/2012 15:26:41] "GET / HTTP/1.1" 200 -
 127.0.0.1 - - [26/Dec/2012 15:26:42] "GET /favicon.ico HTTP/1.1" 404 -

页面在我的浏览器中正确显示,但如果我运行 index.exe,我会得到

 * Running on http://0.0.0.0:5000/
rendering index
127.0.0.1 - - [26/Dec/2012 15:30:57] "GET / HTTP/1.1" 500 -
127.0.0.1 - - [26/Dec/2012 15:30:57] "GET /favicon.ico HTTP/1.1" 404 -

Internal Server Error

The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

在我的浏览器中。

如果我返回原始 html,例如

@app.route('/index', methods=['GET'])
def index():
    print "rendering index"
    return "This works"

然后它工作正常。因此,一种可能的解决方法是停止使用 Flask 的模板并将所有 html 逻辑硬编码到主 python 文件中。但这会变得非常困惑,所以我想尽可能避免它。

我正在使用 Python 2.7 32 位、Cx_freeze for Python 2.7 32 位和 Flask 0.9

感谢您的帮助和想法!

最佳答案

在 Flask 和 Jinga 模块中搜索了许多错误线索后,我终于找到了问题所在。

CXFreeze 不承认 jinja2.ext 是一个依赖项,因此没有包含它。

我通过在其中一个 python 文件中包含 import jinja2.ext 来解决这个问题。

CXFreeze 然后将 ext.pyc 添加到 library.zip\jinja。 (构建后手动复制也可以)

以防其他人疯狂到尝试使用 Flask 开发本地运行的应用程序:)

关于python - 在 flask 应用程序上使用 cx_freeze,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14041450/

相关文章:

python - AWS Chalice 从 S3 返回图像文件

python - 对 ssdeep 的 fuzzy.dll 使用 Python Ctypes 但收到错误

python - Django forms.VaildationError 未显示在基于类的 View 上

python - 在 Flask 中初始化全局数据连接的并发安全方式

python - 是否可以从 Windows 命令提示符运行 python 脚本并同时传递该脚本的参数?

javascript - 在外部 javascript 文件中使用 Jinja2 模板引擎

python - Flask-Migrate 命令 'flask db init' 找不到应用程序文件

python - 为什么对 sys.frozen 使用 getattr 而不是 hasattr?

python - 启动 exe 后,终端窗口与 pygame 窗口一起出现

python - 在 Mac 上使用 cx_Freeze 从 .py 创建 .exe