Forums

ModuleNotFoundError: Trying to import functions from local module that will execute as scheduled task

Sorry if this question sounds stupid as this is my first time using PythonAnywhere. The answer may seem obvious but I cannot help myself. If any bright minds here can help me, I would be really grateful to them.

I have a python script that is assigned to Scheduled Task. It is importing the functions from its sibling directory by accessing the parent directory as follows:

|_app
  |_products
    |_controllers.py => defines method delete_products, insert_products
  |_cron
    |_ __init__.py => from app.products.controllers import delete_products, insert_products

The script in question that is assigned to Scheduled Task is app/cron/__init__.py. It is throwing the error as below:

Traceback (most recent call last):
  File "/home/flask_app/flask_app_backend/app/cron/__init__.py", line 7, in <module>
    from app.products.controllers import delete_products, insert_products
ModuleNotFoundError: No module named 'app'

Is there anything I am missing?

You should add path to the app module to the PATH (you can use sys.path.append in Python, like it's used in our wsgi files).

I have added a path to the app module to the PATH in some_project_pythonanywhere_com_wsgi.py as:

path = '/home/some_project/some_project_backend'
app_path = path + '/app'
if path not in sys.path:
    sys.path.append(path)
    sys.path.append(app_path)

from app import app as application  # noqa

Is this the way the above answer expects me to add the path? However, it throws me the same error as mentioned in the question. Apologies if I interpreted the solution wrong.

Just to clarify, you need to put that code into the file that you are running as a scheduled task -- not into the WSGI file. The WSGI file is only used when running your code inside your website. I'd also recommend only adding the value that you have in your variable path to the sys.path -- not the one you have in app_path.