0

Here's my directory structure:

python
 -main
  -api
   -__init__.py
 -tests
 -__init__.py
 -wsgi.py

wsgi contains the following code:

from .main import api


app = api.create_app()

if __name__ == '__main__':
    app.run(port=8080)

but, when I try to run the code I get the following error:

 Traceback (most recent call last):   File
 "/Users/unbp/projects/webservices/fund-distribution.webservice/python/wsgi.py",
 line 1, in <module>
     from .main import api ImportError: attempted relative import with no known parent package

The parent folder 'python' does contain __init__.py file, so it is a package, isn't it? It works fine with from main import api (without dot in front of main) Where am I going wrong?

ForceBru
  • 43,482
  • 10
  • 63
  • 98
Pritam Bohra
  • 3,912
  • 8
  • 41
  • 72
  • 1
    Does this answer your question? [Relative imports for the billionth time](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time) – yut23 Oct 20 '21 at 21:29
  • `main` folder does not contain a __init__.py – Ronnie Oct 20 '21 at 21:33
  • Its a package if its on the python path. You could cd above the "python" directory and now "python" is the package. You could write a setup.py and make this thing installable. Python follows the same model as a C program. Executables in PATH (a python script) and shared modules in a library path. – tdelaney Oct 20 '21 at 21:51

1 Answers1

0

I'm still new to python so take this with a grain of salt, when doing:

from [filename/module/library/etc] import [something]

you're importing a specific part of the library which is the first call in the line (so .main)

app = api.create_app()

is treating "api" as the library and calling "create_app()" as a function within the "api" module.

If api is the library, do this instead:

import api

and it should work, if create_app() is the function and api is your library do

from api import create_app()

app = create_app()

if __name__ == '__main__':
    app.run(port=8080)

You no longer have to specify the file because you've already declared it and can just call the function as if it were already written into your script. I hope I didn't botch my terminology, but that should resolve your issue.

edit*** I realized I read your original post wrong, you can't call a folder the way you're trying to do, what I wrote above should explain why which is why I'm not deleting it.

to solve your issue, you need to adjust your pathing, do

import sys
sys.path.insert(0, 'api')

from _init_ import create_app()

app = create_app()

if __name__ == '__main__':
    app.run(port=8080)

What this is doing is using the sys module to append the pathing to the folder so that the interpreter is able to find the file you want to reference and call the function.

Tanner Burton
  • 69
  • 1
  • 9