flaskwebgui

repository·master·Indexed 21 days ago

https://github.com/climentea/flaskwebgui

A Python library that allows developers to turn standard web applications built with Flask, FastAPI, Django, or Flask-SocketIO into standalone desktop applications by wrapping them in a browser window. It provides the FlaskUI class to manage server lifecycles and browser configurations, including app mode to hide browser UI elements, custom window sizing, and support for distribution via PyInstaller.

Tokens
2.8K
Snippets
13
Records
14
Agent score
24%

What's inside flaskwebgui

  1. Plug in custom web frameworks with FlaskUI

    master

    You can support any Python web framework by providing a custom server function to FlaskUI. This function will receive server_kwargs which you can use to initialize and run your framework.

    def start_custom_framework(**server_kwargs):
        app = server_kwargs.pop("app", None)
        # ... logic to start your framework ...
        app.run(**server_kwargs)
    
    if __name__ == "__main__":
        FlaskUI(
            server=start_custom_framework,
            server_kwargs={
                "app": app,
                "port": 3000,
            },
        ).run()
  2. Distribute your app with PyInstaller

    master

    To distribute your application as a standalone executable, use pyinstaller. If you have static assets (templates, CSS, etc.), you must include them using the --add-data flag.

    # Basic command
    pyinstaller -w -F main.py
    
    # Including data files (Windows uses ';' separator, Linux/Mac uses ':')
    pyinstaller --name your-app-name --add-data "templates:templates" --add-data "static:static" main.py
  3. Use FlaskUI with Django

    master

    To use Django, you must first configure static/media files and add whitenoise.middleware.WhiteNoiseMiddleware to your MIDDLEWARE in settings.py. Then, create a gui.py file next to manage.py to launch the UI.

    # gui.py
    from flaskwebgui import FlaskUI
    from djangodesktop.wsgi import application as app
    
    if __name__ == "__main__":
        FlaskUI(app=app, server="django").run()

    Run the application using:

    python gui.py
  4. Prevent users from opening the browser console

    master

    Since the GUI is a browser window, you can use JavaScript to disable common developer tools like the F12 key and right-click context menus.

    <script>
        // Prevent F12 key
        document.onkeydown = function (e) {
            if (e.key === "F12") {
                e.preventDefault();
            }
        };
    
        // Prevent right-click
        document.addEventListener("contextmenu", function (e) {
            e.preventDefault();
        });
    </script>
  5. Configure FlaskUI parameters

    master

    The FlaskUI class accepts several parameters to customize the desktop experience:

    • server: Union[str, Callable[[Any], None]]: Function to start the server (e.g., "flask", "fastapi", "django").
    • server_kwargs: dict = None: Arguments passed to the server function.
    • app: Any = None: The WSGI or ASGI application instance.
    • port: int = None: Specify a port.
    • width: int = None: Window width.
    • height: int = None: Window height.
    • fullscreen: bool = True: Start in maximized mode.
    • on_startup: Callable = None: Function to run before starting the browser and server.
    • on_shutdown: Callable = None: Function to run after shutdown.
    • extra_flags: List[str] = None: Additional browser command line flags.
    • browser_path: str = None: Path to the Chrome executable.
    • browser_command: List[str] = None: Custom command line to start Chrome in app mode.
    • socketio: Any = None: The SocketIO instance (required for flask_socketio).
    • app_mode: bool = True: If True, starts in app mode (no address bar); if False, starts in guest mode.
    • browser_pid: int = None: The PID of the opened browser process.
    • auto_close: bool = True: If True, closing the browser also closes the server.
  6. Use FlaskUI with Flask

    master

    To wrap a standard Flask application in a desktop window, import FlaskUI and call .run() with the app instance and server="flask".

    from flask import Flask, render_template
    from flaskwebgui import FlaskUI
    
    app = Flask(__name__)
    
    @app.route("/")
    def hello():
        return render_template('index.html')
    
    if __name__ == "__main__":
        FlaskUI(app=app, server="flask").run()
  7. Use FlaskUI with Flask-SocketIO

    master

    For SocketIO applications, pass both the app and the socketio instance to FlaskUI, and set server="flask_socketio".

    from flask import Flask, render_template
    from flask_socketio import SocketIO
    from flaskwebgui import FlaskUI
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    socketio = SocketIO(app)
    
    @app.route("/")
    def hello():
        return render_template('index.html')
    
    if __name__ == '__main__':
        FlaskUI(
            app=app,
            socketio=socketio,
            server="flask_socketio",
            width=800,
            height=600,
        ).run()
  8. Use FlaskUI with FastAPI

    master

    To use FastAPI, pass the app instance and set server="fastapi". The application will be served using uvicorn.

    from fastapi import FastAPI, Request
    from fastapi.responses import HTMLResponse
    from fastapi.staticfiles import StaticFiles
    from fastapi.templating import Jinja2Templates
    from flaskwebgui import FlaskUI
    
    app = FastAPI()
    app.mount("/public", StaticFiles(directory="dist/"))
    templates = Jinja2Templates(directory="dist")
    
    @app.get("/", response_class=HTMLResponse)
    async def root(request: Request):
        return templates.TemplateResponse("index.html", {"request": request})
    
    if __name__ == "__main__":
        FlaskUI(app=app, server="fastapi").run()
  9. Close the application using a route

    master

    You can programmatically close the desktop window by calling close_application() from within a web framework route.

    from flaskwebgui import FlaskUI, close_application
    
    @app.route("/close", methods=["GET"])
    def close_window():
        close_application()
  10. Set the logging level for FlaskUI

    master

    You can control the verbosity of flaskwebgui logs by setting the FLASKWEBGUI_LOG_LEVEL environment variable before running your application. Supported levels are standard Python logging levels (e.g., DEBUG, INFO, WARNING, ERROR).

    Default level is DEBUG.

    export FLASKWEBGUI_LOG_LEVEL=INFO
    python your_app.py
  11. Customize browser behavior and paths in FlaskUI

    master

    You can override the automatic browser detection by providing specific paths or commands to FlaskUI:

    • browser_path: An absolute path to the browser executable (e.g., /usr/bin/google-chrome).
    • browser_command: A list of strings representing the full command to launch the browser. This overrides both browser_path and the default flags generated by get_browser_command.
    • extra_flags: A list of strings to append to the default Chromium command-line switches (like --user-data-dir and --app).
    # Using a specific browser path
    ui = FlaskUI(app=app, server='flask', browser_path='/path/to/custom/browser')
    
    # Adding custom flags
    ui = FlaskUI(app=app, server='flask', extra_flags=['--incognito'])