### Advanced Usage: NiceGUI Integration Example Source: https://github.com/climentea/flaskwebgui/blob/master/README.md Example of integrating FlaskWebGUI with the NiceGUI framework. ```APIDOC ## Advanced Usage: NiceGUI Integration Example ### Description This example shows how to use `FlaskUI` with the `nicegui` package to create a desktop application. ### Method N/A (Python Script) ### Endpoint N/A ### Parameters See `FlaskUI` Configurations. ### Request Example ```python from flaskwebgui import FlaskUI from nicegui import ui ui.label("Hello Super NiceGUI!") ui.button("BUTTON", on_click=lambda: ui.notify("button was pressed")) def start_nicegui(**kwargs): ui.run(**kwargs) if __name__ in {"__main__", "__mp_main__"}: DEBUG = False if DEBUG: ui.run() else: FlaskUI( server=start_nicegui, server_kwargs={"dark": True, "reload": False, "show": False, "port": 3000}, width=800, height=600, ).run() ``` ### Response N/A ``` -------------------------------- ### Integrate NiceGUI with FlaskWebGUI Source: https://context7.com/climentea/flaskwebgui/llms.txt Demonstrates building reactive desktop applications using NiceGUI and FlaskWebGUI. Requires a custom start function to interface with NiceGUI's internal server. ```python from flaskwebgui import FlaskUI, close_application from nicegui import ui ui.label("Desktop Application with NiceGUI") ui.button("Click Me", on_click=lambda: ui.notify("Button clicked!")) ui.button("Close App", on_click=close_application) def start_nicegui(**kwargs): ui.run(**kwargs) if __name__ in {"__main__", "__mp_main__"}: FlaskUI( server=start_nicegui, server_kwargs={ "dark": True, "reload": False, "show": False, "port": 3000, }, width=800, height=600, ).run() ``` -------------------------------- ### Install Flaskwebgui Source: https://github.com/climentea/flaskwebgui/blob/master/README.md Command to install the flaskwebgui package via pip. ```bash pip install flaskwebgui ``` -------------------------------- ### Custom Flask Server Implementation Source: https://github.com/climentea/flaskwebgui/blob/master/README.md Demonstrates how to provide a custom server function to FlaskUI to manage Flask application startup. This example uses the 'waitress' WSGI server if available, falling back to Flask's built-in development server. ```python from flaskwebgui import FlaskUI from flask import Flask app = Flask(__name__) def start_flask(**server_kwargs): app = server_kwargs.pop("app", None) server_kwargs.pop("debug", None) try: import waitress waitress.serve(app, **server_kwargs) except ImportError: app.run(**server_kwargs) except Exception as e: print(f"Error starting server: {e}") app.run(**server_kwargs) if __name__ == "__main__": def saybye(): print("on_exit bye") FlaskUI( server=start_flask, server_kwargs={ "app": app, "port": 3000, "threaded": True, }, width=800, height=600, on_shutdown=saybye, ).run() ``` -------------------------------- ### Advanced Usage: Custom Server Example (Waitress) Source: https://github.com/climentea/flaskwebgui/blob/master/README.md Example of how to use a custom server function (like Waitress) with FlaskUI. ```APIDOC ## Advanced Usage: Custom Server Example (Waitress) ### Description This example demonstrates how to plug in a custom web server like Waitress by providing a `server` function to `FlaskUI`. ### Method N/A (Python Script) ### Endpoint N/A ### Parameters See `FlaskUI` Configurations. ### Request Example ```python from flaskwebgui import FlaskUI def start_flask(**server_kwargs): app = server_kwargs.pop("app", None) server_kwargs.pop("debug", None) try: import waitress waitress.serve(app, **server_kwargs) except ImportError: app.run(**server_kwargs) if __name__ == "__main__": # Assume 'app' is your Flask application instance # from flask import Flask # app = Flask(__name__) def saybye(): print("on_exit bye") FlaskUI( server=start_flask, server_kwargs={ "app": app, "port": 3000, "threaded": True, }, width=800, height=600, on_shutdown=saybye, ).run() ``` ### Response N/A ``` -------------------------------- ### GET /close Endpoint Source: https://github.com/climentea/flaskwebgui/blob/master/README.md This endpoint is used to close the application window. ```APIDOC ## GET /close ### Description This endpoint triggers the closing of the application window. ### Method GET ### Endpoint /close ### Parameters None ### Request Example None ### Response None ``` -------------------------------- ### Get Available Port Utility Source: https://context7.com/climentea/flaskwebgui/llms.txt A utility function to find an available network port, which is essential for custom server configurations to avoid port conflicts. ```python from flaskwebgui import get_free_port # Get a random available port port = get_free_port() print(f"Available port: {port}") # e.g., Available port: 54321 ``` -------------------------------- ### Fetch Data from Bottle Server Source: https://github.com/climentea/flaskwebgui/blob/master/examples/bottle-desktop/static/index.html This snippet demonstrates how to perform an asynchronous HTTP GET request to a Bottle route using the JavaScript Fetch API. It expects a JSON response from the server and logs the result to the console. ```javascript async function fetchData() { const response = await fetch("/forum?id=test"); const data = await response.json(); console.log(data); } fetchData(); ``` -------------------------------- ### Flask Routing for Window Close Source: https://github.com/climentea/flaskwebgui/blob/master/README.md Defines a Flask route '/close' that triggers the close_application function when accessed via a GET request. This is typically linked from an HTML button to close the application window. ```python from flask import Flask app = Flask(__name__) def close_application(): # Placeholder for actual window closing logic print("Closing application...") @app.route("/close", methods=["GET"]) def close_window(): close_application() return "", 204 # Return empty response with 204 No Content status ``` -------------------------------- ### Initialize FlaskUI for Desktop Application Source: https://context7.com/climentea/flaskwebgui/llms.txt Demonstrates how to wrap a standard Flask application into a desktop window. It includes custom window dimensions and lifecycle callbacks for startup and shutdown events. ```python from flask import Flask, render_template from flaskwebgui import FlaskUI app = Flask(__name__) @app.route("/") def index(): return render_template("index.html") @app.route("/about") def about(): return render_template("about.html") if __name__ == "__main__": FlaskUI( app=app, server="flask", width=1024, height=768, fullscreen=False, on_startup=lambda: print("Application starting..."), on_shutdown=lambda: print("Application closed"), ).run() ``` -------------------------------- ### Run Flask Application as Desktop GUI Source: https://github.com/climentea/flaskwebgui/blob/master/README.md Demonstrates how to wrap a standard Flask application with FlaskUI to run it in a desktop window. ```python 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() ``` -------------------------------- ### Use Custom Server Functions Source: https://context7.com/climentea/flaskwebgui/llms.txt Allows integration of arbitrary web frameworks like Bottle or Tornado by passing a custom server run function and configuration arguments. ```python from bottle import Bottle, run, static_file from flaskwebgui import FlaskUI, get_free_port app = Bottle() @app.route("/") def index(): return static_file("index.html", root="./static") @app.route("/static/") def static_files(path): return static_file(path, root="./static") if __name__ == "__main__": port = get_free_port() FlaskUI( server=run, # Bottle's run function server_kwargs={ "app": app, "server": "wsgiref", "host": "127.0.0.1", "port": port, "reloader": False, "quiet": True, }, width=800, height=600, ).run() ``` -------------------------------- ### FlaskUI Initialization and Server Configuration Source: https://context7.com/climentea/flaskwebgui/llms.txt Configures the FlaskUI instance with custom server logic and window dimensions. ```APIDOC ## FlaskUI Initialization ### Description Initializes the desktop application wrapper with a custom server implementation. ### Parameters - **server** (callable) - Required - Custom function to run the server. - **server_kwargs** (dict) - Optional - Arguments passed to the server function. - **width** (int) - Optional - Window width in pixels. - **height** (int) - Optional - Window height in pixels. ### Request Example FlaskUI(server=custom_server, server_kwargs={"app": "main:app", "port": 5000}, width=800, height=600).run() ``` -------------------------------- ### Run FastAPI Application as Desktop GUI Source: https://github.com/climentea/flaskwebgui/blob/master/README.md Demonstrates wrapping a FastAPI application with FlaskUI for desktop deployment. ```python from fastapi import FastAPI from flaskwebgui import FlaskUI app = FastAPI() if __name__ == "__main__": FlaskUI(app=app, server="fastapi").run() ``` -------------------------------- ### Package Application with PyInstaller Source: https://context7.com/climentea/flaskwebgui/llms.txt Provides command-line instructions for building standalone desktop executables, including handling data files for Linux/macOS and Windows. ```bash # Basic build pyinstaller -w -F main.py # With data files (Linux/macOS) pyinstaller --name my-app --add-data "templates:templates" --windowed --onefile main.py # With data files (Windows) pyinstaller --name my-app --add-data "templates;templates" --windowed --onefile main.py ``` -------------------------------- ### Configure Custom Server with FlaskUI Source: https://context7.com/climentea/flaskwebgui/llms.txt Demonstrates how to integrate a custom server, such as Uvicorn, with FlaskUI by passing a custom server function and arguments. ```python from flaskwebgui import FlaskUI def custom_server(**kwargs): import uvicorn uvicorn.run(**kwargs) port = get_free_port() FlaskUI( server=custom_server, server_kwargs={"app": "main:app", "port": port}, width=800, height=600, ).run() ``` -------------------------------- ### Customize Browser Behavior and Flags Source: https://context7.com/climentea/flaskwebgui/llms.txt Shows how to specify custom browser paths, inject Chromium flags for kiosk mode, or define a full browser command for specific startup requirements. ```python from flaskwebgui import FlaskUI # Custom browser path FlaskUI(app=app, server="flask", browser_path="/usr/bin/chromium-browser", width=800, height=600).run() # Extra Chromium flags FlaskUI(app=app, server="flask", extra_flags=["--disable-gpu", "--kiosk"], width=800, height=600).run() # Full custom browser command FlaskUI(app=app, server="flask", browser_command=["/path/to/chrome", "--app=http://127.0.0.1:5000"]).run() ``` -------------------------------- ### Integrate Django with FlaskWebGUI Source: https://context7.com/climentea/flaskwebgui/llms.txt Shows how to configure a Django project as a desktop app. Requires specific middleware for static file serving and a dedicated entry point script. ```python # gui.py - place next to manage.py from flaskwebgui import FlaskUI from myproject.wsgi import application as app if __name__ == "__main__": FlaskUI( app=app, server="django", width=1200, height=800, ).run() ``` ```python # settings.py - required configuration import os STATIC_URL = "static/" STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")] STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") MIDDLEWARE = [ "whitenoise.middleware.WhiteNoiseMiddleware", # ... other middleware ] ``` -------------------------------- ### Lifecycle Hooks and Auto-Close Source: https://context7.com/climentea/flaskwebgui/llms.txt Manages application startup/shutdown events and server persistence. ```APIDOC ## Lifecycle Hooks ### Description Defines functions to execute during application lifecycle events. ### Parameters - **on_startup** (callable) - Optional - Function called when the app starts. - **on_shutdown** (callable) - Optional - Function called when the app closes. - **auto_close** (bool) - Optional - If False, the server remains running after the browser window is closed. ``` -------------------------------- ### Run Flask-SocketIO Application as Desktop GUI Source: https://github.com/climentea/flaskwebgui/blob/master/README.md Shows how to integrate Flask-SocketIO with FlaskUI to maintain real-time communication in a desktop window. ```python from flask import Flask, render_template from flask_socketio import SocketIO from flaskwebgui import FlaskUI app = Flask(__name__) socketio = SocketIO(app) if __name__ == '__main__': FlaskUI(app=app, socketio=socketio, server="flask_socketio", width=800, height=600).run() ``` -------------------------------- ### Package FlaskWebGUI with PyInstaller Source: https://github.com/climentea/flaskwebgui/blob/master/README.md Commands to bundle a Python web application into a single executable file. The first command creates a basic executable, while the second demonstrates how to include static assets and templates. ```shell pyinstaller -w -F main.py ``` ```shell pyinstaller --name your-app-name --add-data "dbsqlite:dbsqlite" --add-data "templates:templates" --add-data "static:static" --collect-all name_of_package_that_pyinstaller_did_not_found gui.py ``` -------------------------------- ### Distribution with PyInstaller Source: https://context7.com/climentea/flaskwebgui/llms.txt Packaging the application into a standalone executable. ```APIDOC ## PyInstaller Packaging ### Description Commands to bundle the application into a single executable file. ### Command Example pyinstaller --name my-desktop-app --add-data "templates:templates" --windowed --onefile main.py ``` -------------------------------- ### Manage Lifecycle Hooks and Auto-Close Source: https://context7.com/climentea/flaskwebgui/llms.txt Implements startup and shutdown hooks for resource management and controls whether the server process terminates when the browser window is closed. ```python from flaskwebgui import FlaskUI def on_startup(): print("Starting...") def on_shutdown(): print("Shutting down...") FlaskUI(app=app, server="flask", on_startup=on_startup, on_shutdown=on_shutdown).run() # Keep server running after browser closes FlaskUI(app=app, server="flask", auto_close=False).run() ``` -------------------------------- ### NiceGUI Integration with FlaskWebGUI Source: https://github.com/climentea/flaskwebgui/blob/master/README.md Shows how to integrate the NiceGUI framework with FlaskWebGUI. It defines a simple NiceGUI interface and then uses FlaskUI to run it, allowing for custom server configurations and window properties. ```python from flaskwebgui import FlaskUI from nicegui import ui ui.label("Hello Super NiceGUI!") ui.button("BUTTON", on_click=lambda: ui.notify("button was pressed")) def start_nicegui(**kwargs): ui.run(**kwargs) if __name__ in {"__main__", "__mp_main__"}: DEBUG = False if DEBUG: ui.run() else: FlaskUI( server=start_nicegui, server_kwargs={"dark": True, "reload": False, "show": False, "port": 3000}, width=800, height=600, ).run() ``` -------------------------------- ### Run Django Application as Desktop GUI Source: https://github.com/climentea/flaskwebgui/blob/master/README.md Configures a Django project to run via FlaskUI by importing the WSGI application. ```python from flaskwebgui import FlaskUI from djangodesktop.wsgi import application as app if __name__ == "__main__": FlaskUI(app=app, server="django").run() ``` -------------------------------- ### Browser Configuration Source: https://context7.com/climentea/flaskwebgui/llms.txt Customizes the browser environment, including paths, flags, and full command overrides. ```APIDOC ## Browser Configuration ### Description Allows fine-grained control over the browser instance used to display the web application. ### Parameters - **browser_path** (str) - Optional - Absolute path to the browser executable. - **extra_flags** (list) - Optional - List of command-line flags for the browser. - **browser_command** (list) - Optional - Full command list to launch the browser. - **app_mode** (bool) - Optional - If False, shows the browser address bar (Guest Mode). ``` -------------------------------- ### FlaskUI Configurations Source: https://github.com/climentea/flaskwebgui/blob/master/README.md Default parameters available for the FlaskUI class. ```APIDOC ## FlaskUI Configurations ### Description These are the default parameters you can use when initializing the `FlaskUI` class. ### Parameters - **server** (Union[str, Callable[[Any], None]]) - Function that receives `server_kwargs` to start the server. - **server_kwargs** (dict) - Keyword arguments passed to the `server` function. - **app** (Any) - The WSGI or ASGI application. - **port** (int) - Specify the port. If not available, a free port will be assigned. - **width** (int) - The width of the application window. - **height** (int) - The height of the application window. - **fullscreen** (bool) - Whether to start the app in fullscreen (maximized) mode. Defaults to `True`. - **on_startup** (Callable) - A function to execute before starting the browser and webserver. - **on_shutdown** (Callable) - A function to execute after the browser and webserver shutdown. - **extra_flags** (List[str]) - A list of additional flags for the browser command. - **browser_path** (str) - Path to the Chrome executable. If not provided, defaults will be used. - **browser_command** (List[str]) - Command line arguments to start Chrome in app mode. - **socketio** (Any) - SocketIO instance for use with `flask_socketio`. - **app_mode** (bool) - Whether to start the browser in app mode (without address bar). Defaults to `True`. - **browser_pid** (int) - Will be filled with the PID of the subprocess when the app starts. - **auto_close** (bool) - Determines if the server closes when the browser is closed. Defaults to `True`. ``` -------------------------------- ### Integrate FastAPI with FlaskWebGUI Source: https://context7.com/climentea/flaskwebgui/llms.txt Demonstrates wrapping a FastAPI application for desktop execution. It uses the FlaskUI class with the fastapi server parameter to manage the lifecycle of the web server and browser window. ```python from fastapi import FastAPI, Request from fastapi.responses import HTMLResponse from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates from flaskwebgui import FlaskUI, close_application app = FastAPI() app.mount("/static", StaticFiles(directory="static")) templates = Jinja2Templates(directory="templates") @app.get("/", response_class=HTMLResponse) async def root(request: Request): return templates.TemplateResponse("index.html", {"request": request}) @app.get("/api/data") async def get_data(): return {"message": "Hello from FastAPI desktop app"} @app.get("/close") async def close(): close_application() if __name__ == "__main__": FlaskUI( app=app, server="fastapi", width=1024, height=768, ).run() ``` -------------------------------- ### Configure FlaskUI Parameters Source: https://context7.com/climentea/flaskwebgui/llms.txt A comprehensive overview of the configuration options available for the FlaskUI class, including server settings, window dimensions, browser flags, and lifecycle hooks. ```python from flaskwebgui import FlaskUI FlaskUI( server="flask", server_kwargs=None, app=app, port=5000, socketio=None, width=800, height=600, fullscreen=True, app_mode=True, browser_path=None, browser_command=None, extra_flags=["--disable-gpu"], profile_dir_prefix="flaskwebgui", on_startup=lambda: print("Starting"), on_shutdown=lambda: print("Closing"), auto_close=True, ) ``` -------------------------------- ### Implement Flask Application with Lifecycle Control Source: https://context7.com/climentea/flaskwebgui/llms.txt Shows a Flask application that includes a programmatic way to close the desktop application using the close_application utility function. ```python from flask import Flask, render_template, request from flaskwebgui import FlaskUI, close_application app = Flask(__name__) @app.route("/") def home(): return render_template("index.html") @app.route("/submit", methods=["POST"]) def submit(): data = request.form.get("data") return render_template("result.html", data=data) @app.route("/close") def close(): close_application() return "Closing..." if __name__ == "__main__": FlaskUI( app=app, server="flask", width=800, height=600, ).run() ``` -------------------------------- ### Integrate Flask-SocketIO with FlaskWebGUI Source: https://context7.com/climentea/flaskwebgui/llms.txt Enables real-time communication in a desktop application using Flask-SocketIO. Requires passing the socketio instance to the FlaskUI constructor. ```python from flask import Flask, render_template from flask_socketio import SocketIO, emit from flaskwebgui import FlaskUI, close_application app = Flask(__name__) app.config["SECRET_KEY"] = "your-secret-key" socketio = SocketIO(app) @app.route("/") def index(): return render_template("index.html") @socketio.on("message") def handle_message(data): emit("response", {"data": f"Received: {data}"}) @app.route("/close") def close(): close_application() if __name__ == "__main__": FlaskUI( app=app, socketio=socketio, server="flask_socketio", width=800, height=600, ).run() ``` -------------------------------- ### Enable Guest Mode in FlaskUI Source: https://context7.com/climentea/flaskwebgui/llms.txt Configures the application to run in guest mode, which displays the browser address bar instead of the default app-only window mode. ```python from flaskwebgui import FlaskUI FlaskUI( app=app, server="fastapi", width=1024, height=768, app_mode=False, ).run() ``` -------------------------------- ### Close Application Programmatically Source: https://github.com/climentea/flaskwebgui/blob/master/README.md Import the close_application function to trigger a shutdown of the GUI window from within a route. ```python from flaskwebgui import FlaskUI, close_application ``` -------------------------------- ### Programmatically Close Application Source: https://context7.com/climentea/flaskwebgui/llms.txt Provides a mechanism to shut down the desktop application from within the web interface, terminating both the server and the browser window. ```python from flask import Flask from flaskwebgui import FlaskUI, close_application app = Flask(__name__) @app.route("/") def index(): return """

