首页 文章

在flask app上使用cx_freeze

提问于
浏览
7

我正在使用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 . 现在包括templates文件夹和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用于Python 2.7 32位和Flask 0.9

感谢您的帮助和想法!

2 回答

  • 16

    经过Flask和Jinga模块的许多虚假踪迹后,我终于找到了问题所在 .

    CXFreeze无法识别jinja2.ext是一个依赖项,并且不包括它 .

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

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

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

  • 0

    源文件中 import jinja2.ext 的替代方法是在setup.py中具体包含 jinja2.ext

    from cx_Freeze import setup,Executable
    
    includefiles = [ 'templates\index.html']
    includes = ['jinja2.ext']  # add jinja2.ext here
    excludes = ['Tkinter']
    
    setup(
    name = 'index',
    version = '0.1',
    description = 'membership app',
    author = 'Me',
    author_email = 'me@me.com',
    # Add includes to the options
    options = {'build_exe':   {'excludes':excludes,'include_files':includefiles, 'includes':includes}},   
    executables = [Executable('index.py')]
    )
    

相关问题