Open Plotly graph, when python server is running in a Docker - Stack Overflow

admin2025-04-15  0

I have a flask app that is communicating with my UI via webSockets, at the end of one of my functions, I need to display a plotly graph. Everything works fine until when my project is running locally from terminal. When I uploaded my python project in a container the plotly does not open a new tab inside my browser and I cannot manually open it because plotly always opens up in a new port. My question is.. how can I make plotly open a new tab while running inside a docker.

docker config:

# Use an official Python runtime as a parent image
FROM python:3.11.1

# Set the working directory inside the container
WORKDIR /app

# Copy only the Backend folder into the container
COPY Backend /app

# Install dependencies
RUN pip install --no-cache-dir -r requirements.txt

# Expose the port Flask runs on
EXPOSE 8001 8050 62079

# Run Flask app
CMD ["python", "app.py"]
"""Flask Application"""

from flask import Flask
from flask_socketio import SocketIO, emit
from serviceswork_monitoring import (disable_port)

app = Flask(__name__)

# Enable usage of websockets
socketio = SocketIO(cors_allowed_origins="*", async_mode="threading")
socketio.init_app(app)

# ---- Helper Functions ----- #
def is_any_none(*args):
    """Checks if any of the element is none"""

    return any(arg is None or arg == "" for arg in args)

# ----- Endpoints ----- #

@socketio.on("/enablePort")
def enable_snmp_port(data):
    """Enable port"""

    ip_target = data["data"].get("ipTarget", None)
    community = data["data"].get("community", None)
    port_to_enable = data["data"].get("portToEnable", None)

    if is_any_none(ip_target, community, port_to_enable):
        emit("error", {"smallTerminalError": "Invalid IP, community or portToEnable"})
    else:
        enable_port(socketio, ip_target, community, port_to_enable)
# ----- Socket Consumer ----- #
@socketio.on('connect')
def handle_connect():
    """Handles connecting to WebSocket"""

    print("WebSocket client connected")
    emit('connection', {"connection": "Connected to WebSocket!"})

@socketio.on('disconnect')
def handle_disconnect():
    """Handles disconnecting to WebSocket"""

    print("Disconnection WebSocket client")
    emit('connection', {"connection": "Disconnected from WebSocket!"})

if __name__ == '__main__':
    socketio.run(app, host="0.0.0.0", debug=True, port=8001)

and if it matters here is my plotly function:

def plot_graph():
    print("PLOTLY ENTERED")

    # Create a subplot with 4 rows and 1 column
    fig = make_subplots(
        rows=4, cols=1,
        shared_xaxes=True,
        vertical_spacing=0.1,
        subplot_titles=[
            'In Errors', 
            'Out Errors', 
            'In Traffic (Mbps)', 
            'Out Traffic (Mbps)'
        ]
    )

    # In Errors Bar Plot
    fig.add_trace(
        go.Bar(
            x=portsw,
            y=in_errors,
            name='InError',
            marker=dict(color='blue'),
            text=[str(f(val)) for val in in_errors],
            textposition='outside'
        ),
        row=1, col=1
    )

    # Out Errors Bar Plot
    fig.add_trace(
        go.Bar(
            x=portsw,
            y=out_errors,
            name='OutError',
            marker=dict(color='skyblue'),
            text=[str(f(val)) for val in out_errors],
            textposition='outside'
        ),
        row=2, col=1
    )

    # In Mbps Bar Plot
    fig.add_trace(
        go.Bar(
            x=portsw,
            y=in_mbits,
            name='InMbps',
            marker=dict(color='green'),
            text=[str(f(val)) for val in in_mbits],
            textposition='outside'
        ),
        row=3, col=1
    )

    # Out Mbps Bar Plot
    fig.add_trace(
        go.Bar(
            x=portsw,
            y=out_mbits,
            name='OutMbps',
            marker=dict(color='orange'),
            text=[str(f(val)) for val in out_mbits],
            textposition='outside'
        ),
        row=4, col=1
    )

    # Update layout for the entire figure
    fig.update_layout(
        title=f'{ip_target} - ({a[1]})',
        height=1000,
        showlegend=True,
        title_x=0.5,
        xaxis_title='Ports',
        yaxis_title='Values',
    )

    # Update y-axes for each subplot
    fig.update_yaxes(title_text="vh", row=1, col=1)
    fig.update_yaxes(title_text="izh", row=2, col=1)
    fig.update_yaxes(title_text="vht", row=3, col=1)
    fig.update_yaxes(title_text="izht", row=4, col=1)

    # Show the figure
    fig.show()
转载请注明原文地址:http://www.anycun.com/QandA/1744713064a86582.html