1

I need to access some functions form create_database.py from my app.py file. Is this possible?

This is structure of my folder:

application
├── database
│   └── create_database.py
└── microservice
    └── app.py

I was looking for solution and only found two codes that could help me but they didn't work for me.

  1. sys.path.append('path/to/folder') and than import create_database.py. If i got this right it should work with full path but I need to be able to work with relative path since this app is going to be dockerized on server.

  2. from database.create_database import User this throws ModuleNotFoundError: No module named 'database' here I also tried to create empty __init__.py in database folder but that also didn't help.

wondergrandma
  • 103
  • 1
  • 12
  • If app.py is used as a script (`python app.py`), try moving it up one level instead of having it inside `microservice`. Or run app.py as a module (from the `application` directory), via `python -m microservice.app`. Getting imports right can sometimes be a bit tricky. Your issue seems similar to the problem that prompted this popular question: https://stackoverflow.com/q/14132789/407651. – mzjn Apr 08 '23 at 12:43
  • @mzjn I was trying to avoid it but eventually I found out that this is probably the only option. But it took some time to rethink whole structure of files because it's way more complicated than the example. But moving `app.py` one level up seems like only possible option. – wondergrandma Apr 08 '23 at 13:22

2 Answers2

0

Try this in the empty __init__.py file:

from .create_database import User
__all__ = ["User"]

Then you should be able to import User in your current file as such:

from .database import User

I hope this helped. For clarification app.py is only ran from its directory right? Its not called in another script at different location.

Oliver
  • 41
  • 7
  • So I tried it but it still throws `ModuleNotFoundError: No module named 'database'`. The _app.py_ just stores my functions they are called from file where are my API endpoints described. But I tried to run that function in the same file where it is declared but it still throws that same error. – wondergrandma Apr 08 '23 at 11:38
-1

The following code to perform a relative system path change will work when python app.py is called from the microservice folder.

import sys

# Import create_database function from ./../database/create_database.py
# Since this is the root of the project, accessing other modules will be more straightforward.
sys.path.append('./../')

from database.create_database import User
SaptakD625
  • 89
  • 4
  • Never mess with `sys.path` unless you're absolutely sure what you're doing, especially don't put a relative path there like here. – AKX Apr 08 '23 at 14:45