1

I have a Python FastAPI project with two applications that can be run separately or at the same time. The structure is like this:

project/
  app_1/
    models/
      model_1.py
    file_1.py
    app_1.Dockerfile
  app_2/
    models/
      model_1.py
    file_1.py
    app_2.Dockerfile
  docker-compose.yaml

These applications/API's share some of the models and to avoid maintaining the same models in multiple locations, I'd like to move all models under the project/ -folder and import them from there.

If I want to import something from project/models/model_1.py in project/app_2/file_1.py, how can I do it? I've tried importing it from project.models.model_1 import Model but I get an error: ModuleNotFoundError: No module named 'project'. I also tried using dots like this: from ........project.models.model_1 import Model (Note: my real structure is more complicated than the example I've provided and that would be the real amount of dots to get to the top level). This gives me an error: ImportError: attempted relative import beyond top-level package.

Is it possible at all to do what I'm trying to do? If yes, how could I achieve it?

lr_optim
  • 299
  • 1
  • 10
  • 30
  • if it's more complicated than the example above, then consider looking at https://packaging.python.org/en/latest/guides/packaging-namespace-packages/. also note that there ain't any `__init__.py` in your structure example therefore no modules. `ImportError: attempted relative import beyond top-level package` probably means that you have too many dots. – aleksandarbos Nov 14 '22 at 10:30
  • Does this answer your question? [ModuleNotFoundError when trying to unpickle a model in Flask app](https://stackoverflow.com/questions/71303417/modulenotfounderror-when-trying-to-unpickle-a-model-in-flask-app) – Chris Nov 14 '22 at 10:38
  • Related answers can also be found [here](https://stackoverflow.com/a/73647164/17865804) and [here](https://stackoverflow.com/a/71080756/17865804). – Chris Nov 14 '22 at 10:39
  • Thank you @aleksandarbos and @Chris , I will look on to those answers. Should the `project/` -folder also be a python package? – lr_optim Nov 14 '22 at 10:48

0 Answers0