RuntimeError: No auth token found. Authentication Flow needed o365 python

I’m using a Linux machine to run a python script within the Linux terminal. If I open the terminal inside the directory that houses my python script then use python3 availableHoursReporting.py command the script runs without any issues.

However, if I open a terminal session outside of the directory that houses my python script then I get RuntimeError: No auth token found. Authentication Flow needed

The directory structure is as follows on my Linux machine:

/home/ubuntu/python_scripts/Available-Hours-Reporting-/

The ‘auth_token’ is stored within the Available-Hours-Reporting folder

Here is the relevant code:

import o365
from o365 import Account

credentials = ('xxxxxxxxx',)

account = Account(credentials, auth_flow_type = 'public')
account.connection.get_session(load_token = True)

Traceback:

Traceback (most recent call last):
  File "/home/ubuntu/python_scripts/Available-Hours-Reporting-/availableHoursReporting.py", line 27, in <module>
    account.connection.get_session(load_token = True)
  File "/home/ubuntu/.local/lib/python3.8/site-packages/O365/connection.py", line 563, in get_session
    raise RuntimeError('No auth token found. Authentication Flow needed')
RuntimeError: No auth token found. Authentication Flow needed

I’m new to Linux so I’m not sure If I’m totally misunderstanding the folder structures or if I’m using the terminal correctly to execute the .py script.

Answer

You have two ways to solve it.
method 1.

from o365.utils.token import FileSystemTokenBackend
tk = FileSystemTokenBackend(token_path="your token path", token_filename="filename")
account = Account(credentials, auth_flow_type = 'public',token_backend=tk)

method 2. not use an instance of FileSystemTokenBackend

account = Account(credentials, auth_flow_type = 'public',token_path="your token path", token_filename="filename")

You can find the details in the source code of “connection.py”. token_path should be a full absolute path.