Monday, May 19, 2025

Python Flask project into a distributable .exe file using PyInstaller

๐Ÿงฉ How to Convert a Complete Flask Project into a Distributable .exe File Using PyInstaller

Flask is a popular Python web framework, but distributing a Flask app to non-technical users or across an organization can be a challenge—especially when you want to avoid complex setups or Python dependencies. Fortunately, PyInstaller lets you turn your Flask app into a single Windows .exe file that can be executed without installing Python or managing virtual environments.

๐Ÿš€ To convert a complete Flask project into a distributable .exe file using PyInstaller, follow the steps outlined below:

✅ 1. Prepare Your Flask Project

Make sure your Flask app has an entry point, typically something like app.py or run.py with a structure like:

from flask import Flask

app = Flask(__name__)

@app.route('/')

def home():

    return "Hello, Flask!"

if __name__ == "__main__":

    app.run()

✅ 2. Install PyInstaller

pip install pyinstaller

✅ 3. Use the PyInstaller Command

Run the following command in your project directory to generate a standalone executable that includes all dependencies:

pyinstaller --onefile --windowed --add-data "templates;templates" --add-data "static;static" app.py

Replace app.py with the main entry-point file of your Flask app.

๐Ÿ” Explanation of Flags

--onefile: Package everything into a single .exe file.

--windowed: Hides the console window (optional; good for GUI apps).

--add-data: Includes folders like templates and static.

Format: "source;destination" (use : instead of ; on macOS/Linux).

✅ 4. Output Location

After running the command, your .exe will be in the dist/ folder:

dist/

└── app.exe

✅ 5. Distribute Within the Company

You can share the dist/run.exe file directly. Ensure:

Target machines have the required firewall permissions (Flask runs a local server).

If the app uses a browser interface, it should auto-open or include instructions to visit http://127.0.0.1:5000.

๐Ÿ’ก Optional: Auto-Open Browser on Run

In your app.py, add:

import webbrowser from threading import Timer

def open_browser():

    webbrowser.open("http://127.0.0.1:5000")

if __name__ == "__main__":

    Timer(1, open_browser).start()

    app.run()

๐ŸŽฏ Conclusion

Packaging your Flask application into a .exe file using PyInstaller is a powerful way to simplify deployment and make your app more accessible to end users. With just a few commands and a clear structure, you can create and share production-ready desktop versions of your web applications within your company—no Python installation required.


No comments:

Post a Comment

Building Secure Azure AI Foundry Agents with Managed Identity

  The credential problem nobody wants to own Every team that connects an Azure AI Foundry agent to Microsoft Graph, SharePoint, Outlook, or...