OSError : Job token is not initialized

I try to connect to DFoundations trough GeoLib. My worker seems to be connecting (green tick in the app). But I get the following error when I try to execute:

File "viktor/external/external_program.pyx", line 494, in viktor.external.external_program.ExternalProgram.execute
OSError: Job token is not initialized

My code looks like this:

from pathlib import Path
from viktor.core import File
import geolib.models.dfoundations as df
from viktor.external.dfoundations import DFoundationsAnalysis

model = df.DFoundationsModel()
... create model ...
file = File() 
path = Path(file.source)  
input_file = model.serialize(path)  
df_analysis = DFoundationsAnalysis(input_file=input_file)
df_analysis.execute()  # Error occurs here

The problem seems to be that I tried to take a shortcut, and run a script directly. Therefore it ran before the platform was ready for it. Moving it inside a function to be called in the controller seems to have fixed it

1 Like

Indeed. When you try to start a VIKTOR application, it first imports all app-code and afterwards initializes the rest of the system (e.g. connecting to the VIKTOR Platform). That means that, when there is a bare python script (lines of code that are not placed inside a function or a class), and the python file containing this script is imported, that code is executed immediately.

The error message shows that the Job token is not initialized which makes sense, because this will only be initialized after all app-code is imported and the rest of the system is being initialized.

As described in the solution, moving the code inside a function solves the problem, as it prevents the code from being executed before the initialization of the rest of the system.

1 Like

This error pops up when ‘Victor’ code is run outside the platform framework, for example in tests. In tests this can be bypassed by mocking functions with Victor api calls using the unit test Mock functionality.