Michael Paccione
Michael Paccione

Reputation: 2807

Cant import from file in python

I am running a Flask server in Docker and cannot import create_app from app.py into my integration tests. I've tried a variety of naming approaches but Python is unable to find app.py.

The directory structure is as follows

/server
   /test/integration/test.py
   app.py

test.py has this import

from app import create_app

I tried relative imports as well but there was a "parent" error. I then played around with empty __init__.py files in an attempt to use relative imports. That didn't work. I am not sure why this is so involved to do really. What is the solution for this?

Upvotes: 0

Views: 49

Answers (2)

alec_djinn
alec_djinn

Reputation: 10789

You can try with relative imports

from ..app import create_app

Upvotes: 0

Triceratops
Triceratops

Reputation: 813

In test.py add:

# some_file.py
import sys
# caution: path[0] is reserved for script path (or '' in REPL)
sys.path.insert(1, '/path/to/app/folder')
import app
from app import create_app

This add the directory of the source file to the system so Python will know to go there when searching the things to import. This is true when both files are local on your computer. If there is a server you need to see how you modify the in-server Python environment to know the folder of the app.py file.

See: Importing files from different folder

Upvotes: 1

Related Questions