Creating an object accessible from all sessions

I run a Bokeh server using the directory format. I would like to store an object that is defined once for the server and can be accessed by each session. Is it possible to do that? I know the on_server_loaded() function in the lifecycle hooks, but I don’t see how to create inter-session variables within that function.

In case more information about why I want this is desired: I use PySide6’s QTranslator() class for translations in my Bokeh app. When the user passes lang=jp as a URL parameter, in main.py I run:

lang = curdoc().session_context.request.arguments.get('lang')
if lang and lang[0].decode('utf-8') == 'jp':
    translator = QTranslator()
    translator.load('ja_JP.qm')
    QCoreApplication.installTranslator(translator)

This QCoreApplication objects stays constant between sessions (I create it via app = QCoreApplication() in app_hooks.py). So when the next user loads a session without lang=jp in the URL parameters, the language settings are still present. I need to uninstall the translator with:

QCoreApplication.removeTranslator(translator)

However, this requires the translator object I created in the prior session to still be accessible as an object. Unfortunately, pyside6 allows no way for the QCoreApplication to remove all present translator objects; they need to be stored and removed.

Oh, I think I realized the answer. In the on_server_loaded(server_context) function, I can add instance variables to the server_context object. Something like:

def on_server_loaded(server_context):
    server_context.translator = QTranslator()
    server_context.translator.load('ja_JP.qm')

Then the variable is available in main.py via curdoc().session_context.server_context.translator.

1 Like

The very simplest way is simply to utilize Python’s built-in module caching. Have on_server_loaded import and set up a module with some functions or module-level attributes. Then any session can import that module access those functions or attributes. See this example for a demonstration of that technique:

You can also attach things to the server_context as well, it’s just not common or very well demonstrated.

Thank you!

1 Like

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