最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览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()
发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>