Flask application built using pyinstaller not rendering index.html

前端 未结 5 650
面向向阳花
面向向阳花 2020-12-25 15:19

I have written a flask application and it works perfectly fine. I wanted to distribute it as an executable. Tried doing it using pyinstaller flaskScript.py dist folder got

5条回答
  •  没有蜡笔的小新
    2020-12-25 15:52

    This question is a bit old now, but I was having the same problem (Python 3.4.3, Flask 0.10.1 and PyInstaller 3.1.1) when packaging it to a single file.

    I've managed to solve it by adding the following to the initialization script (app\__init__.py):

    import sys
    import os
    from flask import Flask
    # Other imports
    
    if getattr(sys, 'frozen', False):
        template_folder = os.path.join(sys._MEIPASS, 'templates')
        app = Flask(__name__, template_folder=template_folder)
    else:
        app = Flask(__name__)
    
    # etc
    

    The problem is that when the site is running in packaged form, the templates are inside a directory called _MEIxxxxxx under the temp directory (see this in the PyInstaller Manual) so we have to tell that to Flask.

    That is done with the template_folder argument (which I found out about in this answer here and later in the API docs).

    Finally, the if is there to ensure that we can still use it unpackaged while developing it. If it is frozen, then the script is packaged and we have to tell Flask where to find the templates; otherwise we're running it in a Python environment (taken from here) and the defaults will work (assuming you're using the standard templates directory of course).

提交回复
热议问题