My Desktop App

Exit Application """ @app.route("/exit") def exit_app(): close_application() return "Goodbye!" if __name__ == "__main__": FlaskUI(app=app, server="flask").run() ``` -------------------------------- ### Custom Context Menu Implementation Source: https://github.com/climentea/flaskwebgui/blob/master/examples/fastapi-desktop/templates/index.html This script overrides the default browser context menu with a custom implementation. It provides basic copy and paste functionality while preventing the standard browser right-click menu. ```javascript document.addEventListener("contextmenu", function (e) { e.preventDefault(); const cursorX = e.clientX; const cursorY = e.clientY; const dropdown = document.createElement('div'); dropdown.style.position = 'absolute'; dropdown.style.left = `${cursorX}px`; dropdown.style.top = `${cursorY}px`; dropdown.style.color = 'black'; dropdown.style.backgroundColor = 'white'; dropdown.style.paddingTop = '5px'; dropdown.style.paddingBottom = '5px'; dropdown.style.paddingLeft = '10px'; dropdown.style.paddingRight = '10px'; dropdown.style.cursor = 'pointer'; const copyItem = document.createElement('div'); copyItem.textContent = 'Copy'; dropdown.style.marginBottom = '5px'; copyItem.addEventListener('click', async () => { try { const textToCopy = document.selection.createRange().text; alert(textToCopy) await navigator.clipboard.writeText(textToCopy); dropdown.remove(); } catch (error) { console.error(`Error copying to clipboard: ${error}`); } }); dropdown.appendChild(copyItem); const pasteItem = document.createElement('div'); pasteItem.textContent = 'Paste'; dropdown.style.marginBottom = '5px'; pasteItem.addEventListener('click', async () => { try { const clipboardText = await navigator.clipboard.readText(); console.log(`Pasted text: ${clipboardText}`); dropdown.remove(); } catch (error) { console.error(`Error pasting from clipboard: ${error}`); } }); dropdown.appendChild(pasteItem); document.body.appendChild(dropdown); }); ``` -------------------------------- ### Disable F12 Developer Tools Source: https://github.com/climentea/flaskwebgui/blob/master/examples/fastapi-desktop/templates/index.html This snippet intercepts the keydown event to prevent the F12 key from opening browser developer tools. It ensures a more controlled environment for desktop-wrapped web applications. ```javascript document.onkeydown = function (e) { if (e.key === "F12") { e.preventDefault(); } }; ``` -------------------------------- ### Preventing Browser Console Access Source: https://github.com/climentea/flaskwebgui/blob/master/README.md JavaScript code to prevent users from opening the browser console (e.g., by pressing F12 or using right-click). ```APIDOC ## Prevent Browser Console Access ### Description Add the following JavaScript snippet to your `index.html` file to disable the F12 key and right-click context menu, preventing users from opening the browser console. ### Method N/A (Client-side JavaScript) ### Endpoint N/A ### Parameters None ### Request Example ```html ``` ### Response N/A ``` -------------------------------- ### Prevent Browser Console Access with JavaScript Source: https://github.com/climentea/flaskwebgui/blob/master/README.md This JavaScript code snippet prevents users from opening the browser's developer console by disabling the F12 key and the right-click context menu. It's intended to be added to an index.html file. ```javascript ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.