Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python import from parent directory for dockerize structure

I have a project with two applications. They both use a mongo-engine database model file. Also they have to start in different Docker containers, but use the same Mongo database in the fird container. Now my app structure looks like this:

app_root/
   app1/
      database/
         models.py
      main.py
   app2/
      database/
         models.py
      main.py

And it works fine, BUT I have to support two same files database/models.py. I dont want to do this and I make the next structure:

app_root/
   shared/
      database/
         models.py
   app1/
      main.py
   app2/
      main.py

Unfortunately it doesnt work for me, because when I try this in my main.py:

from ..shared.database.models import *

I get

Exception has occurred: ImportError 
attempted relative import with no known parent package

And when I try

from app_root.shared.database.models import *

I get

Exception has occurred: ModuleNotFoundError No module named 'app_root'

Please, what do I do wrong?

like image 935
Slovo Avatar asked Jan 19 '26 19:01

Slovo


1 Answers

In the file you perform the import, try adding this:

import os
import sys
sys.path.append(os.path.abspath('../../..'))

from app_root.shared.database.models import *
like image 123
0buz Avatar answered Jan 21 '26 09:01

0buz