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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.
0

You can try with relative imports

from ..app import create_app

4 Comments

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
"no known parent package" do you have the init.py file in the package folder? stackoverflow.com/questions/448271/what-is-init-py-for
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.
@alec_djinn Since Python 3.3 which was released in 2012, init files are no longer necessary. Have a look at peps.python.org/pep-0420

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.