0

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?

Michael Paccione
  • 2,467
  • 6
  • 39
  • 74

2 Answers2

1

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

Triceratops
  • 741
  • 1
  • 6
  • 15
  • Hi, thank you for this as it worked. I find it so obtuse though. Is this really the best solution in Python? Node comparatively makes this look like a lot to write for an import. – Michael Paccione Dec 08 '22 at 17:29
0

You can try with relative imports

from ..app import create_app
alec_djinn
  • 10,104
  • 8
  • 46
  • 71
  • I had mentioned relative imports didnt work. Here is the exact error: from ..app import create_app E ImportError: attempted relative import with no known parent package – Michael Paccione Dec 08 '22 at 17:25
  • "no known parent package" do you have the __init__.py file in the package folder? https://stackoverflow.com/questions/448271/what-is-init-py-for – alec_djinn Dec 09 '22 at 09:24
  • As far as I know Python 3.3+ doesn't need __init__ files for imports as it namespaces it automatically. I did play around with creating some empty ones and it did not resolve the issue. – Michael Paccione Dec 09 '22 at 19:48
  • @alec_djinn Since Python 3.3 which was released in 2012, init files are no longer necessary. Have a look at https://peps.python.org/pep-0420/ –  Dec 13 '22 at 11:03