Python API: Server.py
This page is generated automatically from Server.py during docs builds.
Module Overview
QGas – Interactive Map Interface
================================
Academic Software Description
-----------------------------
This application provides an interactive web-based visualization interface for
European gas pipeline infrastructure data. The system serves processed pipeline
network data through an integrated web server with real-time updates.
Key Functionalities
-------------------
- Interactive web-based visualization with Folium mapping interface
- Local HTTP server for serving map data
- Data caching and compression for optimized performance
- Manual change management for pipeline data
Technical Implementation
------------------------
The system uses a tkinter-based GUI with an integrated HTTP server for serving
interactive maps. Data is cached in memory for performance and can be updated
through the web interface.
Development Information
------------------------
- Authors: Marco Quantschnig, Yannick Werner, Sonja Wogrin and Thomas Klatzer
- Institution: Institute of Electricity Economics and Energy Innovation (IEE), Graz University of
Technology, Inffeldgasse 18, Graz, 8010, Austria
- License: See LICENSE file
- Disclaimer: AI-assisted tools were used to support development and documentation.
Inputs
------
- Runtime environment: Python 3.x with Tkinter.
- Local project folders (Input/ and related assets).
- Map HTML entry point: GUI.html served over the local HTTP server.
Classes
CombinedGUI
Methods (28)
__init__(root)
Initialize the QGas application GUI. Configures the main window geometry, determines the application base path (supporting both script and PyInstaller frozen-exe execution), initializes the HTTP server state variables, and builds all UI widgets.
| Parameter | Type | Description |
|---|---|---|
root | tk.Tk | The root Tkinter window instance created by ``main()``. |
ensure_directories()
Create any missing required directories for the application. Since we now use Input project folders, Output directories are no longer needed.
create_widgets()
Create the main GUI layout with the QGas Interactive Map interface. Modern design with logo and tile-based layout optimized for larger window.
create_header(parent)
Create the header section with logo, application title, and LED server-status indicator. Attempts to load ``Images/QGas_Logo.png`` (requires Pillow); falls back to a text emoji placeholder if the image is unavailable. The LED indicator in the top-right corner is updated by ``update_status()`` whenever the server state changes.
| Parameter | Type | Description |
|---|---|---|
parent | tk.Frame | Parent container frame that the header is packed into. |
create_control_tiles(parent)
Create the tile-based control interface with Start, Open Map, and Stop action tiles. Arranges three action tiles in a responsive 3-column grid (row 0) and an information tile spanning all columns below (row 1). Row weights are set so action tiles receive three times more vertical space than the info tile.
| Parameter | Type | Description |
|---|---|---|
parent | tk.Frame | Parent container frame for the tile grid. |
create_action_tile(parent, title, description, icon, button_text, command, color, row, column)
Create a single action tile widget and place it in the given grid cell. Each tile contains a large emoji icon, a heading, a short description and a colored action button. Hover effects darken the button color using ``darken_color()``.
| Parameter | Type | Description |
|---|---|---|
parent | tk.Frame | Parent grid container. |
title | str | Heading text displayed inside the tile. |
description | str | Longer description text shown below the heading. |
icon | str | Unicode emoji used as the tile icon (e.g. ``"🚀"``). |
button_text | str | Label text of the action button. |
command | callable | Callback invoked when the button is clicked. |
color | str | Hex color code for the button background (e.g. ``"#28a745"``). |
row | int | Grid row index for tile placement. |
column | int | Grid column index for tile placement. |
create_info_tile(parent)
Create the compact information tile that spans all three columns. Displays static server metadata in a 3-column grid: map file name, HTTP port, server URL, working directory, and a feature summary.
| Parameter | Type | Description |
|---|---|---|
parent | tk.Frame | Parent container whose grid row 1 receives the tile. |
darken_color(color)
Utility function to darken colors for hover effects
| Parameter | Type | Description |
|---|---|---|
color | str | Hex color code |
Returns: str — Darker version of the color
update_status(status, is_running=False)
Update the header LED indicator to reflect server status
| Parameter | Type | Description |
|---|---|---|
status | str | Status text (e.g., "Running", "Stopped") |
is_running | bool | True if server is running, False otherwise |
create_map_tab(parent)
Legacy method for map tab creation Now handled by create_widgets for unified interface
start_server()
Start the HTTP server for map visualization
Features:
- Serves static files (HTML, JS, CSS)
- Provides API endpoints for dynamic data
- Handles GeoJSON with compression
- Dynamic project path routing
show_project_selection_after_start()
Scan the ``Input/`` folder and auto-select or prompt for a project after server start. If only one sub-folder exists it is selected automatically. If multiple folders exist the user is shown the project selection dialog. Falls back to ``"Standard"`` on any error.
get_cached_layer_data(layer_name, bbox=None)
Load layer data with caching and optional bounding box filtering
| Parameter | Type | Description |
|---|---|---|
layer_name | str | Name of the layer to load |
bbox | str, optional | Bounding box string "minX,minY,maxX,maxY" |
Returns: dict — GeoJSON FeatureCollection
filter_data_by_bbox(geojson_data, bbox_str)
Filter GeoJSON data by bounding box for viewport optimization
| Parameter | Type | Description |
|---|---|---|
geojson_data | dict | GeoJSON FeatureCollection |
bbox_str | str | Bounding box "minX,minY,maxX,maxY" |
Returns: dict — Filtered GeoJSON FeatureCollection
update_layer_feature(layer_name, feature)
Update a feature in the layer data Note: Currently logs the update. Extend this method to persist changes to files or database as needed.
| Parameter | Type | Description |
|---|---|---|
layer_name | str | Name of the layer |
feature | dict | Updated GeoJSON feature |
Returns: bool — True if update was successful
stop_server()
Stop all running servers and cleanup resources
Actions:
- Shutdown HTTP server
- Clear data cache
- Reset UI status
- Reset selected project
open_browser()
Open the interactive map in web browser with project selection
Features:
- Project selection dialog before opening
- Automatic URL parameter injection with selected project
- Preference for Microsoft Edge browser
- Fallback to default browser if Edge unavailable
select_project()
Show project selection dialog if multiple projects exist
Returns: bool — True if project selected or default used, False if cancelled
show_project_selection_dialog(projects)
Display a modal project-selection dialog with a dropdown and project-creation support. Defaults to ``"Standard"`` in the dropdown if that folder exists. The dialog also exposes a *Create New Project* button that calls ``prompt_new_project_dialog()`` before returning.
| Parameter | Type | Description |
|---|---|---|
projects | list[str] | Sorted list of available project folder names. |
Returns: str | None — The selected or newly created project name, or ``None`` if the user cancelled the dialog.
prompt_new_project_dialog(parent, projects)
Show a secondary modal dialog to collect a new project name and create it on disk. Validates the name with ``validate_project_name()`` and then calls ``create_project_from_template()`` to scaffold the folder structure.
| Parameter | Type | Description |
|---|---|---|
parent | tk.Toplevel | Parent dialog window used as the transient owner. |
projects | list[str] | Existing project names used for duplicate detection. |
Returns: str | None — The validated new project name on success, or ``None`` if the user cancelled or validation failed.
validate_project_name(name, projects)
Validate a proposed project name against Windows filesystem and uniqueness rules. Checks for empty input, forbidden characters (``< > : / \ | ? * "``), reserved names (``"."`` / ``".."``), trailing spaces or dots, and case-insensitive duplicates in *projects*. Displays an error dialog for each violation.
| Parameter | Type | Description |
|---|---|---|
name | str | Raw name string entered by the user. |
projects | list[str] | Existing project folder names for duplicate checking. |
Returns: str | None — The validated name if all checks pass, ``None`` otherwise.
create_project_from_template(project_name)
Scaffold a new project folder under ``Input/`` with minimal required files. Creates ``Input/<project_name>/`` and populates it with: - ``PL_Pipelines.geojson`` — empty feature collection (schema from Standard) - ``N_Nodes.geojson`` — empty feature collection (schema from Standard) - ``config.xlsx`` — minimal configuration workbook - ``license.txt`` — empty placeholder
| Parameter | Type | Description |
|---|---|---|
project_name | str | Validated name for the new project folder. |
Returns: bool — ``True`` if the project was created successfully, ``False`` on error.
write_empty_geojson(template_path, dest_path)
Write an empty GeoJSON FeatureCollection to *dest_path*. Preserves the ``name`` and ``crs`` fields from *template_path* if it exists; otherwise writes a minimal FeatureCollection whose ``name`` is derived from the destination filename stem.
| Parameter | Type | Description |
|---|---|---|
template_path | str | Path to an existing GeoJSON used as schema source. If the file does not exist, a bare FeatureCollection is created. |
dest_path | str | Absolute or relative output path for the new GeoJSON file. |
write_minimal_configuration_xlsx(dest_path)
Write a minimal OOXML ``.xlsx`` workbook to *dest_path* without requiring openpyxl. The workbook contains a single ``Input_Files`` sheet pre-populated with header row and two data rows (pipelines and nodes) matching the expected QGas configuration schema.
| Parameter | Type | Description |
|---|---|---|
dest_path | str | Absolute or relative path where the ``.xlsx`` file is written. |
update_map_paths(project_name)
Rewrite ``fetch()`` URLs in ``GUI.html`` to point to ``Input/<project_name>/``. First normalises any pre-existing ``Input/<old_project>/`` prefix to plain ``Input/`` (prevents double-nesting on repeated calls), then replaces all ``fetch('Input/`` occurrences with ``fetch('Input/<project_name>/``.
| Parameter | Type | Description |
|---|---|---|
project_name | str | Name of the project folder to activate in the map. |
reset_map_paths()
Revert all ``fetch('Input/<project>/``) URLs in ``GUI.html`` back to ``fetch('Output/``. Intended as a cleanup step when the application shuts down or when the user reverts to the legacy Output-folder layout.
clear_browser_cache()
Add or update a ``?v=<timestamp>`` cache-busting query parameter in ``GUI.html``. Scans all ``.geojson`` fetch URLs in the HTML and replaces or appends a ``v`` parameter set to the current Unix timestamp so the browser fetches fresh data on the next page load.
on_closing()
Handle application shutdown gracefully. Stops the map server if running and cleans up any background processes before closing the application window.
Module-level Functions
Functions (1)
main()
Main entry point for the QGas Interactive Map application. Initializes the Tkinter GUI, creates the application instance, and starts the main event loop. Includes error handling for startup issues.