Updating Bokeh Plots in Django After Database Changes: Best Practices and Solutions

I embed an autoload script within my Django template which works great. Its several plots with data aggregated from a database. However the database is currently updated via “regular django views” outside my bokeh app and i would like to update my bokeh plot when i update the data in the database.

bokeh_apps = [
    autoload("duty_cycle_plot", apps_path / "DutyCycleVisualizer.py"),
]

# from my django view:
    script = server_document(request._current_scheme_host + "/duty_cycle_plot")

Currently i have a button on my bokeh app that updates the the datasource. Is there an instance related to the served document i could use within my django backend and update this data source automatically after doing changes to the database?

My hypothetical solution is i could use websockets create a sessions that provides the serve_document autoload script and keeps the instance being served so i can modify the data being plotted.

What are my options here?

An approach might be to to create a session when the client connects and i could embed this session with server_session.

def server_session(model: Model | None = None, session_id: ID | None = None, url: str = "default",
        relative_urls: bool = False, resources: Literal["default"] | None = "default", headers: dict[str, str] = {}) -> str:
    ''' Return a script tag that embeds content from a specific existing session on
    a Bokeh server.

    This function is typically only useful for serving from a a specific session
    that was previously created using the ``bokeh.client`` API.

My immediate thought would be something like this, just for testing and playing around:

def sea_surface(request: HttpRequest) -> HttpResponse:
    # Define the custom session ID
    custom_session_id = "default"

    # Connect to the Bokeh server
    session = pull_session(
        url=request.build_absolute_uri(), session_id=custom_session_id
    )

    # Generate the script to embed the session
    script = server_session(
        session_id=custom_session_id, url=request.build_absolute_uri()
    )

    print(session.id)

    return render(request, "embed.html", dict(script=script))

This gives an error:

WebSocket HANDSHAKING /sea-surface-temp/ws [127.0.0.1:39052]
WebSocket CONNECT /sea-surface-temp/ws [127.0.0.1:39052]
Could not create new server session, reason: io_loop should already been set

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.