Import Pages after app = Dash() instantiation

Hello everyone,

I have this app repository folder organization:

\
   _init_.py
   app.py
   \pages
     page1.py
     page2.py

in app.py I have of th app instantiation and cache setting:

dash_app =
Dash(
name,
use_pages=True,
pages_folder =str((Path(file).parent / ‘pages’).absolute()),
assets_folder= str((Path(file).parent / ‘assets’).absolute()),
prevent_initial_callbacks = True,
suppress_callback_exceptions = True,
external_stylesheets=[themes.BOOTSTRAP]
)

cache = Cache(dash_app.server, config={
‘CACHE_TYPE’: ‘FileSystemCache’,
‘CACHE_DIR’: ‘cache-directory’
})

and a cache function below the code above:

@cache.memoize(timeout=CACHE_TIMEOUT)
def compute_data():

   return data

In pages\page1.py I rgister the page of course but then I would also want to import and use the function compute data.

I am struggling to make it work because i has ImportError caused by the thing that in app = Dash() all the pages are imported but the function `compute_data()´ is not yet defined,
so I get a final

ImportError cannot import compute_data from partially initialized module

Did it ever happened to you a similar multipage app an functions design?
Do someone have any sugestion on how to achieve possibility to use in pages callback functions defined in app.py?

My idea would have been to init pages after the app= Dash() instantiation but at the moment it is not possible and if I implement modifications on a dash package fork, I thought I would lose all or I would have to manage all the future updates on the dash package.

Many thanks,
Nick

Hi @nicfior

Have you tried using the Background callbacks
You can find an example with multi-page apps here (See #4)

Otherwise, you could try defining the cache in a separate file then importing it. If you use dash.get_app() it’s a function that will get the app defined in app.py file

cache.py

import dash

app= dash.get_app()
cache = Cache(dash_app.server, config={
    'CACHE_TYPE': 'FileSystemCache',
    'CACHE_DIR': 'cache-directory'
})
1 Like

Hello @AnnMarieW,

I’m still finding hard using functions with @cache decorator cause the cache definition needs app rference defined.
But at pages importing the app is not yet defined in Dash so the get_app() call returns

Exception: 
App object is not yet defined.  `app = dash.Dash()` needs to be run
before `dash.get_app()` is called and can only be used within apps that use
the `pages` multi-page app feature: `dash.Dash(use_pages=True).

`dash.get_app()` is used to get around circular import issues when Python files
within the pages/` folder need to reference the `app` object`

Correct me if I’m wrong.

So I think I will go with background callbacks as it fits better in multipage apps.

Thanks,
Nick